Robust covariance and multivariate outliers

Robust estimators of multivariate location and scatter, in robustmodels.covariance.

Choosing an estimator

Class

Needs

Random

Notes

MCD

n > p

Optional

The standard choice; algorithm="deterministic" avoids random starts

MRCD

Any n, p

No

Regularized MCD for many variables, including p > n

MVE

n > p + 1

Yes

Smallest covering ellipsoid; less efficient than MCD

OGK

n >= 2

No

Fast for many variables; not rotation equivariant

StahelDonoho

n > p

Optional

Weights from projection outlyingness; no subset search

PenaPrieto

n > 2p

Optional

Kurtosis and specific directions (KSD); fast for many variables

SEstimator

n > p

Yes

Smooth weights instead of a hard subset

MMEstimator

n > p

Yes

S-estimator refined to 95% shape efficiency

Here n is the number of observations and p the number of variables. The exact MCD, MVE, S and MM definitions are affine equivariant under their respective assumptions. Numerical searches may behave differently; in particular deterministic starts do not guarantee full affine equivariance. Maximal breakdown approaches 50% for fixed dimension as sample size grows, and can be substantially lower in small samples or high dimensions.

Use

All classes are scikit-learn estimators: parameters go to the constructor, fit(X) returns the estimator, and results are attributes ending in _.

>>> import numpy as np
>>> from robustmodels.covariance import MCD
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10  # ten outliers
>>> mcd = MCD(random_state=0).fit(X)
>>> mcd.location_.round(2).tolist()
[0.01, 0.1]
>>> mcd.covariance_.round(2).tolist()
[[0.93, 0.15], [0.15, 1.06]]

Every fitted estimator has:

Attribute or method

Meaning

location_

Robust location

covariance_

Robust covariance matrix

precision_

Its (pseudo-)inverse

dist_

Squared robust distances of the training data

mahalanobis(X)

Squared robust distances of any observations

score(X), error_norm(...), get_precision()

As in sklearn.covariance.EmpiricalCovariance

Estimators that select observations (MCD, MRCD, MVE, OGK, PenaPrieto) also have support_, a boolean mask of the observations used.

Detecting outliers

Under the normal model, squared robust distances follow approximately a chi-square distribution with p degrees of freedom. Flag the observations above a high quantile:

>>> from scipy.stats import chi2
>>> flagged = mcd.mahalanobis(X) > chi2.ppf(0.975, df=2)
>>> np.flatnonzero(flagged).tolist()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 69]

The ten planted outliers are found. Observation 69 is a clean point in the tail. The 2.5% tail probability is a population/asymptotic reference; fitted in-sample distances do not provide an exact finite-sample test or an exact 2.5% false-positive rate.

Use plots.distance_distance to compare robust and classical distances, or plots.tolerance_ellipse for two variables.

Reproducibility

MCD (with algorithm="fast"), MVE, SEstimator and MMEstimator draw random subsets. Pass random_state to get the same result on every run, or use a deterministic estimator:

>>> det = MCD(algorithm="deterministic").fit(X)
>>> int(det.support_[:10].sum())  # no outlier is used
0

More variables than observations

MCD needs more observations than variables. MRCD regularizes the covariance and works in any dimension:

>>> from robustmodels.covariance import MRCD
>>> wide = np.random.default_rng(0).normal(size=(20, 50))
>>> mrcd = MRCD().fit(wide)
>>> mrcd.covariance_.shape
(50, 50)
>>> 0 < mrcd.rho_ < 1  # regularization weight
True

Many variables: Peña–Prieto directions

Random (p + 1)-subsets are rarely free of outliers when p is large. PenaPrieto instead projects the data on directions chosen from the data: the two directions of extreme kurtosis, normals of hyperplanes through neighbouring observations, and the observations themselves (the KSD procedure of Peña and Prieto 2007, with the modification of Maronna 2017). Observations that stand out on some direction are set aside, the directions are recomputed, and the clean set is then completed by Mahalanobis distance.

>>> from robustmodels.covariance import PenaPrieto
>>> wide = np.random.default_rng(0).normal(size=(200, 20))
>>> wide[:40, 0] += 10  # 20% concentrated outliers
>>> ksd = PenaPrieto(random_state=0).fit(wide)
>>> int(ksd.support_[:40].sum())  # none of the outliers is used
0

It flags the same observations as initPP of R’s RobStatTM on frozen data, and its covariance is additionally scaled for consistency at the normal model. Neither KSD nor MCD dominates. In simulations with 20% of outliers shifted along one coordinate (n = 300, p = 20), MCD excluded them from a shift of 8 and KSD only from 14; with n = 1000, p = 100 and 10% shifted by 10, KSD kept 12 outliers and MCD 41. With few observations per variable (n / p around 3) KSD can keep many outliers, as RobStatTM’s implementation. RobStatTM uses KSD to start Rocke’s S-estimator; the bisquare SEstimator gains nothing from it, because in high dimension its own minimum can be the contaminated fit (Rocke 1996).

With scikit-learn

The estimators work with clone, get_params, set_params and pipelines:

>>> from sklearn.base import clone
>>> clone(mcd).set_params(alpha=0.75).fit(X).h_
75

Numerical limits and sources

Rank checks use the correlation scale. Changing measurement units therefore preserves whether a covariance qualifies as numerically nonsingular and preserves Mahalanobis distances for full-rank fits. The threshold still applies to near collinearity.

MCD is solved by an exhaustive sorted-window search in one dimension. Multivariate MCD, MRCD, MVE, S and MM use finite searches or iterative refinements: they do not certify a global optimum. The MVE implementation searches elemental ellipsoids and local refits; it also does not solve a minimum-volume enclosing-ellipsoid problem for each selected subset.

For exact raw MCD on data in general position, the finite-sample breakdown fraction is min(n-h+1, h-p)/n; it is not simply 50% for every n,p. Finite-sample correction factors are empirical approximations.

MRCD applies the common-rho rule in Boudt et al., algorithm step 3.4. The max_condition parameter calibrates initial subsets in standardized coordinates. Keeping rho fixed during C-steps does not impose a hard bound on the final subset’s condition number. In original units, unequal column scales can further increase the condition number.

MM’s efficiency targets asymptotic shape efficiency. Its scale comes from the S-estimator; 95% shape efficiency does not imply 95% efficiency for location or all covariance entries. The final normalized bisquare loss must not exceed the initial loss pointwise (final tuning at least initial tuning). Parameter combinations violating this condition raise ValueError.

The Stahel-Donoho estimator downweights observations with the Huber-type weights of Maronna and Yohai, so an outlier keeps a small bounded influence instead of being removed; with all hyperplanes through p observations as directions the result is deterministic and affine equivariant. rrcov::CovSde uses another weight function and gives different estimates on contaminated data.

Sources: FAST-MCD, DetMCD, Stahel-Donoho estimator, MCD corrections, MRCD, MVE, OGK, S-estimation, and multivariate MM.

Reference

class MCD(*, alpha=0.5, algorithm='fast', n_trials=500, reweighting=True, small_sample_correction=True, random_state=None)[source]

Minimum Covariance Determinant estimator (Rousseeuw 1984).

Mean and covariance of the h observations whose covariance matrix has the smallest determinant, scaled for consistency at the normal model. The reweighting step then recomputes both from the observations whose squared robust distance is below the 0.975 chi-square quantile. In general position, the exact raw estimator has breakdown min(n - h + 1, h - p) / n, approaching 50% for alpha = 0.5 and fixed p. The multivariate search does not certify a global minimum. Needs n > p; use MRCD otherwise. If h observations lie on a hyperplane, a RuntimeWarning reports the exact fit and the raw estimates are kept.

Parameters:
  • alpha (float in [0.5, 1], default 0.5) – Coverage. The subset size h = h_alpha_n(alpha, n, p) goes from (n + p + 1) // 2 (maximal breakdown) at 0.5 to n at 1.

  • algorithm ({"fast", "deterministic"}, default "fast") – FAST-MCD with random starts (Rousseeuw & Van Driessen 1999), or DetMCD with six deterministic starts (Hubert, Rousseeuw & Verdonck 2012). With one variable both use the exact univariate MCD.

  • n_trials (int, default 500) – Random starting subsets of FAST-MCD.

  • reweighting (bool, default True) – Apply the reweighting step.

  • small_sample_correction (bool, default True) – Multiply the covariance by the factors of Pison, Van Aelst & Willems (2002).

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of FAST-MCD.

location_

Final location.

Type:

ndarray of shape (n_features,)

covariance_

Final covariance matrix.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

support_

Observations used for the final estimates.

Type:

ndarray of bool, shape (n_samples,)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

raw_location_

Mean of the h-subset.

Type:

ndarray of shape (n_features,)

raw_covariance_

Corrected covariance of the h-subset.

Type:

ndarray of shape (n_features, n_features)

raw_support_

The h-subset.

Type:

ndarray of bool, shape (n_samples,)

h_

Subset size.

Type:

int

References

Rousseeuw, P. J. (1984). Least median of squares regression. Journal of the American Statistical Association, 79(388), 871-880.

Rousseeuw, P. J. and Van Driessen, K. (1999). A fast algorithm for the minimum covariance determinant estimator. Technometrics, 41(3), 212-223.

Hubert, M., Rousseeuw, P. J. and Verdonck, T. (2012). A deterministic algorithm for robust location and scatter. Journal of Computational and Graphical Statistics, 21(3), 618-637.

Croux, C. and Haesbroeck, G. (1999). Influence function and efficiency of the minimum covariance determinant scatter matrix estimator. Journal of Multivariate Analysis, 71(2), 161-190.

Pison, G., Van Aelst, S. and Willems, G. (2002). Small sample corrections for LTS and MCD. Metrika, 55, 111-123.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import MCD
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10  # ten outliers
>>> mcd = MCD(random_state=0).fit(X)
>>> mcd.location_.round(2).tolist()
[0.01, 0.1]
>>> int(mcd.support_[:10].sum())  # no outlier is used
0
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class MRCD(*, alpha=0.5, max_condition=50.0, rho=None)[source]

Minimum Regularized Covariance Determinant estimator (Boudt et al. 2020).

The data are standardized with the column medians and Qn scales. The h-subset H then minimizes the determinant of K(H) = rho * I + (1 - rho) * c_alpha * cov(H), where c_alpha is the MCD consistency factor. The common rho is selected from the initial subsets by step 3.4 of Boudt et al. (2020), then held fixed during C-steps. The search does not certify a global minimum. In the original units the regularization target is the diagonal matrix of squared Qn scales. Works with more variables than observations; when the subset covariance is already well-conditioned, rho = 0 and the result is the raw MCD. There is no reweighting step.

With more variables than observations the starting subsets come from eigenvectors that are not unique, so results can differ slightly between platforms and linear algebra libraries.

Parameters:
  • alpha (float in [0.5, 1], default 0.5) – Coverage; the subset size is h = ceil(alpha * n).

  • max_condition (float, default 50) – Condition-number bound used to calibrate the starting subsets in standardized coordinates. It is not a hard bound on the final subset or on the covariance in original units.

  • rho (float in [0, 1), optional) – Fixed regularization weight, which replaces max_condition. Needed when a starting subset has zero scatter.

location_

Mean of the h-subset.

Type:

ndarray of shape (n_features,)

covariance_

Regularized covariance matrix.

Type:

ndarray of shape (n_features, n_features)

precision_

Inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

support_

The h-subset.

Type:

ndarray of bool, shape (n_samples,)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

rho_

Regularization weight used.

Type:

float

h_

Subset size.

Type:

int

References

Boudt, K., Rousseeuw, P. J., Vanduffel, S. and Verdonck, T. (2020). The minimum regularized covariance determinant estimator. Statistics and Computing, 30(1), 113-128.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import MRCD
>>> X = np.random.default_rng(0).normal(size=(20, 50))  # p > n
>>> mrcd = MRCD().fit(X)
>>> mrcd.covariance_.shape
(50, 50)
>>> 0 < mrcd.rho_ < 1
True
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class MVE(*, alpha=0.5, n_trials=500, reweighting=True, random_state=None)[source]

Minimum Volume Ellipsoid estimator (Rousseeuw 1985).

Approximation to the center and scaled shape of the smallest ellipsoid that covers h observations. The search draws random (p + 1)-subsets, refits each ellipsoid once to the h points it covers (as rrcov), then refits the 10 best while the volume decreases. This heuristic does not certify a minimum-volume ellipsoid, even on each selected subset. The shape is scaled for consistency at the normal model and reweighted as in MCD. Breakdown point about 50% for alpha = 0.5. Needs n > p + 1.

Parameters:
  • alpha (float in [0.5, 1), default 0.5) – Coverage, as for MCD. Full coverage has no finite scale correction.

  • n_trials (int, default 500) – Random starting subsets.

  • reweighting (bool, default True) – Recompute mean and covariance from the observations whose squared robust distance is below the 0.975 chi-square quantile.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the random subsets.

location_

Final location.

Type:

ndarray of shape (n_features,)

covariance_

Final covariance matrix.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

support_

Observations used for the final estimates.

Type:

ndarray of bool, shape (n_samples,)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

raw_location_

Center of the best ellipsoid.

Type:

ndarray of shape (n_features,)

raw_covariance_

Scaled shape of the best ellipsoid.

Type:

ndarray of shape (n_features, n_features)

raw_support_

Observations inside the best ellipsoid.

Type:

ndarray of bool, shape (n_samples,)

h_

Number of observations covered.

Type:

int

References

Rousseeuw, P. J. (1985). Multivariate estimation with high breakdown point. In W. Grossmann et al. (eds.), Mathematical Statistics and Applications, Vol. B, 283-297. Reidel.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import MVE
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10
>>> mve = MVE(random_state=0).fit(X)
>>> mve.location_.round(2).tolist()
[0.01, 0.1]
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class OGK(*, scale='tau', n_iter=2, reweighting=True, beta=0.9)[source]

Orthogonalized Gnanadesikan-Kettenring estimator (Maronna & Zamar 2002).

Robust pairwise covariances (s(X + Y)^2 - s(X - Y)^2) / 4, with s a robust univariate scale, made positive definite by orthogonalization. Deterministic and fast for many variables. It is equivariant under shifts and rescaling of the variables, but not under rotations.

Parameters:
  • scale ({"tau", "qn", "mad", "pn"}, default "tau") – Univariate scale. “tau” is centered at the tau location, the others at the median.

  • n_iter (int, default 2) – Orthogonalization iterations.

  • reweighting (bool, default True) – Recompute mean and covariance from the observations with d^2 <= chi2_p^-1(beta) * median(d^2) / chi2_p^-1(0.5). The reweighted covariance is corrected for consistency at the normal model, which R’s covOGK omits.

  • beta (float in (0, 1), default 0.9) – Quantile of the reweighting cutoff.

location_

Final location.

Type:

ndarray of shape (n_features,)

covariance_

Final covariance matrix.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

support_

Observations used for the final estimates (all if reweighting=False).

Type:

ndarray of bool, shape (n_samples,)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

raw_location_

Location before reweighting.

Type:

ndarray of shape (n_features,)

raw_covariance_

Covariance before reweighting.

Type:

ndarray of shape (n_features, n_features)

References

Maronna, R. A. and Zamar, R. H. (2002). Robust estimates of location and dispersion for high-dimensional datasets. Technometrics, 44(4), 307-317.

Gnanadesikan, R. and Kettenring, J. R. (1972). Robust estimates, residuals, and outlier detection with multiresponse data. Biometrics, 28(1), 81-124.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import OGK
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10
>>> OGK().fit(X).covariance_.round(1).tolist()
[[1.1, 0.2], [0.2, 1.1]]
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class StahelDonoho(*, quantile=0.95, n_directions=None, random_state=None)[source]

Stahel-Donoho estimator of location and scatter (Stahel 1981; Donoho 1982).

Weighted mean and covariance with weights w(r_i) that decrease with the Stahel-Donoho outlyingness r_i of each observation, computed by StahelDonohoOutlyingness. The weights are w(r) = min(1, (c / r)^2) with c the square root of a chi-square quantile, as recommended by Maronna & Yohai (1995). The covariance is then scaled so that the median squared distance equals the chi-square median, which makes it consistent at the normal model. With all directions the estimator is affine equivariant and its breakdown point approaches 50%; a finite set of directions approximates it. An outlier keeps a small bounded influence, since w(r) r^2 equals c^2 beyond c. Needs n > p.

Parameters:
  • quantile (float in (0, 1), default 0.95) – Chi-square quantile for c: observations with outlyingness up to c keep weight 1.

  • n_directions (int, default None) – Number of directions; 250 * n_features by default.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the random directions.

location_

Weighted mean.

Type:

ndarray of shape (n_features,)

covariance_

Scaled weighted covariance matrix.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

outlyingness_

Stahel-Donoho outlyingness of the training data.

Type:

ndarray of shape (n_samples,)

weights_

Weights in [0, 1].

Type:

ndarray of shape (n_samples,)

Notes

R’s rrcov::CovSde uses a different, redescending weight function, so its estimates differ on contaminated data.

References

Stahel, W. A. (1981). Robuste Schätzungen: infinitesimale Optimalität und Schätzungen von Kovarianzmatrizen. PhD thesis, ETH Zürich.

Donoho, D. L. (1982). Breakdown properties of multivariate location estimators. Qualifying paper, Harvard University.

Maronna, R. A. and Yohai, V. J. (1995). The behavior of the Stahel-Donoho robust multivariate estimator. Journal of the American Statistical Association, 90(429), 330-341.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import StahelDonoho
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10
>>> sd = StahelDonoho(random_state=0).fit(X)
>>> sd.location_.round(1).tolist()
[0.0, 0.2]
>>> bool(sd.weights_[:10].max() < 0.1)  # the outliers hardly count
True
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class PenaPrieto(*, n_directions=None, random_state=None)[source]

Location and scatter by kurtosis and specific directions (Peña & Prieto 2007).

The KSD procedure, a fast and deterministic-start estimator for many variables, where random hyperplanes through p observations rarely miss every outlier only after a huge number of trials. On data standardized by the sample mean and covariance it projects the observations on

  • the directions that maximize and minimize the kurtosis of the projections (Peña & Prieto 2001): a few concentrated outliers raise the kurtosis along their direction, many of them lower it;

  • n_directions specific directions: normals of hyperplanes through p observations drawn from groups of 2p neighbours along random lines, which are often free of outliers;

  • the 10p observations of smallest and largest norm, as directions (Maronna 2017).

Observations whose largest |projection - median| / MAD exceeds 3.05 + 0.081 p are set aside and the directions recomputed on the rest, at most 10 times or until at most half the sample remains; directions with zero MAD are skipped for an observation, as in StahelDonohoOutlyingness, and the trimming stops before the rest would lie on a hyperplane (ties of discrete data). Set-aside observations then return, closest first, until (n + p + 1) / 2 are in, and while their squared Mahalanobis distance to the mean and covariance of those in is below the 0.99 chi-square quantile. The estimates are the mean and covariance of the observations in, the latter scaled for consistency at the normal model (by mcd_consistency(p, 0.99)) when some observation is out. The steps and constants follow RobStatTM (the R package of Maronna et al. 2019), whose covariance is unscaled. The estimator is affine equivariant; needs n > 2p. RobStatTM uses it to start Rocke’s S-estimator; the bisquare SEstimator cannot use it that way, since in high dimension its own minimum can be a contaminated fit (Rocke 1996). With few observations per variable, KSD can keep outliers.

Parameters:
  • n_directions (int, default None) – Specific directions per pass; max(20 * n_features, 1000) by default.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the specific directions.

location_

Mean of the observations in support_.

Type:

ndarray of shape (n_features,)

covariance_

Their covariance, scaled for consistency.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

support_

Observations used for the estimates.

Type:

ndarray of bool, shape (n_samples,)

n_iter_

Passes of the projection step.

Type:

int

References

Peña, D. and Prieto, F. J. (2001). Multivariate outlier detection and robust covariance matrix estimation. Technometrics, 43(3), 286-310.

Peña, D. and Prieto, F. J. (2007). Combining random and specific directions for outlier detection and robust estimation in high-dimensional multivariate data. Journal of Computational and Graphical Statistics, 16(1), 228-254.

Maronna, R. A. (2017). Improving the Peña-Prieto “KSD” procedure. arXiv:1708.03196.

Maronna, R. A., Martin, R. D., Yohai, V. J. and Salibián-Barrera, M. (2019). Robust Statistics: Theory and Methods (with R), 2nd edition. Wiley.

Rocke, D. M. (1996). Robustness properties of S-estimators of multivariate location and shape in high dimension. The Annals of Statistics, 24(3), 1327-1345.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import PenaPrieto
>>> X = np.random.default_rng(0).normal(size=(200, 20))
>>> X[:40, 0] += 10  # 20% concentrated outliers
>>> ksd = PenaPrieto(random_state=0).fit(X)
>>> int(ksd.support_[:40].sum()), int(ksd.support_[40:].sum())
(0, 153)
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class SEstimator(*, breakdown=0.5, n_trials=500, n_best=5, k_steps=2, max_iter=200, random_state=None)[source]

S-estimator of location and scatter (Davies 1987), with Tukey’s bisquare.

Finds the location mu and the shape Gamma (determinant 1) that minimize the M-scale s of the distances d_i = sqrt((x_i - mu)' Gamma^-1 (x_i - mu)), where s solves mean(rho(d_i / s)) = breakdown. The covariance is s^2 * Gamma, consistent at the normal model. Computed with the FAST-S algorithm (Salibián-Barrera, Van Aelst & Willems 2006), without a global-minimum certificate. The theoretical estimator is affine equivariant; needs n > p.

Parameters:
  • breakdown (float in (0, 0.5], default 0.5) – Breakdown point.

  • n_trials (int, default 500) – Random (p + 1)-subsets, each refined with k_steps I-steps.

  • n_best (int, default 5) – Best candidates iterated to convergence.

  • k_steps (int, default 2) – I-steps applied to each random subset.

  • max_iter (int, default 200) – Maximum I-steps for each of the best candidates.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the random subsets.

location_

Location mu.

Type:

ndarray of shape (n_features,)

covariance_

Covariance matrix s^2 * Gamma.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

scale_

The minimized M-scale s.

Type:

float

References

Davies, P. L. (1987). Asymptotic behaviour of S-estimates of multivariate location parameters and dispersion matrices. Annals of Statistics, 15(3), 1269-1292.

Salibián-Barrera, M., Van Aelst, S. and Willems, G. (2006). Principal components analysis based on multivariate MM estimators with fast and robust bootstrap. Journal of the American Statistical Association, 101(475), 1198-1211.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import SEstimator
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10
>>> s = SEstimator(random_state=0).fit(X)
>>> s.covariance_.round(1).tolist()
[[1.1, 0.1], [0.1, 1.3]]
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

class MMEstimator(*, breakdown=0.5, efficiency=0.95, n_trials=500, max_iter=200, random_state=None)[source]

MM-estimator of location and scatter (Tatsuoka & Tyler 2000).

Starts from a bisquare SEstimator and keeps its scale s. A bisquare M-estimator of location and shape, tuned for the requested Gaussian efficiency of the shape, then refines the estimates. It keeps the breakdown point of the S-estimator and gains efficiency. Affine equivariant; needs n > p.

Parameters:
  • breakdown (float in (0, 0.5], default 0.5) – Breakdown point of the initial S-estimator.

  • efficiency (float in (0, 1), default 0.95) – Asymptotic Gaussian efficiency of the shape, not of the full covariance or location. Must imply a final bisquare tuning constant at least as large as the initial S tuning, to preserve the breakdown guarantee; incompatible combinations of efficiency, breakdown and dimension raise ValueError.

  • n_trials (int, default 500) – Random subsets of the initial S-estimator.

  • max_iter (int, default 200) – Maximum iterations of the M-step.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the initial S-estimator.

location_

MM location.

Type:

ndarray of shape (n_features,)

covariance_

MM covariance matrix.

Type:

ndarray of shape (n_features, n_features)

precision_

Pseudo-inverse of covariance_.

Type:

ndarray of shape (n_features, n_features)

dist_

Squared robust distances of the training data.

Type:

ndarray of shape (n_samples,)

scale_

Scale of the S-estimator.

Type:

float

s_location_

Location of the S-estimator.

Type:

ndarray of shape (n_features,)

s_covariance_

Covariance of the S-estimator.

Type:

ndarray of shape (n_features, n_features)

References

Tatsuoka, K. S. and Tyler, D. E. (2000). On the uniqueness of S-functionals and M-functionals under nonelliptical distributions. Annals of Statistics, 28(4), 1219-1243.

Salibián-Barrera, M., Van Aelst, S. and Willems, G. (2006). Principal components analysis based on multivariate MM estimators with fast and robust bootstrap. Journal of the American Statistical Association, 101(475), 1198-1211.

Examples

>>> import numpy as np
>>> from robustmodels.covariance import MMEstimator
>>> X = np.random.default_rng(0).normal(size=(100, 2))
>>> X[:10] += 10
>>> mm = MMEstimator(random_state=0).fit(X)
>>> mm.covariance_.round(1).tolist()
[[1.2, 0.1], [0.1, 1.2]]
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

Correction factors

h_alpha_n(alpha, n, p)[source]

Subset size of the MCD for coverage alpha, as R’s robustbase::h.alpha.n.

(n + p + 1) // 2 at alpha = 0.5, n at alpha = 1 and linear in between.

Parameters:
  • alpha (float in [0.5, 1]) – Coverage.

  • n (int) – Number of observations and of variables.

  • p (int) – Number of observations and of variables.

Return type:

int

Raises:

ValueError – If n <= p: no subset of at most n observations exists.

Examples

>>> from robustmodels.covariance import h_alpha_n
>>> h_alpha_n(0.5, 100, 3), h_alpha_n(0.75, 100, 3)
(52, 76)
mcd_consistency(p, alpha)[source]

Consistency factor of the MCD at the normal model (Croux & Haesbroeck 1999).

alpha / F_{p+2}(chi2_p^-1(alpha)), with F_k the chi-square distribution function with k degrees of freedom. It makes the covariance of the fraction alpha of observations closest to the center consistent.

Parameters:
  • p (int) – Number of variables.

  • alpha (float in (0, 1]) – Fraction of observations kept; 1 gives 1.

Return type:

float

Examples

>>> from robustmodels.covariance import mcd_consistency
>>> round(mcd_consistency(3, 0.5), 4)
2.4574
mcd_small_sample(p, n, alpha, reweighted=False)[source]

Small-sample factor of the MCD (Pison, Van Aelst & Willems 2002).

The paper fits the factors at alpha = 0.5 and 0.875; other coverages are interpolated linearly, reaching 1 at alpha = 1.

Parameters:
  • p (int) – Number of variables and of observations.

  • n (int) – Number of variables and of observations.

  • alpha (float in [0.5, 1]) – Coverage.

  • reweighted (bool, default False) – Factor for the reweighted instead of the raw MCD.

Return type:

float

Examples

>>> from robustmodels.covariance import mcd_small_sample
>>> round(mcd_small_sample(3, 100, 0.5), 4)
1.0989