Robust PCA, discriminant analysis, Hotelling’s T² and MANOVA¶
Multivariate methods that keep working when part of the observations are
outliers, in robustmodels.multivariate: principal components, linear and
quadratic discriminant analysis, and tests on mean vectors.
Choosing a method¶
Task |
Class or function |
Notes |
|---|---|---|
Principal components |
|
The standard choice; works with more variables than observations |
Principal components without a covariance matrix |
|
Maximizes a robust scale direction by direction; more biased by outliers near the data |
Classify with a common covariance |
|
Linear boundaries; pooled MCD |
Classify with one covariance per class |
|
Quadratic boundaries; one MCD per class |
Test a mean vector, or paired differences |
|
One sample; reweighted MCD |
Compare the means of two or more groups |
|
Robust Wilks’ lambda; simulated null distribution |
The discriminant rules and the tests are built on
covariance.MCD, so every group needs more observations than
variables. For a robust covariance matrix itself, including the Stahel-Donoho
estimator, see the covariance guide.
Principal components¶
Classical PCA follows the directions of largest variance, and a few outliers are enough to create one. ROBPCA finds the subspace of the bulk of the data:
>>> import numpy as np
>>> from robustmodels.multivariate import ROBPCA
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(100, 2)) @ rng.normal(size=(2, 20)) # a plane in 20-D
>>> X += 0.1 * rng.normal(size=X.shape)
>>> X[:10] += 5 # ten outliers away from the plane
>>> pca = ROBPCA(random_state=0).fit(X)
>>> pca.n_components_, pca.explained_variance_.round(1).tolist()
(2, [42.5, 24.2])
>>> pca.transform(X).shape
(100, 2)
>>> np.flatnonzero(~pca.support_).tolist()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 40, 69, 70]
The ten outliers are flagged, with three regular observations in the tails. The largest angle between the fitted plane and the plane of the 90 regular observations is 0.1 degrees; for classical PCA of all rows it is 45 degrees.
Attribute or method |
Meaning |
|---|---|
|
Robust center, principal axes in rows and variance of each score |
|
Scores, and their points in the original space |
|
Score and orthogonal distances of new observations |
|
Distance inside the subspace and its 0.975 chi-square cutoff |
|
Distance to the subspace and its cutoff |
|
Observations within both cutoffs |
An observation can be outlying in two ways: far from the subspace (a large
orthogonal distance) or far from the center inside it (a large score distance).
plots.pca_outlier_map shows both;
plots.scree_plot and plots.biplot show
the variances, scores and loadings.
With n_components=None, ROBPCA keeps the smallest number of components that
explains 80% of the variance of the least outlying observations, at most
max_components. Pass n_components to choose it yourself, for example after
looking at explained_variance_ of a fit with more components.
ProjectionPursuitPCA needs no covariance estimate. It searches, one after
another, the orthogonal directions on which a robust scale of the projected
data is largest:
>>> from robustmodels.multivariate import ProjectionPursuitPCA
>>> X = np.random.default_rng(0).normal(size=(100, 3)) * [5, 1, 1]
>>> X[:10] = [0, 100, 0] # ten outliers on the second axis
>>> abs(np.linalg.svd(X - X.mean(axis=0))[2][0]).round(1).tolist() # classical
[0.0, 1.0, 0.0]
>>> pp = ProjectionPursuitPCA(n_components=1).fit(X)
>>> abs(pp.components_[0]).round(1).tolist()
[1.0, 0.1, 0.1]
Discriminant analysis¶
RobustLDA and RobustQDA are scikit-learn classifiers. Robust class
location and scatter estimates limit the influence of training outliers,
including mislabeled observations, within their contamination assumptions:
>>> from robustmodels.multivariate import RobustLDA
>>> rng = np.random.default_rng(0)
>>> X = np.vstack([rng.normal(size=(50, 2)), rng.normal(size=(50, 2)) + 3])
>>> y = np.repeat([0, 1], 50)
>>> X[:5] = [15, 15] # five outliers labeled as class 0
>>> lda = RobustLDA(random_state=0).fit(X, y)
>>> lda.means_.round(1).tolist()
[[-0.1, 0.2], [3.1, 3.0]]
>>> lda.predict([[0, 0], [3, 3]]).tolist()
[0, 1]
>>> X[y == 0].mean(axis=0).round(1).tolist() # the classical center of class 0
[1.5, 1.7]
predict_proba gives posterior probabilities under the normal model and
decision_function the discriminant scores. priors sets the prior
probabilities; by default they are the class proportions, outliers included.
Use RobustQDA when the classes have different covariance matrices. For two
variables, plots.discriminant_plot draws
the regions of either rule.
Tests on mean vectors¶
hotelling_t2 tests whether the center of a sample equals a given vector. For
paired samples, test the differences against zero.
>>> from robustmodels.multivariate import hotelling_t2
>>> X = np.random.default_rng(0).normal(size=(60, 3))
>>> X[:6] += 8 # six outliers
>>> result = hotelling_t2(X, random_state=0)
>>> round(result.statistic, 2), round(result.pvalue, 2)
(5.16, 0.27)
>>> hotelling_t2(X, mu=[1, 1, 1], random_state=0).pvalue < 0.001
True
manova tests whether two or more groups share the same mean vector, assuming
a common covariance matrix. With two groups it is a robust two-sample
Hotelling test.
>>> from robustmodels.multivariate import manova
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(90, 2))
>>> groups = np.repeat([0, 1, 2], 30)
>>> X[:4] += 9 # outliers in the first group
>>> result = manova(X, groups, random_state=0)
>>> round(result.statistic, 3), round(result.pvalue, 2)
(0.962, 0.63)
>>> X[groups == 2] += 1.5 # a real shift of the third group
>>> manova(X, groups, random_state=0).pvalue < 0.001
True
Both tests return named tuples. They assume that the regular observations are multivariate normal: the p-values are approximations calibrated at that model, not distribution-free results.
Numerical limits and sources¶
ROBPCA. The outlyingness uses directions through pairs of observations:
all pairs when there are at most n_directions, otherwise a random selection,
so set random_state for reproducible results. The subset size follows the
paper’s Appendix, h = max(floor(alpha*n), floor((n+k_max+1)/2)), and is
preserved in the final MCD. Zero robust projection scale gives infinite
outlyingness away from its hyperplane, rather than silently dropping that
direction. The implementation selects components with positive robust spread
and rejects point masses or numerically unidentified components.
This is a computational ROBPCA variant: the final scatter uses the package’s
generic corrected MCD and random starts. It does not reproduce every Appendix
step, including its additional C-steps from H0 and its empirical h-quantile
scale correction. Independent tests check the defining h, orthonormality,
reconstruction, score/orthogonal distances, rotations and exact-fit cases.
The orthogonal cutoff uses univariate MCD on distances to the power 2/3.
With all components retained the orthogonal cutoff is 0. Finite direction
searches and local subset optimization do not certify global optimality or
uniform subspace recovery under arbitrary contamination.
Projection pursuit. The grid search stops at a local maximum of a
nonsmooth criterion. Independent tests compare it with a dense search in two
dimensions and recover classical PCA when scale is standard deviation.
Outliers near the main data can inflate scale in intermediate directions and
tilt the components. scale="qn" is more efficient under a Gaussian model
than default MAD and computationally more expensive for large samples.
Discriminant analysis. The common covariance is the reweighted MCD of
observations centered by class. The discriminant scores are normal log
densities plus log priors; tests calculate those densities directly. A class
with singular robust scatter raises ValueError. Every class must have more
observations than variables. Older scikit-learn generic checks that violate
this mathematical requirement are documented as expected failures; equivalent
feature/dtype properties are also tested with valid per-class samples.
Hotelling’s T². The statistic is n*(t-mu)' C^-1 (t-mu), with a scaled
F approximation using the moment-calibration constants of Willems et al. for
reweighted MCD with coverage 0.75. A nonpositive or nonfinite scale, or degrees
of freedom q<=4, invalidates the two finite moments used by that approximation
and raises ValueError. The approximation can be liberal. Independent normal
null checks at nominal 5% gave 58/1000 rejections for n=40,p=1 (5.8%; exact
95% binomial interval 4.43–7.43%) and 24/300 for n=50,p=3 (8.0%; interval
5.19–11.67%). These bounded experiments do not establish uniform calibration.
MANOVA. The robust Wilks statistic requires defined weighted means for
all original groups and nonsingular within/total scatter. Singular cases or
trimming that removes any group raise ValueError. The null statistic is
simulated for the observed group sizes and dimension using deterministic MCD;
a two-moment chi-square calibration adds approximation error, and the finite
simulation adds Monte Carlo error. The p-value depends on random_state.
An independent normal null check with three equal groups, n=60,p=2, 100
calibration simulations and 80 repetitions rejected once at nominal 5%
(1.25%; exact 95% interval 0.032–6.77%). This small experiment does not prove
general conservatism or exact level. Both mean-vector tests rely on the
regular-data normal model and are not distribution-free.
Sources: ROBPCA, projection pursuit (definition, grid algorithm), robust discriminant analysis with the pooled-observations estimator, robust Hotelling test and robust MANOVA.
Reference¶
- class ROBPCA(n_components=None, *, alpha=0.75, max_components=10, n_directions=250, random_state=None)[source]¶
Robust principal components by ROBPCA (Hubert, Rousseeuw & Vanden Branden 2005).
The data are first reduced, without loss, to the subspace they span, so the method works with more variables than observations. Each observation then receives a Stahel-Donoho outlyingness: the largest
|v'x - t(v'X)| / s(v'X)over directionsvthrough two observations, withtandsthe reweighted univariate MCD location and scale. Thehleast outlying observations give a first subspace, the observations close to it give the finalk-dimensional subspace, and the reweightedMCDof the data projected on it gives the center, the components and their variances. When the data have few dimensions (rank <= min(n // 5, max_components)) the MCD is applied directly and its eigenvectors are the components.The score distance of an observation measures how far its scores are from the center, and its orthogonal distance how far it lies from the subspace. Observations beyond
score_cutoff_ororthogonal_cutoff_are outlying;pca_outlier_map()shows both.- Parameters:
n_components (int, default None) – Number of components
k. By default, the smallest number that explains 80% of the variance of thehleast outlying observations, among the components with a variance above 0.001 times the largest, and at mostmax_components.alpha (float in [0.5, 1], default 0.75) – Coverage parameter; finite-sample resistance also depends on dimension and
h_. The subset size ismax(floor(alpha * n), floor((n + k_max + 1) / 2)), withk_maxthe requested number of components, ormax_components, capped at the rank of the data. The same subset size is used in the final MCD fit.max_components (int, default 10) – Largest number of components chosen when
n_componentsis None.n_directions (int, default 250) – Directions for the outlyingness; all pairs of observations are used when there are at most this many.
random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed for the random directions and for the MCD.
- location_¶
Robust center.
- Type:
ndarray of shape (n_features,)
- components_¶
Principal axes in rows, by decreasing variance. The largest loading of each axis is positive.
- Type:
ndarray of shape (n_components, n_features)
- explained_variance_¶
Robust variance of the scores on each component.
- Type:
ndarray of shape (n_components,)
- n_components_¶
Number of components.
- Type:
int
- h_¶
Subset size.
- Type:
int
- score_distances_, orthogonal_distances_
Distances of the training data.
- Type:
ndarray of shape (n_samples,)
- score_cutoff_¶
Square root of the 0.975 chi-square quantile with
n_components_degrees of freedom.- Type:
float
- orthogonal_cutoff_¶
(m + s z)^(3/2), withmandsthe univariate MCD location and scale of the orthogonal distances to the power 2/3 andzthe 0.975 normal quantile; 0 when the components span the data.- Type:
float
- support_¶
Observations within both cutoffs.
- Type:
ndarray of bool, shape (n_samples,)
Notes
R’s
rrcov::PcaHubertestimates the orthogonal cutoff with the median and MAD instead of the univariate MCD of the paper, and may end with a reweighted covariance that has no consistency factor.References
Hubert, M., Rousseeuw, P. J. and Vanden Branden, K. (2005). ROBPCA: a new approach to robust principal component analysis. Technometrics, 47(1), 64-79.
Examples
>>> import numpy as np >>> from robustmodels.multivariate import ROBPCA >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(100, 2)) @ rng.normal(size=(2, 20)) # a plane in 20-D >>> X += 0.1 * rng.normal(size=X.shape) >>> X[:10] += 5 # ten outliers away from the plane >>> pca = ROBPCA(n_components=2, random_state=0).fit(X) >>> pca.transform(X).shape (100, 2) >>> bool(np.all(pca.orthogonal_distances_[:10] > pca.orthogonal_cutoff_)) True >>> int(pca.support_[10:].sum()) # regular observations within both cutoffs 87
- distances(X)¶
Score and orthogonal distances of each row of
X.The score distance is the robust distance of the scores inside the principal subspace; the orthogonal distance is the Euclidean distance from the observation to that subspace.
- Returns:
score_distances, orthogonal_distances
- Return type:
ndarray of shape (n_samples,)
- inverse_transform(X)¶
Points of the original space with scores
X.
- transform(X)¶
Scores of
X: coordinates on the principal components.
- class ProjectionPursuitPCA(n_components=2, *, scale='mad', n_grid=25, n_cycles=10, alpha=0.75)[source]¶
Robust principal components by projection pursuit (Li & Chen 1985).
The first component is the direction that maximizes a robust scale of the projected data; each next one maximizes it among the directions orthogonal to the previous components. The search uses the grid algorithm of Croux, Filzmoser & Oliveira (2007): it improves the direction in the plane of the current direction and one variable at a time, over a grid of angles that is halved at every cycle. The result is a local optimum of each criterion. The data are centered at the spatial median. No covariance matrix is needed, so the method works with more variables than observations, and the components are orthogonally equivariant up to the grid resolution.
- Parameters:
n_components (int, default 2) – Number of components.
scale ({"mad", "qn", "tau", "pn"} or callable, default "mad") – Robust scale to maximize, or a function of a one-dimensional sample. “qn” is more efficient than “mad” but much slower for large samples. With the standard deviation the method estimates classical components.
n_grid (int, default 25) – Angles tried in each plane.
n_cycles (int, default 10) – Cycles over the variables; the grid is halved at each cycle.
alpha (float in [0.5, 1], default 0.75) – Coverage of the univariate MCD in the orthogonal distance cutoff.
- location_¶
Spatial median.
- Type:
ndarray of shape (n_features,)
- components_¶
Principal axes in rows, in the order found. The largest loading of each axis is positive.
- Type:
ndarray of shape (n_components, n_features)
- explained_variance_¶
Squared robust scale of the scores on each component.
- Type:
ndarray of shape (n_components,)
- n_components_¶
Number of components.
- Type:
int
- score_distances_, orthogonal_distances_
Distances of the training data.
- Type:
ndarray of shape (n_samples,)
- score_cutoff_, orthogonal_cutoff_
Cutoffs, as in
ROBPCA.- Type:
float
References
Li, G. and Chen, Z. (1985). Projection-pursuit approach to robust dispersion matrices and principal components: primary theory and Monte Carlo. Journal of the American Statistical Association, 80(391), 759-766.
Croux, C., Filzmoser, P. and Oliveira, M. R. (2007). Algorithms for projection-pursuit robust principal component analysis. Chemometrics and Intelligent Laboratory Systems, 87(2), 218-225.
Examples
>>> import numpy as np >>> from robustmodels.multivariate import ProjectionPursuitPCA >>> X = np.random.default_rng(0).normal(size=(100, 3)) * [5, 1, 1] >>> X[:10] = [0, 100, 0] # ten outliers on the second axis >>> pca = ProjectionPursuitPCA(n_components=1).fit(X) >>> abs(pca.components_[0]).round(1).tolist() [1.0, 0.1, 0.1]
- distances(X)¶
Score and orthogonal distances of each row of
X.The score distance is the robust distance of the scores inside the principal subspace; the orthogonal distance is the Euclidean distance from the observation to that subspace.
- Returns:
score_distances, orthogonal_distances
- Return type:
ndarray of shape (n_samples,)
- inverse_transform(X)¶
Points of the original space with scores
X.
- transform(X)¶
Scores of
X: coordinates on the principal components.
- class RobustLDA(*, alpha=0.5, priors=None, random_state=None)[source]¶
Robust linear discriminant analysis with the MCD (Hubert & Van Driessen 2004).
The classical rule assigns
xto the class with the largestmu_k' S^-1 x - mu_k' S^-1 mu_k / 2 + log(prior_k); a few outliers can ruin its sample means and pooled covarianceS. Here each class is centered at its reweightedMCDlocation, and the reweighted MCD of the pooled centered observations gives the common covariance and a correction of the centers (the pooled-observations estimator of He & Fung 2000). Every class needs more observations than variables.- Parameters:
alpha (float in [0.5, 1], default 0.5) – Coverage of the MCD estimators.
priors (array-like of shape (n_classes,), default None) – Prior probabilities; the class proportions by default.
random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the MCD estimators.
- classes_¶
Class labels.
- Type:
ndarray of shape (n_classes,)
- priors_¶
Prior probabilities.
- Type:
ndarray of shape (n_classes,)
- means_¶
Robust class centers.
- Type:
ndarray of shape (n_classes, n_features)
- covariance_¶
Robust common covariance matrix.
- Type:
ndarray of shape (n_features, n_features)
- support_¶
Observations used by the reweighted pooled MCD; False marks outliers.
- Type:
ndarray of bool, shape (n_samples,)
References
Hubert, M. and Van Driessen, K. (2004). Fast and robust discriminant analysis. Computational Statistics & Data Analysis, 45(2), 301-320.
He, X. and Fung, W. K. (2000). High breakdown estimation for multiple populations with applications to discriminant analysis. Journal of Multivariate Analysis, 72(2), 151-162.
Examples
>>> import numpy as np >>> from robustmodels.multivariate import RobustLDA >>> rng = np.random.default_rng(0) >>> X = np.vstack([rng.normal(size=(50, 2)), rng.normal(size=(50, 2)) + 3]) >>> y = np.repeat([0, 1], 50) >>> X[:5] = [15, 15] # five outliers labeled as class 0 >>> lda = RobustLDA(random_state=0).fit(X, y) >>> lda.means_.round(1).tolist() [[-0.1, 0.2], [3.1, 3.0]] >>> lda.predict([[0, 0], [3, 3]]).tolist() [0, 1]
- decision_function(X)¶
Discriminant scores; with two classes, the score of the second minus the first.
- predict(X)¶
Class with the largest discriminant score.
- predict_proba(X)¶
Posterior probabilities of the classes under the normal model.
- class RobustQDA(*, alpha=0.5, priors=None, random_state=None)[source]¶
Robust quadratic discriminant analysis with the MCD (Hubert & Van Driessen 2004).
Assigns
xto the class with the largest-log det(S_k) / 2 - d_k(x)^2 / 2 + log(prior_k), where the center and covarianceS_kof each class are its reweightedMCDestimates andd_kis the robust distance to classk. Every class needs more observations than variables.- Parameters:
alpha (float in [0.5, 1], default 0.5) – Coverage of the MCD estimators.
priors (array-like of shape (n_classes,), default None) – Prior probabilities; the class proportions by default.
random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the MCD estimators.
- classes_¶
Class labels.
- Type:
ndarray of shape (n_classes,)
- priors_¶
Prior probabilities.
- Type:
ndarray of shape (n_classes,)
- means_¶
Robust class centers.
- Type:
ndarray of shape (n_classes, n_features)
- covariances_¶
Robust covariance matrix of each class.
- Type:
ndarray of shape (n_classes, n_features, n_features)
References
Hubert, M. and Van Driessen, K. (2004). Fast and robust discriminant analysis. Computational Statistics & Data Analysis, 45(2), 301-320.
Examples
>>> import numpy as np >>> from robustmodels.multivariate import RobustQDA >>> rng = np.random.default_rng(0) >>> X = np.vstack([rng.normal(size=(50, 2)), 3 * rng.normal(size=(50, 2)) + 4]) >>> y = np.repeat(["a", "b"], 50) >>> qda = RobustQDA(random_state=0).fit(X, y) >>> qda.predict([[0, 0], [8, 8]]).tolist() ['a', 'b']
- decision_function(X)¶
Discriminant scores; with two classes, the score of the second minus the first.
- predict(X)¶
Class with the largest discriminant score.
- predict_proba(X)¶
Posterior probabilities of the classes under the normal model.
- hotelling_t2(X, mu=None, *, random_state=None)[source]¶
Robust one-sample Hotelling test (Willems, Pison, Rousseeuw & Van Aelst 2002).
Tests that the center of
XequalsmuwithT^2 = n (t - mu)' C^-1 (t - mu), wheretandCare the reweightedMCDlocation and covariance with coverage 0.75. Under the normal modelT^2 / dis approximatelyF(p, q);dandqmatch the mean and variance ofT^2, which the authors fitted to simulations for eachnandpand which tend to those of the asymptotic chi-square distribution. For paired samples, test the differences.- Parameters:
X (array-like of shape (n_samples, n_features))
mu (array-like of shape (n_features,), default None) – Hypothesized center; the origin by default.
random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the MCD.
- Returns:
Named tuple with
statistic(T^2),f_statistic(T^2 / d),df((p, q)),pvalueandlocation(the MCD center).- Return type:
HotellingResult
References
Willems, G., Pison, G., Rousseeuw, P. J. and Van Aelst, S. (2002). A robust Hotelling test. Metrika, 55, 125-138.
Examples
>>> import numpy as np >>> from robustmodels.multivariate import hotelling_t2 >>> X = np.random.default_rng(0).normal(size=(60, 3)) >>> X[:6] += 8 # outliers that would shift the sample mean >>> hotelling_t2(X, random_state=0).pvalue > 0.05 True >>> hotelling_t2(X, mu=[1, 1, 1], random_state=0).pvalue < 0.001 True
- manova(X, groups, *, alpha=0.5, n_simulations=500, random_state=None)[source]¶
Robust one-way MANOVA with Wilks’ lambda (Todorov & Filzmoser 2010).
Tests that all groups have the same mean vector, assuming a common covariance matrix. Observations get weight 1 when their squared robust distance to their own group center is below the 0.975 chi-square quantile and 0 otherwise; centers and common covariance are the reweighted pooled
MCDestimates ofRobustLDA, computed with the deterministic algorithm. Wilks’ lambda isdet(W) / det(T), withWandTthe within-group and total sums of squares and products of the observations with weight 1.Under the normal model the null distribution depends only on the group sizes and the dimension, so it is simulated with standard normal samples and the same estimator:
log(lambda) / dis treated as chi-square withqdegrees of freedom, wheredandqmatch the simulated mean and variance oflog(lambda). With two groups this is a robust two-sample Hotelling test. The simulation takes most of the time, which is why the deterministic MCD is used; R’srrcov::Wilks.testsearches with FAST-MCD and can find other subsets, hence another lambda.- Parameters:
X (array-like of shape (n_samples, n_features))
groups (array-like of shape (n_samples,)) – Group label of each observation.
alpha (float in [0.5, 1], default 0.5) – Coverage of the MCD estimators.
n_simulations (int, default 500) – Normal samples used to approximate the null distribution. Each needs one MCD per group and one for the pooled data.
random_state (int, numpy.random.Generator, numpy.random.RandomState or None) – Seed of the simulation.
- Returns:
Named tuple with
statistic(Wilks’ lambda),chi2_statistic(log(lambda) / d),df(q),pvalueandmeans(the weighted group means, in the sorted order of the labels).- Return type:
ManovaResult
References
Todorov, V. and Filzmoser, P. (2010). Robust statistic for the one-way MANOVA. Computational Statistics & Data Analysis, 54(1), 37-48.
Examples
>>> import numpy as np >>> from robustmodels.multivariate import manova >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=(90, 2)) >>> groups = np.repeat([0, 1, 2], 30) >>> X[:4] += 9 # outliers in the first group >>> manova(X, groups, n_simulations=100, random_state=0).pvalue > 0.05 True >>> X[groups == 2] += 1.5 # a real shift >>> manova(X, groups, n_simulations=100, random_state=0).pvalue < 0.001 True