Algorithm Search⌘K

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
Properties
randomizednot exact in exact arithmeticnot in placeofflinerandomized
Origin
Peter J. Rousseeuw, Katrien Van Driessen, 1984

The minimum covariance determinant (MCD) estimator of multivariate location and scatter looks at all subsets of hh of the nn 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 hh points. With hh near n/2n/2, the estimator has a breakdown point near one half and is affine equivariant. An exact search costs (nh)\binom nh 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 nn points x1,…,xn∈Rpx_1, \ldots, x_n \in \mathbb R^p and an integer hh with p<h≤np < h \le n. The default is h=⌊(n+p+1)/2⌋h = \lfloor (n + p + 1)/2 \rfloor. For a set HH of hh indices, let T(H)T(H) be the mean and S(H)=1h∑i∈H(xi−T(H))(xi−T(H))TS(H) = \frac1h\sum_{i \in H}(x_i - T(H))(x_i - T(H))^{\mathsf T} the covariance matrix of its points.

  • The raw MCD is (T(H∗),S(H∗))(T(H^*), S(H^*)), where H∗H^* minimizes det⁡S(H)\det S(H) over all sets of hh indices.
  • The squared Mahalanobis distance of a point from a fit (T,S)(T, S) is d2(x;T,S)=(x−T)TS−1(x−T)d^2(x; T, S) = (x - T)^{\mathsf T}S^{-1}(x - T).
  • The consistency factor cα=α/Fp+2(qα)c_\alpha = \alpha / F_{p+2}(q_\alpha), with α=h/n\alpha = h/n, qαq_\alpha the α\alpha-quantile of the chi-squared distribution with pp degrees of freedom, and Fp+2F_{p+2} the chi-squared distribution function with p+2p + 2 degrees of freedom. The raw scatter is reported as cαS(H∗)c_\alpha S(H^*), which estimates Σ\Sigma at the normal model N(μ,Σ)N(\mu, \Sigma).
  • The reweighted MCD keeps the points with d2≤χp,0.9752d^2 \le \chi^2_{p, 0.975} under the raw fit, and returns their mean and their covariance times 0.975/Fp+2(χp,0.9752)0.975/F_{p+2}(\chi^2_{p,0.975}).

The algorithm

  1. FAST-MCD(x_1..x_n, h, m)
  2. 1for j ← 1 to m do
  3. 2J ← a random set of p + 1 indices; while S(J) is singular, add a random index to J
  4. 3(μ, S) ← the mean and the covariance matrix of the points in J
  5. 4H ← the indices of the h points with the least d²(x_i; μ, S)
  6. 5repeat ▷ C-steps
  7. 6(μ, S) ← (T(H), S(H))
  8. 7if det S = 0 then stop ▷ h points on a hyperplane: an exact fit
  9. 8H' ← the indices of the h points with the least d²(x_i; μ, S)
  10. 9if H' = H or det S(H') ≥ det S then stop, else H ← H'
  11. 10if det S is the least so far then (μ*, S*) ← (μ, S)
  12. 11S* ← c_α S* with α = h/n
  13. 12w_i ← 1 if d²(x_i; μ*, S*) ≤ χ²_{p,0.975}, else 0
  14. 13μ_w ← the mean of the points with w_i = 1; S_w ← (0.975 / F_{p+2}(χ²_{p,0.975})) × their covariance matrix
  15. 14return (μ*, 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 hh points and keeps the hh points that are closest to them in Mahalanobis distance.

Example

Take n=10n = 10 points in the plane, p=2p = 2 and h=6h = 6:

x1,…,x10=(2,1),(1,3),(5,4),(3,2),(4,1),(3,4),(4,6),(10,−1),(11,2),(10,10).x_1, \ldots, x_{10} = (2,1), (1,3), (5,4), (3,2), (4,1), (3,4), (4,6), (10,-1), (11,2), (10,10).

The first seven points form a cloud, and x8,x9,x10x_8, x_9, x_{10} are outliers. The sample mean of all ten points is (5.3,3.2)(5.3, 3.2).

Start from J={3,7,8}J = \{3, 7, 8\}, a set with one outlier. Its mean is (19/3,3)(19/3, 3). Each point of JJ has d2=2d^2 = 2, and the next smallest distances are those of x6x_6, x9x_9 and x5x_5. All computations below are exact.

step HH T(H)T(H) det⁡S(H)\det S(H)
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 (106)=210\binom{10}{6} = 210 sets confirms that 85/3685/36 is the least determinant, so this start found the raw MCD: T=(7/2,3)T = (7/2, 3) and S=(11/125/65/610/3)S = \begin{pmatrix} 11/12 & 5/6 \\ 5/6 & 10/3 \end{pmatrix}.

Not every start succeeds. Of the 119 nonsingular starts with 3 points, 43 reach H∗={1,3,4,5,6,7}H^* = \{1, 3, 4, 5, 6, 7\}. The others stop at 7 other sets. For example, the start {1,2,8}\{1, 2, 8\} stops at {1,2,4,5,6,8}\{1, 2, 4, 5, 6, 8\}, which holds the outlier x8x_8 and has determinant 973/108≈9.01973/108 \approx 9.01. This is why FAST-MCD uses many starts.

With α=0.6\alpha = 0.6 the consistency factor is c0.6=2.5698c_{0.6} = 2.5698. The clean point x2x_2 is outside HH, but its distance under the corrected raw fit is 3.433.43, below χ2,0.9752=7.378\chi^2_{2, 0.975} = 7.378, so the reweighting step brings it back. The reweighted mean is the mean of the seven clean points, (22/7,3)≈(3.14,3.00)(22/7, 3) \approx (3.14, 3.00). The final squared distances of x8,x9,x10x_8, x_9, x_{10} 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 H2H_2 come from a C-step from H1H_1, with det⁡S1>0\det S_1 > 0. Inside H1H_1 the squared distances add up to tr⁡(S1−1hS1)=hp\operatorname{tr}(S_1^{-1}hS_1) = hp. H2H_2 takes the hh smallest distances, so their sum is at most hphp. That sum equals htr⁡(S1−1S2)+h(T2−T1)TS1−1(T2−T1)h\operatorname{tr}(S_1^{-1}S_2) + h(T_2 - T_1)^{\mathsf T}S_1^{-1}(T_2 - T_1). So tr⁡(S1−1S2)≤p\operatorname{tr}(S_1^{-1}S_2) \le p. The eigenvalues of S1−1S2S_1^{-1}S_2 are nonnegative, their product is det⁡S2/det⁡S1\det S_2/\det S_1, and their mean is at most 1. The inequality of the arithmetic and geometric means gives det⁡S2≤det⁡S1\det S_2 \le \det S_1. Equality forces T2=T1T_2 = T_1 and S2=S1S_2 = S_1.
  • Termination. Line L9 accepts only a strictly smaller determinant, so no set comes back, and the loop stops after at most (nh)\binom nh 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 H∗H^* cannot lower the determinant further, so it keeps T(H∗)T(H^*) and S(H∗)S(H^*). Other sets can also be stopping points, as the example shows. FAST-MCD finds H∗H^* when the C-steps from at least one start reach it.
  • The consistency factor. For a standard normal vector XX, E[XXT∣∥X∥2≤qα]=Fp+2(qα)αI\mathbb E[XX^{\mathsf T} \mid \|X\|^2 \le q_\alpha] = \frac{F_{p+2}(q_\alpha)}{\alpha}I, because ufp(u)=pfp+2(u)u f_p(u) = p f_{p+2}(u) 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 x1,…,xn∈Rpx_1, \ldots, x_n \in \mathbb R^p and p<h≤np < h \le n. For a set HH of hh indices put

T(H)=1h∑i∈Hxi,S(H)=1h∑i∈H(xi−T(H))(xi−T(H))T.T(H) = \frac1h\sum_{i \in H} x_i, \qquad S(H) = \frac1h\sum_{i \in H}(x_i - T(H))(x_i - T(H))^{\mathsf T}.

If S(H)S(H) is nonsingular, put dH(i)2=(xi−T(H))TS(H)−1(xi−T(H))d_H(i)^2 = (x_i - T(H))^{\mathsf T}S(H)^{-1}(x_i - T(H)). A C-step from H1H_1 returns a set H2H_2 of hh indices with the hh least values of dH1(i)2d_{H_1}(i)^2, with ties broken in any way. Write Tk=T(Hk)T_k = T(H_k) and Sk=S(Hk)S_k = S(H_k).

Lemma 1 (the distances inside HH add up to hphp). If S(H)S(H) is nonsingular, then ∑i∈HdH(i)2=hp\sum_{i \in H} d_H(i)^2 = hp.

Proof. A scalar equals its trace, and tr⁡(AB)=tr⁡(BA)\operatorname{tr}(AB) = \operatorname{tr}(BA). So

∑i∈HdH(i)2=tr⁡(S(H)−1∑i∈H(xi−T(H))(xi−T(H))T)=tr⁡(S(H)−1 h S(H))=hp.□\sum_{i \in H} d_H(i)^2 = \operatorname{tr}\Bigl(S(H)^{-1}\sum_{i \in H}(x_i - T(H))(x_i - T(H))^{\mathsf T}\Bigr) = \operatorname{tr}\bigl(S(H)^{-1}\,h\,S(H)\bigr) = hp. \qquad \square

Lemma 2 (moving the center). For every m∈Rpm \in \mathbb R^p,

1h∑i∈H(xi−m)(xi−m)T=S(H)+(T(H)−m)(T(H)−m)T.\frac1h\sum_{i \in H}(x_i - m)(x_i - m)^{\mathsf T} = S(H) + (T(H) - m)(T(H) - m)^{\mathsf T}.

Proof. Write xi−m=(xi−T(H))+(T(H)−m)x_i - m = (x_i - T(H)) + (T(H) - m) and expand. The two cross terms contain ∑i∈H(xi−T(H))=0\sum_{i \in H}(x_i - T(H)) = 0, so they vanish. □\square

Lemma 3 (eigenvalues of A−1BA^{-1}B). Let AA be symmetric positive definite and BB symmetric positive semidefinite. Then A−1BA^{-1}B has real eigenvalues λ1,…,λp≥0\lambda_1, \ldots, \lambda_p \ge 0, with ∑jλj=tr⁡(A−1B)\sum_j\lambda_j = \operatorname{tr}(A^{-1}B) and ∏jλj=det⁡B/det⁡A\prod_j\lambda_j = \det B/\det A. If every λj\lambda_j equals 1, then B=AB = A.

Proof. Let A1/2A^{1/2} be the symmetric positive definite square root of AA. Then A−1B=A−1/2 (A−1/2BA−1/2) A1/2A^{-1}B = A^{-1/2}\,(A^{-1/2}BA^{-1/2})\,A^{1/2}, so A−1BA^{-1}B is similar to C=A−1/2BA−1/2C = A^{-1/2}BA^{-1/2}. CC is symmetric, and zTCz=(A−1/2z)TB(A−1/2z)≥0z^{\mathsf T}Cz = (A^{-1/2}z)^{\mathsf T}B(A^{-1/2}z) \ge 0, so its eigenvalues are real and nonnegative. Similar matrices have the same trace, determinant and eigenvalues, and det⁡C=det⁡B/det⁡A\det C = \det B/\det A. If every eigenvalue of the symmetric matrix CC is 1, then C=IC = I, so B=A1/2A1/2=AB = A^{1/2}A^{1/2} = A. □\square

Theorem (the C-step). Let det⁡S1>0\det S_1 > 0 and let H2H_2 be the result of a C-step from H1H_1. Then

tr⁡(S1−1S2)+(T2−T1)TS1−1(T2−T1)≤panddet⁡S2≤det⁡S1,\operatorname{tr}(S_1^{-1}S_2) + (T_2 - T_1)^{\mathsf T}S_1^{-1}(T_2 - T_1) \le p \quad\text{and}\quad \det S_2 \le \det S_1,

and det⁡S2=det⁡S1\det S_2 = \det S_1 holds only if T2=T1T_2 = T_1 and S2=S1S_2 = S_1.

Proof. H2H_2 holds the hh least values of dH1(i)2d_{H_1}(i)^2, and H1H_1 is one set of hh indices, so by Lemma 1

∑i∈H2dH1(i)2≤∑i∈H1dH1(i)2=hp.\sum_{i \in H_2} d_{H_1}(i)^2 \le \sum_{i \in H_1} d_{H_1}(i)^2 = hp.

Use the trace as in Lemma 1 and then Lemma 2 with H=H2H = H_2 and m=T1m = T_1. With δ=T2−T1\delta = T_2 - T_1,

1h∑i∈H2dH1(i)2=tr⁡(S1−1 1h∑i∈H2(xi−T1)(xi−T1)T)=tr⁡(S1−1S2)+δTS1−1δ.\frac1h\sum_{i \in H_2} d_{H_1}(i)^2 = \operatorname{tr}\Bigl(S_1^{-1}\,\frac1h\sum_{i \in H_2}(x_i - T_1)(x_i - T_1)^{\mathsf T}\Bigr) = \operatorname{tr}(S_1^{-1}S_2) + \delta^{\mathsf T}S_1^{-1}\delta.

This gives the first inequality. Since S1−1S_1^{-1} is positive definite, δTS1−1δ≥0\delta^{\mathsf T}S_1^{-1}\delta \ge 0, so tr⁡(S1−1S2)≤p\operatorname{tr}(S_1^{-1}S_2) \le p. Let λ1,…,λp≥0\lambda_1, \ldots, \lambda_p \ge 0 be the eigenvalues of S1−1S2S_1^{-1}S_2 (Lemma 3 with A=S1A = S_1 and B=S2B = S_2). The inequality of the arithmetic and geometric means gives

det⁡S2det⁡S1=∏jλj≤(1p∑jλj)p=(tr⁡(S1−1S2)p)p≤1.\frac{\det S_2}{\det S_1} = \prod_j\lambda_j \le \Bigl(\frac1p\sum_j\lambda_j\Bigr)^p = \Bigl(\frac{\operatorname{tr}(S_1^{-1}S_2)}{p}\Bigr)^p \le 1.

Now suppose det⁡S2=det⁡S1\det S_2 = \det S_1. Then every inequality in the chain is an equality. So 1p∑jλj=1\frac1p\sum_j\lambda_j = 1, which forces δTS1−1δ=0\delta^{\mathsf T}S_1^{-1}\delta = 0, so δ=0\delta = 0 and T2=T1T_2 = T_1. Equality in the inequality of the means holds only if all λj\lambda_j are equal, and their mean is 1, so every λj=1\lambda_j = 1, and Lemma 3 gives S2=S1S_2 = S_1. □\square

Corollary 1 (the loop stops). In exact arithmetic, the loop of lines L5 to L9 stops after at most (nh)\binom nh passes. When it stops at a set HH with det⁡S(H)>0\det S(H) > 0, the C-step from HH gives the same mean and the same covariance matrix as HH.

Proof. Line L9 accepts H′H' only if det⁡S(H′)<det⁡S(H)\det S(H') < \det S(H). So the determinants of the accepted sets strictly decrease, no set is accepted twice, and there are (nh)\binom nh sets. If an accepted set has determinant 0, line L7 stops. Otherwise line L9 stops when H′=HH' = H or det⁡S(H′)≥det⁡S(H)\det S(H') \ge \det S(H). In the first case the claim is clear. In the second case the theorem gives det⁡S(H′)≤det⁡S(H)\det S(H') \le \det S(H), so the two are equal, and the theorem gives T(H′)=T(H)T(H') = T(H) and S(H′)=S(H)S(H') = S(H). □\square

Corollary 2 (the MCD subset is a fixed point). Let H∗H^* minimize det⁡S(H)\det S(H) over all sets of hh indices, with det⁡S(H∗)>0\det S(H^*) > 0. Then every C-step from H∗H^* gives the mean T(H∗)T(H^*) and the covariance matrix S(H∗)S(H^*).

Proof. By the theorem the C-step gives a set H′H' with det⁡S(H′)≤det⁡S(H∗)\det S(H') \le \det S(H^*), and by the minimality of H∗H^* the two are equal. The equality case of the theorem completes the proof. □\square

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 X∼N(0,Ip)X \sim N(0, I_p), 0<α<10 < \alpha < 1, and let qαq_\alpha be the α\alpha-quantile of the chi-squared distribution with pp degrees of freedom. Then

E[XXT∣∥X∥2≤qα]=Fp+2(qα)α Ip,\mathbb E\bigl[XX^{\mathsf T} \mid \|X\|^2 \le q_\alpha\bigr] = \frac{F_{p+2}(q_\alpha)}{\alpha}\,I_p,

where FkF_k is the chi-squared distribution function with kk degrees of freedom.

Proof. The law of XX and the event are invariant under orthogonal maps, so the conditional covariance is a multiple κIp\kappa I_p, and pκ=E[∥X∥2∣∥X∥2≤qα]p\kappa = \mathbb E[\|X\|^2 \mid \|X\|^2 \le q_\alpha]. ∥X∥2\|X\|^2 has the chi-squared density fp(u)=up/2−1e−u/2/(2p/2Γ(p/2))f_p(u) = u^{p/2 - 1}e^{-u/2}/(2^{p/2}\Gamma(p/2)). Since Γ(p/2+1)=p2Γ(p/2)\Gamma(p/2 + 1) = \frac p2\Gamma(p/2), ufp(u)=pfp+2(u)u f_p(u) = p f_{p+2}(u). So

pκ=1α∫0qαufp(u) du=p Fp+2(qα)α.□p\kappa = \frac1\alpha\int_0^{q_\alpha} u f_p(u)\,du = \frac{p\,F_{p+2}(q_\alpha)}{\alpha}. \qquad \square

At the normal model N(μ,Σ)N(\mu, \Sigma), the population MCD region is the ellipsoid {(x−μ)TΣ−1(x−μ)≤qα}\{(x - \mu)^{\mathsf T}\Sigma^{-1}(x - \mu) \le q_\alpha\}. This fact is cited, not proved here (see Hubert, Debruyne and Rousseeuw 2018). Lemma 4, applied to Σ−1/2(X−μ)\Sigma^{-1/2}(X - \mu), then shows that the raw scatter estimates Fp+2(qα)αΣ\frac{F_{p+2}(q_\alpha)}{\alpha}\Sigma. Line L11 divides by this factor. The same computation with 1−δ1 - \delta in place of α\alpha gives the factor of line L13.

Complexity

  • One C-step. The mean and the covariance cost O(hp2)O(hp^2). The inverse and the determinant cost O(p3)O(p^3). The nn distances cost O(np2)O(np^2). The hh smallest distances cost O(n)O(n) with quickselect, or O(nlog⁡n)O(n \log n) with a sort as in the implementation.
  • All starts. With mm starts and at most tt C-steps for each, the total is O(mt(np2+p3+nlog⁡n))O(mt(np^2 + p^3 + n\log n)). In practice tt is small: the C-steps of the example stopped after 4 steps. There is no useful bound on tt other than (nh)\binom nh.
  • Number of starts. A random (p+1)(p+1)-subset contains no outlier with probability about (1−ε)p+1(1 - \varepsilon)^{p+1}, so the number of starts needed grows exponentially in pp.
  • Exact computation. The enumeration of all hh-subsets costs (nh)\binom nh determinants. This is feasible only for small nn, as in the tests.
  • Space. O(n+p2)O(n + p^2) 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 min⁡(n−h+1,h−p)/n\min(n - h + 1, h - p)/n (Lopuhaä and Rousseeuw 1991; Hubert, Debruyne and Rousseeuw 2018). It is largest, ⌊(n−p+1)/2⌋/n\lfloor (n - p + 1)/2\rfloor / n, for ⌊(n+p)/2⌋≤h≤⌊(n+p+1)/2⌋\lfloor (n+p)/2 \rfloor \le h \le \lfloor (n+p+1)/2 \rfloor. The h−ph - p term comes from implosion: h−ph - p replaced points on a hyperplane through pp good points make an hh-subset with determinant 0. In the example, min⁡(5,4)/10=0.4\min(5, 4)/10 = 0.4. The reweighted MCD keeps the breakdown point of the raw MCD.
  • Efficiency (cited). The raw MCD with α=0.5\alpha = 0.5 has a low efficiency at the normal: about 6% when p=2p = 2. The reweighting step raises it to about 45.5% for p=2p = 2 (Hubert, Debruyne and Rousseeuw 2018).
  • Equivariance. T(H)T(H) and S(H)S(H) 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 p=2p = 2 and n≤12n \le 12, the tests compare FAST-MCD with the enumeration of all hh-subsets in exact arithmetic. Taking every (p+1)(p+1)-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 R3\mathbb R^3 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 nn 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 nn.
  • Minimum volume ellipsoid. The MVE, also defined by Rousseeuw (1984), minimizes the volume of a covering ellipsoid of hh points. It has the same breakdown point and worse efficiency.
  • Regularized MCD. For p≥hp \ge h, the sample covariance of hh 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 (pp 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 min⁡(n−h+1,h−p)/n\min(n - h + 1, h - p)/n, not (n−h+1)/n(n - h + 1)/n. The two agree only when h≥(n+p+1)/2h \ge (n + p + 1)/2.
  • Forgetting the consistency factor. S(H∗)S(H^*) comes from the most compact half of the data, so it is far too small. For p=2p = 2 and α=1/2\alpha = 1/2, the factor is 3.263.26.
  • Not the global optimum. FAST-MCD gives a local optimum. Too few starts can miss the MCD subset, in particular when pp is large or the outliers are many.
  • hh must exceed pp. For h≤ph \le p every covariance matrix of hh points is singular. Exact fits, with more than hh points on a hyperplane, give determinant 0: then report the hyperplane rather than invert SS.
  • The cutoff is approximate. The χp,0.9752\chi^2_{p, 0.975} cutoff assumes normal data and large nn. With small nn, 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.

minimum_covariance_determinant.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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
  4. 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)
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example