Algorithmadvanced
Minimum covariance determinant
Also called MCD estimator, FAST-MCD.
Estimates location and scatter from the h points whose covariance matrix has the least determinant. FAST-MCD uses concentration steps; the result flags multivariate outliers.
- Time
- O(m t (n p² + p³ + n log n)) worst · averageO(m (n p² + p³ + n log n)) best
- Space
- O(n + p²) extra
- Where
- m = the number of random starts; n = the number of points; p = the dimension; t = the number of C-steps for each start
- Model
- Real RAM
- Properties
- randomizednot exact in exact arithmeticnot in placeofflinerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter J. Rousseeuw, Katrien Van Driessen, 1984
The minimum covariance determinant (MCD) estimator of multivariate location and scatter looks at all subsets of of the points. It keeps the subset whose covariance matrix has the least determinant, and it returns the mean and a scaled covariance matrix of that subset. The determinant measures the volume of the ellipsoid of the data, so the MCD subset is the tightest group of points. With near , the estimator has a breakdown point near one half and is affine equivariant. An exact search costs determinants, so the FAST-MCD algorithm of Rousseeuw and Van Driessen (1999) starts from many small random subsets and improves each one by C-steps. A C-step never increases the determinant. Distances from the MCD fit then flag multivariate outliers.
In plain words
The ordinary mean and covariance of a cloud of points are pulled away by a few bad points. The MCD finds the most compact half of the points, or a bit more than half, and computes the center and the spread from those points only. To find that compact group, FAST-MCD starts from a few random points. It measures how far every point lies from their center, taking the shape of the cloud into account, and it keeps the closest points. Then it repeats this with the kept points. Each round makes the group at least as compact as before. It does this from many starts and keeps the best result. Points that lie far from the final center are flagged as outliers.
The problem
The input is points and an integer with . The default is . For a set of indices, let be the mean and the covariance matrix of its points.
- The raw MCD is , where minimizes over all sets of indices.
- The squared Mahalanobis distance of a point from a fit is .
- The consistency factor , with , the -quantile of the chi-squared distribution with degrees of freedom, and the chi-squared distribution function with degrees of freedom. The raw scatter is reported as , which estimates at the normal model .
- The reweighted MCD keeps the points with under the raw fit, and returns their mean and their covariance times .
The algorithm
FAST-MCD(x_1..x_n, h, m)- 1
for j ← 1 to m do - 2
J ← a random set of p + 1 indices; while S(J) is singular, add a random index to J - 3
(μ, S) ← the mean and the covariance matrix of the points in J - 4
H ← the indices of the h points with the least d²(x_i; μ, S) - 5
repeat ▷ C-steps - 6
(μ, S) ← (T(H), S(H)) - 7
if det S = 0 then stop ▷ h points on a hyperplane: an exact fit - 8
H' ← the indices of the h points with the least d²(x_i; μ, S) - 9
if H' = H or det S(H') ≥ det S then stop, else H ← H' - 10
if det S is the least so far then (μ*, S*) ← (μ, S) - 11
S* ← c_α S* with α = h/n - 12
w_i ← 1 if d²(x_i; μ*, S*) ≤ χ²_{p,0.975}, else 0 - 13
μ_w ← the mean of the points with w_i = 1; S_w ← (0.975 / F_{p+2}(χ²_{p,0.975})) × their covariance matrix - 14
return (μ*, S*), (μ_w, S_w), and the outlier flags d²(x_i; μ_w, S_w) > χ²_{p,0.975}
Lines L5 to L9 are the C-steps ("C" for concentration). Each one computes the mean and the covariance of the current points and keeps the points that are closest to them in Mahalanobis distance.
Example
Take points in the plane, and :
The first seven points form a cloud, and are outliers. The sample mean of all ten points is .
Start from , a set with one outlier. Its mean is . Each point of has , and the next smallest distances are those of , and . All computations below are exact.
| step | |||
|---|---|---|---|
| 1 | {3, 5, 6, 7, 8, 9} | (37/6, 8/3) | 3397/108 ≈ 31.45 |
| 2 | {3, 4, 5, 6, 7, 8} | (29/6, 8/3) | 1909/108 ≈ 17.68 |
| 3 | {2, 3, 4, 5, 6, 7} | (10/3, 10/3) | 413/108 ≈ 3.82 |
| 4 | {1, 3, 4, 5, 6, 7} | (7/2, 3) | 85/36 ≈ 2.36 |
The C-step from step 4 returns the same set, so the loop stops. The determinant fell at every step, and the outliers left the set one by one. An enumeration of all sets confirms that is the least determinant, so this start found the raw MCD: and .
Not every start succeeds. Of the 119 nonsingular starts with 3 points, 43 reach . The others stop at 7 other sets. For example, the start stops at , which holds the outlier and has determinant . This is why FAST-MCD uses many starts.
With the consistency factor is . The clean point is outside , but its distance under the corrected raw fit is , below , so the reweighting step brings it back. The reweighted mean is the mean of the seven clean points, . The final squared distances of are 45.8, 43.7 and 32.7, so exactly these three points are flagged.
Correctness
The page proves the C-step theorem and the termination of the loop. It does not prove that FAST-MCD finds the MCD subset, and in general it does not. proofs/correctness.md has the full proofs.
- The C-step theorem (Rousseeuw and Van Driessen 1999). Let come from a C-step from , with . Inside the squared distances add up to . takes the smallest distances, so their sum is at most . That sum equals . So . The eigenvalues of are nonnegative, their product is , and their mean is at most 1. The inequality of the arithmetic and geometric means gives . Equality forces and .
- Termination. Line L9 accepts only a strictly smaller determinant, so no set comes back, and the loop stops after at most passes. At the stop, the next C-step does not change the mean or the covariance matrix.
- The optimum is a stopping point. A C-step from cannot lower the determinant further, so it keeps and . Other sets can also be stopping points, as the example shows. FAST-MCD finds when the C-steps from at least one start reach it.
- The consistency factor. For a standard normal vector , , because for the chi-squared densities. Line L11 removes this factor.
Proof: A C-step never increases the determinant, and the concentration loop stopsfull
This proof covers the C-step and the loop of FAST-MCD. It does not prove that FAST-MCD finds the MCD subset: it does not always find it. The breakdown point, the consistency and the efficiency of the MCD are cited on the main page and are not proved here.
Notation. The points are and . For a set of indices put
If is nonsingular, put . A C-step from returns a set of indices with the least values of , with ties broken in any way. Write and .
Lemma 1 (the distances inside add up to ). If is nonsingular, then .
Proof. A scalar equals its trace, and . So
Lemma 2 (moving the center). For every ,
Proof. Write and expand. The two cross terms contain , so they vanish.
Lemma 3 (eigenvalues of ). Let be symmetric positive definite and symmetric positive semidefinite. Then has real eigenvalues , with and . If every equals 1, then .
Proof. Let be the symmetric positive definite square root of . Then , so is similar to . is symmetric, and , so its eigenvalues are real and nonnegative. Similar matrices have the same trace, determinant and eigenvalues, and . If every eigenvalue of the symmetric matrix is 1, then , so .
Theorem (the C-step). Let and let be the result of a C-step from . Then
and holds only if and .
Proof. holds the least values of , and is one set of indices, so by Lemma 1
Use the trace as in Lemma 1 and then Lemma 2 with and . With ,
This gives the first inequality. Since is positive definite, , so . Let be the eigenvalues of (Lemma 3 with and ). The inequality of the arithmetic and geometric means gives
Now suppose . Then every inequality in the chain is an equality. So , which forces , so and . Equality in the inequality of the means holds only if all are equal, and their mean is 1, so every , and Lemma 3 gives .
Corollary 1 (the loop stops). In exact arithmetic, the loop of lines L5 to L9 stops after at most passes. When it stops at a set with , the C-step from gives the same mean and the same covariance matrix as .
Proof. Line L9 accepts only if . So the determinants of the accepted sets strictly decrease, no set is accepted twice, and there are sets. If an accepted set has determinant 0, line L7 stops. Otherwise line L9 stops when or . In the first case the claim is clear. In the second case the theorem gives , so the two are equal, and the theorem gives and .
Corollary 2 (the MCD subset is a fixed point). Let minimize over all sets of indices, with . Then every C-step from gives the mean and the covariance matrix .
Proof. By the theorem the C-step gives a set with , and by the minimality of the two are equal. The equality case of the theorem completes the proof.
So FAST-MCD returns the MCD subset if the C-steps from at least one start reach it. Corollary 2 shows that the MCD subset is among the stopping points, but other sets can be stopping points too, and a random start does not always lead to the best one.
Lemma 4 (the form of the consistency factor). Let , , and let be the -quantile of the chi-squared distribution with degrees of freedom. Then
where is the chi-squared distribution function with degrees of freedom.
Proof. The law of and the event are invariant under orthogonal maps, so the conditional covariance is a multiple , and . has the chi-squared density . Since , . So
At the normal model , the population MCD region is the ellipsoid . This fact is cited, not proved here (see Hubert, Debruyne and Rousseeuw 2018). Lemma 4, applied to , then shows that the raw scatter estimates . Line L11 divides by this factor. The same computation with in place of gives the factor of line L13.
Complexity
- One C-step. The mean and the covariance cost . The inverse and the determinant cost . The distances cost . The smallest distances cost with quickselect, or with a sort as in the implementation.
- All starts. With starts and at most C-steps for each, the total is . In practice is small: the C-steps of the example stopped after 4 steps. There is no useful bound on other than .
- Number of starts. A random -subset contains no outlier with probability about , so the number of starts needed grows exponentially in .
- Exact computation. The enumeration of all -subsets costs determinants. This is feasible only for small , as in the tests.
- Space. besides the input.
Properties
Proved on this page: the C-step theorem, the termination of the C-steps, the fixed-point property of the optimum, and the form of the consistency factor. Cited: the breakdown point, the consistency and the efficiency. Measured: the numbers from the tests.
- Breakdown point (cited). For points in general position, the finite-sample breakdown point of the raw MCD is (Lopuhaä and Rousseeuw 1991; Hubert, Debruyne and Rousseeuw 2018). It is largest, , for . The term comes from implosion: replaced points on a hyperplane through good points make an -subset with determinant 0. In the example, . The reweighted MCD keeps the breakdown point of the raw MCD.
- Efficiency (cited). The raw MCD with has a low efficiency at the normal: about 6% when . The reweighting step raises it to about 45.5% for (Hubert, Debruyne and Rousseeuw 2018).
- Equivariance. and are affine equivariant, and the Mahalanobis order of the points does not change under an affine map. So the exact MCD and the C-steps are affine equivariant. With the same random starts, FAST-MCD is too. The tests confirm this exactly on the example.
- Bounded influence (cited). The influence function of the MCD is bounded (Hubert, Debruyne and Rousseeuw 2018).
- Measured. For and , the tests compare FAST-MCD with the enumeration of all -subsets in exact arithmetic. Taking every -subset as a start found the exact MCD determinant on all of the random contaminated sets tried. With 30 random starts it found it on 12 of 12 sets. In a larger trial outside the tests, 30 random starts missed the optimum on 2 of 115 sets, so the test allows a few misses. On 80 normal points in with 20 points shifted by 6 in each coordinate, the reweighted MCD flagged all 20 shifted points and 1 of the 80 clean points, and its location was at distance 0.22 from the true center. The distance of the sample mean was 2.05.
Variants and improvements
- Selective iteration. FAST-MCD of Rousseeuw and Van Driessen (1999) runs only two C-steps from each start, keeps the 10 best sets, and runs those to convergence. For large it works on disjoint subsamples first and merges them.
- Deterministic MCD. Start from a few deterministic robust estimates instead of random subsets, as described in the survey of Hubert, Debruyne and Rousseeuw (2018).
- Small-sample corrections. Extra factors make the scatter nearly unbiased at the normal for small .
- Minimum volume ellipsoid. The MVE, also defined by Rousseeuw (1984), minimizes the volume of a covering ellipsoid of points. It has the same breakdown point and worse efficiency.
- Regularized MCD. For , the sample covariance of points is singular. A regularized MCD adds a multiple of a target matrix.
- Uses. Robust Mahalanobis distances for outlier detection, robust principal components (see robust PCA), robust discriminant analysis, and starts for MM-estimators of multivariate location and of regression.
When to use it
Use the MCD to estimate a center and a covariance matrix of moderate-dimensional data ( up to a few dozen) when a sizeable fraction of the points may be outliers, and to flag multivariate outliers that no single coordinate shows. Use the classical mean and covariance on clean data. Use coordinatewise robust estimates, such as the median and the MAD, when affine equivariance is not needed. In high dimension, where random subsets almost never avoid the outliers, use a spectral method such as the robust mean estimation filter, or a regularized MCD.
Pitfalls
- The breakdown formula. The breakdown point is , not . The two agree only when .
- Forgetting the consistency factor. comes from the most compact half of the data, so it is far too small. For and , the factor is .
- Not the global optimum. FAST-MCD gives a local optimum. Too few starts can miss the MCD subset, in particular when is large or the outliers are many.
- must exceed . For every covariance matrix of points is singular. Exact fits, with more than points on a hyperplane, give determinant 0: then report the hyperplane rather than invert .
- The cutoff is approximate. The cutoff assumes normal data and large . With small , many clean points can be flagged.
- Floating point. Comparing determinants that differ only by rounding can make the C-steps cycle. Stop when the determinant does not decrease, as line L9 does.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-covariance-determinant/. The authors are listed in prov/KD8XYJ.jsonl.
import itertools
import random
from stdist import chi2_cdf, chi2_ppf
# The arithmetic below is generic: with int or Fraction coordinates every
# determinant, distance and comparison is exact; with floats it is ordinary
# floating point.
def mean(points, idx):
"""The mean of the points with the given indices."""
k = len(idx)
p = len(points[0])
return [sum(points[i][j] for i in idx) / k for j in range(p)]
def cov(points, idx, mu=None):
"""The covariance matrix of the points with the given indices, with divisor len(idx)."""
if mu is None:
mu = mean(points, idx)
k = len(idx)
p = len(mu)
return [
[sum((points[i][a] - mu[a]) * (points[i][b] - mu[b]) for i in idx) / k for b in range(p)]
for a in range(p)
]
def det(m):
"""The determinant by Gaussian elimination with partial pivoting."""
a = [list(row) for row in m]
p = len(a)
d = 1
for col in range(p):
piv = max(range(col, p), key=lambda r: abs(a[r][col]))
if a[piv][col] == 0:
return 0
if piv != col:
a[col], a[piv] = a[piv], a[col]
d = -d
d = d * a[col][col]
for r in range(col + 1, p):
f = a[r][col] / a[col][col]
for k in range(col, p):
a[r][k] -= f * a[col][k]
return d
def inverse(m):
"""The inverse by Gauss-Jordan elimination; the matrix must be nonsingular."""
p = len(m)
a = [list(row) + [1 if i == j else 0 for j in range(p)] for i, row in enumerate(m)]
for col in range(p):
piv = max(range(col, p), key=lambda r: abs(a[r][col]))
if a[piv][col] == 0:
raise ZeroDivisionError("singular matrix")
a[col], a[piv] = a[piv], a[col]
f = a[col][col]
a[col] = [v / f for v in a[col]]
for r in range(p):
if r != col and a[r][col] != 0:
g = a[r][col]
a[r] = [v - g * w for v, w in zip(a[r], a[col])]
return [row[p:] for row in a]
def mahalanobis2(x, mu, s_inv):
"""The squared Mahalanobis distance (x - mu)^T S^{-1} (x - mu)."""
z = [a - b for a, b in zip(x, mu)]
return sum(z[a] * s_inv[a][b] * z[b] for a in range(len(z)) for b in range(len(z)))
def singular(s):
"""True if S is singular: exactly for exact numbers, relative to its diagonal for floats."""
d = det(s)
if isinstance(d, float):
hadamard = 1.0
for i in range(len(s)):
hadamard *= s[i][i]
return d <= 1e-12 * hadamard or hadamard == 0.0
return d == 0
def closest(points, mu, s, h):
"""The indices of the h points with the least Mahalanobis distance; ties go to the lower index."""
s_inv = inverse(s)
d = [mahalanobis2(x, mu, s_inv) for x in points]
return sorted(sorted(range(len(points)), key=lambda i: (d[i], i))[:h])
def c_step(points, idx, h):
"""One concentration step: the h points closest to the mean and covariance of idx."""
mu = mean(points, idx)
s = cov(points, idx, mu)
return closest(points, mu, s, h)
def concentrate(points, idx, h, max_steps=100):
"""C-steps from the h-subset idx until the determinant stops decreasing.
Returns (det, H, mu, S) for the best h-subset reached. If its covariance is
singular (det 0), that subset is an exact fit and is returned at once.
"""
mu = mean(points, idx) # @line L6
s = cov(points, idx, mu)
d = det(s)
for _ in range(max_steps): # @line L5
if singular(s): # @line L7
break
new = closest(points, mu, s, h) # @line L8
new_mu = mean(points, new)
new_s = cov(points, new, new_mu)
new_d = det(new_s)
if new == idx or new_d >= d: # @line L9
break
idx, mu, s, d = new, new_mu, new_s, new_d # @line L6
return d, idx, mu, s
def start_subset(points, h, rng):
"""A random (p + 1)-subset, enlarged until its covariance is nonsingular, then its h closest points."""
n, p = len(points), len(points[0])
order = list(range(n))
rng.shuffle(order)
k = p + 1
while singular(cov(points, order[:k])): # @line L2
k += 1
if k > n:
return None
j = order[:k]
mu = mean(points, j) # @line L3
s = cov(points, j, mu)
return closest(points, mu, s, h) # @line L4
def default_h(n, p):
"""floor((n + p + 1) / 2), the h with the highest breakdown point."""
return (n + p + 1) // 2
def fast_mcd_raw(points, h=None, starts=500, seed=0, max_steps=100):
"""The raw FAST-MCD fit: (det, H, mu, S) with S the covariance of H with divisor h.
starts is the number of random starts; if it is None, every (p + 1)-subset is
used once as the start, which makes the result deterministic.
"""
n, p = len(points), len(points[0])
if h is None:
h = default_h(n, p)
if not p < h <= n:
raise ValueError("need p < h <= n")
rng = random.Random(seed)
best = None
if starts is None:
pool = itertools.combinations(range(n), p + 1)
else:
pool = range(starts)
for item in pool: # @line L1
if starts is None:
j = list(item)
if singular(cov(points, j)):
continue
mu = mean(points, j)
idx = closest(points, mu, cov(points, j, mu), h)
else:
idx = start_subset(points, h, rng)
if idx is None:
continue
fit = concentrate(points, idx, h, max_steps)
if best is None or fit[0] < best[0]: # @line L10
best = fit
if best is None:
raise ValueError("every start was singular")
return best
def exact_mcd(points, h=None):
"""The exact raw MCD by enumeration of all h-subsets: (det, H). Only for small n."""
n, p = len(points), len(points[0])
if h is None:
h = default_h(n, p)
best = None
for idx in itertools.combinations(range(n), h):
d = det(cov(points, list(idx)))
if best is None or d < best[0]:
best = (d, list(idx))
return best
def consistency_factor(alpha, p):
"""alpha / F_{chi2(p+2)}(chi2_{p, alpha}): it makes the raw MCD scatter consistent at the normal."""
return alpha / chi2_cdf(chi2_ppf(alpha, p), p + 2)
def mcd(points, h=None, starts=500, seed=0, delta=0.025):
"""FAST-MCD with the consistency factor and one reweighting step, in floating point.
Returns a dict with the raw location and scatter, the reweighted location and
scatter, the h-subset, and the outlier flags of the reweighting step.
"""
pts = [[float(v) for v in x] for x in points]
n, p = len(pts), len(pts[0])
if h is None:
h = default_h(n, p)
_, idx, mu, s = fast_mcd_raw(pts, h, starts, seed)
c = consistency_factor(h / n, p) # @line L11
s = [[c * v for v in row] for row in s]
cut = chi2_ppf(1.0 - delta, p)
s_inv = inverse(s)
d2 = [mahalanobis2(x, mu, s_inv) for x in pts]
keep = [i for i in range(n) if d2[i] <= cut] # @line L12
mu_w = mean(pts, keep) # @line L13
c_w = (1.0 - delta) / chi2_cdf(cut, p + 2)
s_w = [[c_w * v for v in row] for row in cov(pts, keep, mu_w)]
s_w_inv = inverse(s_w)
flags = [mahalanobis2(x, mu_w, s_w_inv) > cut for x in pts]
return { # @line L14
"raw_location": mu,
"raw_scatter": s,
"subset": idx,
"location": mu_w,
"scatter": s_w,
"outlier": flags,
"distance2": [mahalanobis2(x, mu_w, s_w_inv) for x in pts],
}
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_minimum_covariance_determinant.py 216 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-covariance-determinant/. The authors are listed in prov/KD8XYJ.jsonl.
import itertools
import math
import random
from fractions import Fraction as F
import pytest
from minimum_covariance_determinant import (
c_step,
closest,
concentrate,
consistency_factor,
cov,
det,
default_h,
exact_mcd,
fast_mcd_raw,
inverse,
mahalanobis2,
mcd,
mean,
)
EXAMPLE = [(2, 1), (1, 3), (5, 4), (3, 2), (4, 1), (3, 4), (4, 6), (10, -1), (11, 2), (10, 10)]
def exact(points):
return [tuple(F(v) for v in x) for x in points]
def random_data(rng, n, k):
"""n - k clean integer points near the origin and k far points, as Fractions."""
clean = [(F(rng.randint(-5, 5)), F(rng.randint(-5, 5))) for _ in range(n - k)]
far = [(F(rng.randint(8, 20)), F(rng.randint(-20, 20))) for _ in range(k)]
return clean + far
def test_example_trace():
pts = exact(EXAMPLE)
h = 6
j = [2, 6, 7]
mu = mean(pts, j)
idx = closest(pts, mu, cov(pts, j, mu), h)
path = [idx]
while True:
new = c_step(pts, idx, h)
if new == idx:
break
idx = new
path.append(idx)
assert path == [[2, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6], [0, 2, 3, 4, 5, 6]]
dets = [det(cov(pts, q)) for q in path]
assert dets == [F(3397, 108), F(1909, 108), F(413, 108), F(85, 36)]
assert exact_mcd(pts, h) == (F(85, 36), [0, 2, 3, 4, 5, 6])
assert mean(pts, path[-1]) == [F(7, 2), F(3)]
assert cov(pts, path[-1]) == [[F(11, 12), F(5, 6)], [F(5, 6), F(10, 3)]]
def test_example_stopping_points():
pts = exact(EXAMPLE)
h = 6
ends = {}
for j in itertools.combinations(range(10), 3):
j = list(j)
if det(cov(pts, j)) == 0:
continue
d, idx, _, _ = concentrate(pts, closest(pts, mean(pts, j), cov(pts, j), h), h)
ends.setdefault((tuple(idx), d), []).append(j)
assert sum(len(v) for v in ends.values()) == 119
assert len(ends) == 8
assert len(ends[((0, 2, 3, 4, 5, 6), F(85, 36))]) == 43
assert [0, 1, 7] in ends[((0, 1, 3, 4, 5, 7), F(973, 108))]
def test_example_reweighted():
r = mcd(EXAMPLE, h=6, starts=50)
assert r["subset"] == [0, 2, 3, 4, 5, 6]
assert r["outlier"] == [False] * 7 + [True] * 3
assert r["location"] == pytest.approx([22 / 7, 3.0])
raw_inv = inverse(r["raw_scatter"])
assert mahalanobis2(EXAMPLE[1], r["raw_location"], raw_inv) == pytest.approx(3.43, abs=0.005)
assert [round(v, 1) for v in r["distance2"][7:]] == [45.8, 43.7, 32.7]
assert consistency_factor(0.6, 2) == pytest.approx(2.56977, abs=1e-5)
def test_fast_mcd_matches_full_enumeration():
"""p = 2 and n <= 12: every (p + 1)-subset as a start finds the exact MCD determinant."""
rng = random.Random(1)
checked = 0
for _ in range(14):
n = rng.randint(6, 12)
pts = random_data(rng, n, rng.randint(0, (n - 1) // 2))
h = default_h(n, 2)
best, _ = exact_mcd(pts, h)
if best == 0:
continue
checked += 1
assert fast_mcd_raw(pts, h, starts=None)[0] == best
assert checked >= 10
def test_random_starts_match_enumeration_on_most_sets():
"""Measured: 30 random starts find the exact optimum on most small sets, not on all."""
rng = random.Random(2)
hits = total = 0
for t in range(12):
n = rng.randint(6, 11)
pts = random_data(rng, n, rng.randint(0, (n - 1) // 2))
h = default_h(n, 2)
best, _ = exact_mcd(pts, h)
got = fast_mcd_raw(pts, h, starts=30, seed=t)[0]
assert got >= best
total += 1
hits += got == best
assert hits >= total - 2
def test_c_step_never_increases_determinant():
rng = random.Random(3)
for _ in range(300):
n = rng.randint(5, 12)
pts = random_data(rng, n, rng.randint(0, n // 3))
h = rng.randint(3, n)
h1 = sorted(rng.sample(range(n), h))
mu1, s1 = mean(pts, h1), cov(pts, h1)
d1 = det(s1)
if d1 == 0:
continue
h2 = c_step(pts, h1, h)
mu2, s2 = mean(pts, h2), cov(pts, h2)
d2 = det(s2)
assert d2 <= d1
# The two inequalities of the proof, exactly.
s1_inv = inverse(s1)
tr = sum(s1_inv[a][b] * s2[b][a] for a in range(2) for b in range(2))
assert tr + mahalanobis2(mu2, mu1, s1_inv) <= 2
assert d2 / d1 <= (tr / 2) ** 2
if d2 == d1:
assert mu2 == mu1 and s2 == s1
def test_optimum_is_a_c_step_fixed_point():
rng = random.Random(4)
for _ in range(6):
n = rng.randint(6, 10)
pts = random_data(rng, n, 2)
h = default_h(n, 2)
best, idx = exact_mcd(pts, h)
if best == 0:
continue
new = c_step(pts, idx, h)
assert det(cov(pts, new)) == best
assert mean(pts, new) == mean(pts, idx)
def test_affine_equivariance():
pts = exact(EXAMPLE)
a = [[F(2), F(1)], [F(-1), F(3)]]
b = [F(5), F(-7)]
moved = [tuple(sum(a[i][j] * x[j] for j in range(2)) + b[i] for i in range(2)) for x in pts]
d0, idx0, _, _ = fast_mcd_raw(pts, 6, starts=None)
d1, idx1, _, _ = fast_mcd_raw(moved, 6, starts=None)
assert idx1 == idx0
assert d1 == det(a) ** 2 * d0
def test_consistency_factor_closed_form_for_two_dimensions():
# For p = 2: chi2_{2, alpha} = -2 log(1 - alpha) and F_4(x) = 1 - exp(-x/2)(1 + x/2).
for alpha in [0.5, 0.6, 0.75, 0.9, 0.975]:
want = alpha / (1.0 - (1.0 - alpha) * (1.0 - math.log(1.0 - alpha)))
assert consistency_factor(alpha, 2) == pytest.approx(want, rel=1e-10)
assert consistency_factor(0.5, 2) == pytest.approx(3.2589, abs=1e-4)
def test_flags_outliers_where_the_mean_fails():
"""Measured: 80 normal points in 3 dimensions and 20 points shifted by 6 in every coordinate."""
rng = random.Random(5)
clean = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(80)]
far = [[rng.gauss(6, 0.5) for _ in range(3)] for _ in range(20)]
r = mcd(clean + far, starts=60, seed=1)
assert all(r["outlier"][80:])
assert sum(r["outlier"][:80]) <= 6
err_mcd = math.sqrt(sum(v * v for v in r["location"]))
sample_mean = [sum(x[j] for x in clean + far) / 100 for j in range(3)]
err_mean = math.sqrt(sum(v * v for v in sample_mean))
assert err_mean > 1.8
assert err_mcd < 0.4
def test_consistency_on_clean_normal_data():
"""Measured: the corrected raw scatter has a determinant near 1; the reweighted scatter is near I."""
rng = random.Random(6)
pts = [[rng.gauss(0, 1), rng.gauss(0, 1)] for _ in range(600)]
r = mcd(pts, starts=10, seed=0)
assert abs(det(r["raw_scatter"]) - 1) < 0.2 # the raw shape is noisy: diagonal 1.32 and 0.68
s = r["scatter"]
assert abs(s[0][0] - 1) < 0.2 and abs(s[1][1] - 1) < 0.2 and abs(s[0][1]) < 0.15
c = consistency_factor(default_h(600, 2) / 600, 2)
assert det(r["raw_scatter"]) / c**2 < 0.15 # without the factor the scatter is far too small
def test_exact_fit_gives_zero_determinant():
pts = exact([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (0, 7), (6, 1)])
d, idx, _, _ = fast_mcd_raw(pts, 5, starts=None)
assert d == 0
assert all(pts[i][0] == pts[i][1] for i in idx)
def test_errors():
with pytest.raises(ValueError):
fast_mcd_raw(exact(EXAMPLE), h=2)
with pytest.raises(ValueError):
fast_mcd_raw(exact(EXAMPLE), h=11)
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
History
Rousseeuw (1984) introduced the MCD and the minimum volume ellipsoid as affine equivariant estimators of multivariate location and scatter with a high breakdown point. The exact computation was out of reach for all but small data sets, and the MVE was used more at first. Lopuhaä and Rousseeuw (1991) gave the breakdown points of affine equivariant estimators, including the MCD. Rousseeuw and Van Driessen (1999) proved the C-step theorem and gave FAST-MCD, which made the MCD practical and the more popular of the two. Hubert, Debruyne and Rousseeuw (2018) survey the estimator, its properties and its extensions.
References
- Peter J. Rousseeuw, Least median of squares regression, Journal of the American Statistical Association 79(388), 1984, pp. 871 to 880 (the definition of the minimum covariance determinant estimator)
- Peter J. Rousseeuw and Katrien Van Driessen, A fast algorithm for the minimum covariance determinant estimator, Technometrics 41(3), 1999, pp. 212 to 223 (the C-step theorem and the FAST-MCD algorithm)
- Mia Hubert, Michiel Debruyne and Peter J. Rousseeuw, Minimum covariance determinant and extensions, WIREs Computational Statistics 10(3), 2018, the survey of the MCD, its breakdown point, its consistency factor, its efficiency, the reweighting step and the C-step
- Hendrik P. Lopuhaä and Peter J. Rousseeuw, Breakdown points of affine equivariant estimators of multivariate location and covariance matrices, The Annals of Statistics 19(1), 1991, pp. 229 to 248 (the breakdown point of the MCD and its dependence on h)
- Peter J. Rousseeuw and Annick M. Leroy, Robust Regression and Outlier Detection, Wiley, 1987, the chapter on multivariate location and covariance (the MVE and the MCD)
- Ricardo A. Maronna, R. Douglas Martin, Victor J. Yohai and Matías Salibián-Barrera, Robust Statistics, Theory and Methods (with R), second edition, Wiley, 2019, the chapter on multivariate analysis (the MCD and its computation)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KD8XYJ Edit this page History Report an error Markdown