robustcov is a research-oriented Python/C++ package for robust covariance and scatter estimation, SPD geometry, anomaly diagnostics, and robust kernel/similarity workflows.
It is designed for workflows where ordinary covariance estimates become unstable: contaminated samples, heavy-tailed data, small-sample regimes, high-dimensional scatter estimation, Mahalanobis-style anomaly screening, covariance drift monitoring, and robust input-metric construction for kernel or similarity methods.
The package combines a Python API with C++/pybind11 kernels for selected compute-heavy routines. The focus is practical robust scatter estimation, diagnostic reporting, SPD geometry utilities, robust input metrics, benchmark galleries, and application-oriented examples. It is not intended to be a full probabilistic modeling framework or a replacement for general-purpose machine-learning libraries.
robustcov is independently maintained volunteer open-source research software released under the Apache-2.0 license.
python -m pip install robustcov
import numpy as npimport robustcov as rcrng = np.random.default_rng(0)# Heavy-tailed data with injected outliersX = rng.standard_t(df=3, size=(400, 5))X[:30] +=8.0est = rc.FastMCD(quality="balanced", random_state=42).fit(X)print(est.location_)print(est.covariance_)print(est.radial_kurtosis_)det = rc.RobustOutlierDetector( estimator=est, contamination=0.075,).fit(X)print(det.labels_)
Motivation
Classical covariance is highly sensitive to outliers and heavy tails. A small number of extreme observations can inflate covariance estimates, rotate principal directions, distort Mahalanobis distances, and hide the very anomalies one wants to detect.
This is especially visible in settings such as:
fraud screening;
sensor anomaly detection;
portfolio stress diagnostics;
biomedical feature screening;
network traffic monitoring;
image or text embedding outlier detection;
small-sample, high-dimensional scientific data;
covariance drift monitoring;
robust input metrics for kernel and similarity workflows.
robustcov provides robust covariance and scatter estimators that try to separate central structure from contamination or diffuse heavy tails. The resulting robust geometry can then be used for diagnostics, anomaly scores, plots, benchmark comparisons, SPD-matrix comparisons, and robust kernel or similarity methods.
What the package does
The package currently focuses on six related tasks:
robust covariance estimation under contamination;
heavy-tail scatter estimation for small-sample or high-dimensional data;
robust-distance anomaly detection and diagnostic reporting;
SPD geometry for covariance and scatter matrices;
robust input metrics for kernel, Gaussian-process, and similarity workflows;
reproducible benchmark and use-case galleries.
Main public APIs include:
FastMCD;
MinCovDet;
RegularizedTyler;
StudentTScatter;
RegularizedCauchy;
KLRegularizedTyler;
WieselTyler;
HellingerRegularizedTyler;
AutoRobustScatter;
RobustOutlierDetector;
AutoRobustAnomalyDetector;
ClusterRobustOutlierDetector;
RobustMedianImputer;
robustcov.geometry;
robust metric and kernel helpers;
sklearn-style and GPyTorch-style kernel adapters;
plotting and diagnostic helpers.
The package is not intended to be a replacement for scikit-learn, SciPy, or GPyTorch. It is narrower: robust covariance, robust scatter, robust geometry, robust distances, and input-metric tools for interpretable diagnostics and ML workflows.
Robust distances
Most workflows are built around robust squared Mahalanobis distances. Given observations
Large robust distances indicate observations that are far from the estimated central elliptical structure.
This idea is simple, but the quality of the result depends heavily on the covariance estimate. If the covariance is fitted using all outliers, then the distances may be distorted. robustcov focuses on estimators that are less sensitive to this failure mode.
SPD geometry and robust similarity
A fitted robust scatter estimate gives more than a covariance matrix. It defines geometry on the cone of symmetric positive-definite matrices and a robust geometry on the input space.
The robustcov.geometry module includes utilities for SPD matrix normalization, matrix powers, matrix logarithms and exponentials, affine-invariant distance, log-Euclidean distance, geodesic interpolation, and Tyler fixed-point diagnostics.
This is useful for covariance drift monitoring, estimator stability diagnostics, robust whitening, comparing empirical and robust scatter, and embedding or nearest-neighbor workflows where Euclidean distance may be distorted by leverage directions.
Robust kernels and GP input metrics
A robust scatter estimate can also define a robust input metric. Instead of using an isotropic Euclidean distance, kernel methods can use a robust Mahalanobis geometry induced by a fitted covariance or scatter estimator.
For example, a robust RBF-style similarity can be written as
The package also includes sklearn-style and GPyTorch-style adapters for robust input metrics. These utilities target the input geometry of kernel methods and Gaussian-process workflows. They do not replace GP inference, likelihood modeling, posterior computation, or training loops.
FastMCD for classical contamination
FastMCD is the main estimator for a classical contamination setting: most observations form a central cloud, while a minority are separated outliers.
and the outliers are at least partly separable from the central data. It is less appropriate when the data are mostly heavy-tailed but not clearly split into clean and contaminated subsets.
Heavy-tail scatter estimators
For diffuse heavy tails, small samples, or high-dimensional regimes, hard subset selection may not be the right tool. robustcov includes several iteratively reweighted scatter estimators.
RegularizedCauchy applies strong radial downweighting with shrinkage. It is intended for very heavy-tailed samples and small-sample regimes.
StudentTScatter uses Student-t style weights. Smaller degrees of freedom correspond to heavier tails and more aggressive downweighting.
RegularizedTyler estimates robust shape. Tyler-style estimators are scale-free unless a scale correction is applied, so they are often best interpreted through robust shape and robust distances.
Automatic estimator selection
AutoRobustScatter is a practical exploratory selector. It fits candidate estimators and chooses one using diagnostic or stability-based criteria.
import numpy as npimport robustcov as rcrng = np.random.default_rng(3)X = rng.standard_t(df=3, size=(300, 12))X[:20] +=5.0auto = rc.AutoRobustScatter(selection="diagnostic").fit(X)print(auto.best_estimator_name_)print(auto.summary())
This is not an oracle. It is meant as a helpful first pass when the user does not yet know whether the data are better described as classical contamination, diffuse heavy tails, or a small-sample high-dimensional problem.
Robust outlier detection
The robust covariance estimators can be wrapped into anomaly detectors.
The anomaly score is based on robust distance. This makes the results interpretable: a point is suspicious because it is far from the robustly estimated center relative to the robust covariance or scatter shape.
Diagnostic reports and plotting
robustcov includes diagnostic summaries to help interpret fitted estimators.
import numpy as npimport robustcov as rcrng = np.random.default_rng(5)X = rng.standard_t(df=3, size=(400, 8))est = rc.RegularizedCauchy(alpha=0.10).fit(X)report = rc.diagnostic_report(est)print(report.summary())
Reports are intended to summarize quantities such as:
robust-distance behavior;
radial kurtosis;
condition number;
detected fraction;
support fraction when applicable;
tail diagnostics;
heuristic recommendations.
The package also includes plotting helpers for robust distances, QQ plots, covariance heatmaps, benchmark curves, and anomaly panels. Most plotting functions support saving figures through output_path, which makes them useful for reports and documentation.
Multimodal diagnostics
A single global robust covariance model is not always appropriate. If a data set contains several legitimate clusters or regimes, a global robust estimator may treat small valid modes as anomalies.
ClusterRobustOutlierDetector provides a cluster-then-local-robust-scatter workflow.
This is not a full robust mixture model. It is a practical diagnostic workflow for multimodal data where local robust distances are more meaningful than one global covariance estimate.
Missing values and preprocessing
The package includes a robust median imputer for simple preprocessing pipelines.
The goal is not to replace full-featured preprocessing libraries. The helper exists so robust covariance examples can handle simple missing-value cases without leaving the package.
OpenMP acceleration
If OpenMP is available at build time, the C++ backend can parallelize selected operations.
import robustcov as rcprint("OpenMP available:", rc.has_openmp())print("threads:", rc.get_num_threads())rc.set_num_threads(4)
For reproducible timing, avoid thread oversubscription from BLAS libraries:
The benchmark documentation is intentionally conservative. robustcov is strongest when the signal is covariance-shaped, heavy-tailed, high-dimensional, or benefits from interpretable robust distances. It is not expected to win every anomaly-detection benchmark.
For fair local benchmarking, report:
hardware;
operating system;
Python version;
NumPy and SciPy versions;
compiler;
OpenMP availability;
BLAS thread settings;
sample size and dimension;
random seed.
Use-case gallery
The examples directory includes practical scripts for different application patterns.
The external-data pages should be read as evidence and diagnostics, not as universal claims. Some data sets are good fits for robust covariance methods, some are competitive but slower, and some are included mainly to show limitations.
Algorithms
The package connects several robust-statistics and geometry ideas:
minimum covariance determinant estimation;
C-step refinement for robust subset selection;
robust Mahalanobis distances;
Tyler shape estimation;
regularized Tyler scatter;
Student-t M-estimation;
Cauchy-style radial downweighting;
shrinkage toward stable covariance targets;
empirical and diagnostic anomaly thresholds;
cluster-aware local robust scatter diagnostics;
SPD matrix normalization, logarithms, powers, and geodesics;
affine-invariant and log-Euclidean distances between scatter matrices;
Tyler fixed-point residual diagnostics;
robust input metrics for kernel and similarity methods;
robust RBF-style kernels using fitted scatter geometry;
sklearn-style and GPyTorch-style kernel adapters.
A simplified view of the robust-distance and robust-similarity workflow is:
raw data
↓
robust location and scatter estimation
↓
robust precision / SPD geometry
↓
robust squared distances
↓
diagnostic thresholds, robust similarities, or kernel matrices
↓
outlier labels, anomaly scores, plots, reports, and ML workflow components
For heavy-tailed M-estimators, the core idea is iterative radial reweighting. Observations with large robust distance receive smaller weights when updating the scatter matrix.
For example, a Student-t style weight has the form
w_i(d_i^2) =
\frac{\nu + p}{\nu + d_i^2},
where
\nu
is the degrees-of-freedom parameter and
p
is the dimension.
Tyler-style estimators use a shape equation of the form
Regularization then shrinks the update toward a stable target matrix,
S_{\text{new}}
=
(1-\alpha)S_{\text{robust}}
+
\alpha T.
This improves conditioning in small-sample or high-dimensional regimes.
Development status
robustcov is an alpha-stage scientific package. The current public release focuses on:
robust covariance under contamination;
heavy-tail scatter estimation;
robust-distance anomaly diagnostics;
automatic estimator selection heuristics;
multimodal cluster-aware diagnostics;
SPD geometry utilities for scatter diagnostics and covariance comparison;
robust input metrics for kernel, GP, and similarity workflows;
plotting and diagnostic reports;
use-case and benchmark galleries;
cross-platform wheels for Python 3.12+;
Sphinx documentation with examples.
Out of scope for the current alpha:
full robust mixture modeling;
minimum-volume ellipsoid as a main production API;
density modeling with AIC/BIC model selection;
deep anomaly detection;
universal fraud or intrusion-detection leadership claims;
replacing scikit-learn covariance estimators in all settings;
replacing GP frameworks such as GPyTorch or scikit-learn Gaussian processes;
robust output-likelihood modeling for Gaussian processes.
The package is best understood as a focused robust scatter geometry toolkit: robust covariance and scatter estimation, robust distances, SPD geometry, anomaly diagnostics, and robust input metrics for ML workflows.
References
P. J. Rousseeuw. “Least Median of Squares Regression.”
P. J. Rousseeuw and K. Van Driessen. “A Fast Algorithm for the Minimum Covariance Determinant Estimator.”
D. E. Tyler. “A Distribution-Free M-Estimator of Multivariate Scatter.”
E. Ollila, D. E. Tyler, V. Koivunen, and H. V. Poor. Work on complex elliptically symmetric distributions and robust covariance.
Y. Chen, A. Wiesel, and A. O. Hero. Work on shrinkage covariance estimation under elliptical models.
R. A. Maronna, R. D. Martin, V. J. Yohai, and M. Salibián-Barrera. Robust Statistics: Theory and Methods.
P. J. Huber and E. M. Ronchetti. Robust Statistics.
X. Pennec, P. Fillard, and N. Ayache. “A Riemannian Framework for Tensor Computing.”
V. Arsigny, P. Fillard, X. Pennec, and N. Ayache. “Geometric Means in a Novel Vector Space Structure on Symmetric Positive-Definite Matrices.”
T. W. Anderson. An Introduction to Multivariate Statistical Analysis.