Algorithm Search⌘K

Algorithmadvanced

MM-estimator

Also called Yohai MM-estimator.

Yohai's regression estimator that starts from a high-breakdown S-estimate of scale and then solves an efficient M-estimation step. It has both high breakdown and high efficiency.

Time
O(m (p³ + n p) + t n p²) worst · averageO(m (p³ + n p) + n p²) best
Space
O(n + p²) extra
Where
m = the number of random subsets; n = the number of observations; p = the number of coefficients; t = the number of reweighting steps
Properties
randomizednot exact in exact arithmeticnot in placeofflinerandomized
Origin
Víctor J. Yohai, 1987

The MM-estimator of linear regression runs in two stages. First, an S-estimate gives a fit β^0\hat\beta_0 and a robust scale s^\hat s of its residuals, with breakdown point one half. Second, with s^\hat s fixed, a Tukey biweight M-estimate is computed by reweighted least squares, starting from β^0\hat\beta_0. The second stage raises the efficiency at the normal to a chosen level, usually 95%. Yohai (1987) proved that it keeps the breakdown point of the first stage. The S-estimate is a hard nonconvex problem, so in practice it is approximated by fits through random subsets of pp points.

In plain words

Fitting a line by least squares fails when a few points are far off, in particular points with unusual xx values. The MM method first finds a rough line that most points agree with. It tries many lines, each through a few randomly chosen points, and keeps the line whose residuals are the smallest in a robust sense. This also gives a robust size of a typical residual. Then it improves the line: points with small residuals count fully, points with larger residuals count less, and points with very large residuals do not count. The improved line is nearly as precise as least squares when the data are clean.

The problem

The input is a design matrix XX with rows xi∈Rpx_i \in \mathbb R^p (with a column of ones for an intercept) and responses y1,…,yny_1, \ldots, y_n, with n≥2pn \ge 2p. Let ρc(u)=1−(1−(u/c)2)3\rho_c(u) = 1 - (1 - (u/c)^2)^3 for ∣u∣≤c|u| \le c and ρc(u)=1\rho_c(u) = 1 beyond: the biweight loss scaled to a maximum of 1. Write ri(β)=yi−xiTβr_i(\beta) = y_i - x_i^{\mathsf T}\beta.

  • The M-scale s(r)s(r) of residuals r1,…,rnr_1, \ldots, r_n is the solution s>0s > 0 of 1n∑iρc0(ri/s)=b\frac1n\sum_i \rho_{c_0}(r_i/s) = b. With c0=1.54764c_0 = 1.54764 and b=1/2b = 1/2, it is consistent for σ\sigma at the normal and has breakdown point one half.
  • The S-estimate is β^0=arg⁡min⁡βs(r(β))\hat\beta_0 = \arg\min_\beta s(r(\beta)), and s^=s(r(β^0))\hat s = s(r(\hat\beta_0)).
  • The MM-estimate is a local minimizer of ∑iρc1(ri(β)/s^)\sum_i \rho_{c_1}(r_i(\beta)/\hat s) with c1=4.685c_1 = 4.685, reached from β^0\hat\beta_0, with s^\hat s fixed.

The algorithm

  1. MM(X, y, m) ▷ c0 = 1.54764, b = 1/2, c1 = 4.685
  2. 1for j ← 1 to m do
  3. 2J ← a random set of p rows; if X_J is singular then skip; β ← the solution of X_J β = y_J
  4. 3s ← M-SCALE(y − Xβ)
  5. 4if s is the least scale so far then (β0, s0) ← (β, s)
  6. 5β ← β0; ŝ ← s0; if ŝ = 0 then return (β, ŝ)
  7. 6repeat
  8. 7r_i ← y_i − x_iᵀβ for each i
  9. 8w_i ← (1 − (r_i/(c1 ŝ))²)² if |r_i| < c1 ŝ, else 0
  10. 9β' ← the weighted least squares fit with weights w_i
  11. 10if ‖β' − β‖ ≤ tol then return (β', ŝ)
  12. 11β ← β'
  13. M-SCALE(r)
  14. 12if at most n b residuals are nonzero then return 0
  15. 13lo ← min_{r_i ≠ 0} |r_i| / c0; hi ← a value with h(hi) ≤ b, where h(s) = (1/n) Σ ρ_{c0}(r_i/s)
  16. 14bisect: if h(mid) > b then lo ← mid else hi ← mid; return hi when the bracket is as small as the precision

hh is continuous and nonincreasing in ss. At lolo every nonzero term is 1, so h(lo)>bh(lo) > b. Since ρc0(u)≤3u2/c02\rho_{c_0}(u) \le 3u^2/c_0^2, any hi≥3 r2‾/b/c0hi \ge \sqrt{3\,\overline{r^2}/b}/c_0 has h(hi)≤bh(hi) \le b.

Example

Take x=1,…,10x = 1, \ldots, 10, an intercept, and y=(3.1,4.8,7.2,9.1,10.8,13.2,15.0,16.9,2.0,1.0)y = (3.1, 4.8, 7.2, 9.1, 10.8, 13.2, 15.0, 16.9, 2.0, 1.0). The first eight points lie near y=1+2xy = 1 + 2x. The last two are bad leverage points.

  • Least squares gives 7.307+0.182x7.307 + 0.182x. The two bad points turn the slope almost flat.
  • S-stage, with all 45 pairs as the subsets: the least M-scale, s^=0.2162\hat s = 0.2162, comes from the line through (4,9.1)(4, 9.1) and (7,15.0)(7, 15.0), that is β^0=(37/30,59/30)≈(1.233,1.967)\hat\beta_0 = (37/30, 59/30) \approx (1.233, 1.967). Its residuals are (−0.10,−0.37,0.07,0,−0.27,0.17,0,−0.07,−16.93,−19.90)(-0.10, -0.37, 0.07, 0, -0.27, 0.17, 0, -0.07, -16.93, -19.90). The terms ρc0(ri/s^)\rho_{c_0}(r_i/\hat s) are (0.245,1,0.114,0,0.951,0.575,0,0.114,1,1)(0.245, 1, 0.114, 0, 0.951, 0.575, 0, 0.114, 1, 1), and their mean is 1/21/2, as the scale equation requires.
  • M-stage, with c1s^=1.013c_1\hat s = 1.013:
step β\beta ∑ρc1(ri/s^)\sum \rho_{c_1}(r_i/\hat s)
0 (1.2333, 1.9667) 2.67162
1 (1.0758, 1.9881) 2.52365
2 (1.0604, 1.9901) 2.52205
3 (1.0589, 1.9902) 2.52204

The iteration stops at β^=(1.0587,1.9902)\hat\beta = (1.0587, 1.9902) after 10 steps. The two bad points have weight 0, and the eight good points have weights between 0.89 and 1. The objective never rises. Each bad point adds exactly 1 to it.

Correctness

The statistical properties are cited, not proved here. The page proves that the computation does what the pseudocode claims; proofs/correctness.md has the details.

  • M-SCALE. hh is continuous and nonincreasing. If more than nbnb residuals are nonzero, hh is strictly decreasing near any root, so the root is unique, and the bisection keeps it in [lo,hi][lo, hi].
  • S-stage. Lines L1 to L4 return the subset fit with the least M-scale among those tried. This is the S-estimate only if the best fit is among the subset fits. In general it is an approximation.
  • M-stage. ρc1(u)=g(u2)\rho_{c_1}(u) = g(u^2) with gg concave, as on the Tukey biweight page. So the objective lies below a weighted sum of squares that touches it at the current β\beta, and line L9 minimizes that sum. Hence the objective does not increase. Since c1>c0c_1 > c_0, ρc1≤ρc0\rho_{c_1} \le \rho_{c_0}, so the objective at the start is at most nb=n/2nb = n/2. Each point with zero weight adds 1, so at most n/2n/2 points have zero weight at every step. If every pp rows of XX are linearly independent and n≥2pn \ge 2p, the weighted least squares problem in line L9 has a unique solution.
Proof: The MM computation finds the M-scale, keeps the least scale, and never increases the M-objectivefull

This proof covers the computation only. The breakdown point and the efficiency of the MM-estimator are theorems of Yohai (1987) and are not proved here.

Notation. ρc(u)=1−(1−u2/c2)3\rho_c(u) = 1 - (1 - u^2/c^2)^3 for ∣u∣≤c|u| \le c and 11 beyond, with 0<c0<c10 < c_0 < c_1 and b=1/2b = 1/2. For residuals r1,…,rnr_1, \ldots, r_n put h(s)=1n∑iρc0(ri/s)h(s) = \frac1n\sum_i \rho_{c_0}(r_i/s) for s>0s > 0, and let zz be the number of nonzero rir_i.

Lemma 1 (the M-scale). If z>nbz > nb, the equation h(s)=bh(s) = b has exactly one solution s∗>0s^* > 0, and the bisection of lines L13 and L14 keeps s∗s^* in [lo,hi][lo, hi].

Proof. ρc0\rho_{c_0} is continuous, even, and nondecreasing in ∣u∣|u|, and strictly increasing in ∣u∣|u| on [0,c0][0, c_0]. So hh is continuous and nonincreasing in ss. At s=lo=min⁡ri≠0∣ri∣/c0s = lo = \min_{r_i \ne 0}|r_i|/c_0, every nonzero term is ρc0(u)\rho_{c_0}(u) with ∣u∣≥c0|u| \ge c_0, which is 1, so h(lo)=z/n>bh(lo) = z/n > b. Since 1−(1−v)3≤3v1 - (1 - v)^3 \le 3v for 0≤v≤10 \le v \le 1, ρc0(u)≤3u2/c02\rho_{c_0}(u) \le 3u^2/c_0^2 for all uu, so h(s)≤3 r2‾/(c02s2)h(s) \le 3\,\overline{r^2}/(c_0^2 s^2), and h(hi)≤bh(hi) \le b for the hihi of line L13. By continuity a root lies in (lo,hi](lo, hi]. Let s∗s^* be a root. Since b<z/nb < z/n, some nonzero term has ρc0(ri/s∗)<1\rho_{c_0}(r_i/s^*) < 1, that is ∣ri∣/s∗<c0|r_i|/s^* < c_0. This term is strictly decreasing in ss near s∗s^* and the others are nonincreasing, so hh is strictly decreasing on a neighbourhood of s∗s^*. A nonincreasing function that is strictly decreasing near each of its roots has at most one root: two roots s1<s2s_1 < s_2 would make hh constant on [s1,s2][s_1, s_2]. So the root is unique. Each bisection step keeps h(lo)>b≥h(hi)h(lo) > b \ge h(hi), so s∗∈(lo,hi]s^* \in (lo, hi]. □\square

If z≤nbz \le nb, line L12 returns 0. This is the limit of the scale equation, because the residuals that are 0 already make up at least half of the sample.

Lemma 2 (the S-stage). Lines L1 to L4 return a pair (β0,s0)(\beta_0, s_0) such that s0s_0 is the least M-scale over the nonsingular subsets drawn, and β0\beta_0 is the fit of one subset that attains it.

Proof. Line L4 keeps a running minimum of the values of line L3. □\square

Lemma 3 (majorization). Put g(v)=1−(1−v/c12)3g(v) = 1 - (1 - v/c_1^2)^3 for 0≤v≤c120 \le v \le c_1^2 and g(v)=1g(v) = 1 beyond. Then ρc1(u)=g(u2)\rho_{c_1}(u) = g(u^2), gg is concave, nondecreasing and differentiable, and g′(u2)=3c12w(u)g'(u^2) = \frac{3}{c_1^2}w(u) with w(u)=(1−u2/c12)2w(u) = (1 - u^2/c_1^2)^2 for ∣u∣<c1|u| < c_1 and 0 beyond.

Proof. g′(v)=3c12(1−v/c12)2g'(v) = \frac{3}{c_1^2}(1 - v/c_1^2)^2 for v<c12v < c_1^2 and 0 for v>c12v > c_1^2, and both one-sided derivatives at c12c_1^2 are 0. This derivative is nonnegative and nonincreasing. □\square

Lemma 4 (descent). Fix s^>0\hat s > 0 and put F(β)=∑iρc1(ri(β)/s^)F(\beta) = \sum_i \rho_{c_1}(r_i(\beta)/\hat s). Let wiw_i be the weights of line L8 at β\beta, and suppose the matrix A=∑iwixixiTA = \sum_i w_i x_i x_i^{\mathsf T} is nonsingular. Then the fit β′\beta' of line L9 satisfies F(β′)≤F(β)F(\beta') \le F(\beta), with equality only if β′=β\beta' = \beta.

Proof. Put vi(γ)=ri(γ)2/s^2v_i(\gamma) = r_i(\gamma)^2/\hat s^2. By Lemma 3 and the tangent inequality for concave functions,

F(γ)≤∑i[g(vi(β))+3c12wi(vi(γ)−vi(β))]=:M(γ),F(\gamma) \le \sum_i \Bigl[g(v_i(\beta)) + \tfrac{3}{c_1^2}w_i\bigl(v_i(\gamma) - v_i(\beta)\bigr)\Bigr] =: M(\gamma),

with equality at γ=β\gamma = \beta. MM is a quadratic in γ\gamma whose quadratic part is 3c12s^2γTAγ\frac{3}{c_1^2\hat s^2}\gamma^{\mathsf T}A\gamma, which is positive definite because AA is nonsingular and wi≥0w_i \ge 0. So MM has a unique minimizer, the weighted least squares fit β′=A−1∑iwixiyi\beta' = A^{-1}\sum_i w_i x_i y_i. Then F(β′)≤M(β′)≤M(β)=F(β)F(\beta') \le M(\beta') \le M(\beta) = F(\beta), and the second inequality is strict when β′≠β\beta' \ne \beta. □\square

Lemma 5 (the weighted design stays nonsingular). Assume s^>0\hat s > 0, every pp rows of XX are linearly independent, and n≥2pn \ge 2p. Then at every step of lines L6 to L11, at least n/2n/2 points have a positive weight, and AA is nonsingular.

Proof. For fixed uu, ρc(u)\rho_c(u) is nonincreasing in cc, because u2/c2u^2/c^2 decreases. Since c1>c0c_1 > c_0, at the start

F(β0)=∑iρc1(ri(β0)/s^)≤∑iρc0(ri(β0)/s^)=nb=n/2,F(\beta_0) = \sum_i \rho_{c_1}(r_i(\beta_0)/\hat s) \le \sum_i \rho_{c_0}(r_i(\beta_0)/\hat s) = nb = n/2,

where the last equality is the scale equation (Lemma 1). A point with weight 0 has ∣ri∣≥c1s^|r_i| \ge c_1\hat s and adds exactly 1 to FF. So the number of points with weight 0 is at most FF. Assume that AA was nonsingular at all earlier steps. By Lemma 4, FF at the current β\beta is at most F(β0)≤n/2F(\beta_0) \le n/2, so at most n/2n/2 points have weight 0, and at least n/2≥pn/2 \ge p points have a positive weight. Any pp of them have independent rows xix_i, so for γ≠0\gamma \ne 0 some of them has xiTγ≠0x_i^{\mathsf T}\gamma \ne 0, and γTAγ≥wi(xiTγ)2>0\gamma^{\mathsf T}A\gamma \ge w_i(x_i^{\mathsf T}\gamma)^2 > 0. So AA is nonsingular. Induction on the steps completes the proof. □\square

Theorem. Under the assumptions of Lemma 5, the M-stage is well defined, F(βt)F(\beta_t) is nonincreasing, and every limit point β∗\beta^* of the iterates satisfies ∑iψc1(ri(β∗)/s^) xi=0\sum_i \psi_{c_1}(r_i(\beta^*)/\hat s)\,x_i = 0, where ψc1(u)=u w(u)\psi_{c_1}(u) = u\,w(u).

Proof. Lemmas 4 and 5 give the first two claims. Let K={β:F(β)≤n/2}K = \{\beta : F(\beta) \le n/2\}. KK is closed, because FF is continuous. For β∈K\beta \in K, as in Lemma 5, there is a set JJ of pp rows with ∣ri(β)∣<c1s^|r_i(\beta)| < c_1\hat s for i∈Ji \in J. Then β=XJ−1(yJ−rJ(β))\beta = X_J^{-1}(y_J - r_J(\beta)) with ∥rJ(β)∥∞<c1s^\|r_J(\beta)\|_\infty < c_1\hat s, so β\beta lies in a bounded set that depends only on JJ. There are finitely many sets JJ, so KK is bounded, and the iterates, which lie in KK, have limit points in KK. The weights are continuous functions of β\beta, and AA is nonsingular at every point of KK by the count of Lemma 5, so the map β↦β′\beta \mapsto \beta' is continuous on KK. As in the proof on the Tukey biweight page, F(βt)F(\beta_t) converges to some F∗F^*, and a limit point β∗\beta^* with its image β∗′\beta^{*\prime} both have F=F∗F = F^*, so Lemma 4 gives β∗′=β∗\beta^{*\prime} = \beta^*. A fixed point of the weighted least squares map satisfies ∑iwixi(yi−xiTβ∗)=0\sum_i w_i x_i (y_i - x_i^{\mathsf T}\beta^*) = 0, which is the stated equation. □\square

Complexity

  • S-stage. Each subset costs O(p3)O(p^3) for the p×pp \times p solve and O(np)O(np) for the residuals. M-SCALE costs O(n)O(n) for each bisection step, and a fixed number of steps reaches the floating-point precision. So the stage costs O(m(p3+np))O(m(p^3 + np)).
  • Number of subsets. If a fraction ε\varepsilon of the points are outliers, a random pp-subset is clean with probability (1−ε)p(1 - \varepsilon)^p. So m≥log⁡δ/log⁡(1−(1−ε)p)m \ge \log\delta / \log(1 - (1 - \varepsilon)^p) subsets give a clean one with probability 1−δ1 - \delta. For p=2p = 2, ε=0.3\varepsilon = 0.3 and δ=0.01\delta = 0.01 this is m=7m = 7; for p=10p = 10 and ε=0.5\varepsilon = 0.5 it is m=4714m = 4714 (the bound is 4713.44713.4). The count grows exponentially in pp.
  • M-stage. Each step costs O(np2)O(np^2) to form the weighted normal equations and O(p3)O(p^3) to solve them. The convergence is linear.
  • Space. O(n+p2)O(n + p^2).

Properties

Proved on this page: the descent and the well-defined steps of the computation. Cited: the statistical properties below. Measured: the numbers in the tests.

  • Breakdown point one half (cited). If the S-estimate uses b=12max⁡ρb = \tfrac12\max\rho and ρc1≤ρc0\rho_{c_1} \le \rho_{c_0}, the MM-estimate has asymptotic breakdown point 12\tfrac12 (Yohai 1987). It holds for outliers in yy and for bad leverage points in xx. The S-estimate alone has this breakdown point (Rousseeuw and Yohai 1984).
  • Efficiency (cited). Under normal errors the MM-estimate has the same asymptotic distribution as the M-estimate with the true σ\sigma, so c1=4.685c_1 = 4.685 gives 95% efficiency relative to least squares (Yohai 1987). The S-estimate with c0=1.54764c_0 = 1.54764 alone has an efficiency of only about 29% (Maronna et al. 2019).
  • Measured. In the tests, on 60 points with 30% bad leverage points the least squares slope is off by more than 1, and the MM slope is within 0.15 of the truth. On 40 clean replications of 40 points the variance ratio of the slopes, least squares over MM, is 0.94.
  • Equivariance. The MM-estimate is regression, scale and affine equivariant, when the subsets are chosen independently of the values.
  • Exact fit. If more than half of the points lie exactly on a hyperplane, the M-scale of that fit is 0, and the algorithm returns that fit when a subset from those points is drawn.

Variants and improvements

  • Fast-S. Improve each subset fit by a few local steps for the S-objective, keep the best few, and refine them fully (Salibián-Barrera and Yohai 2006). This needs far fewer subsets than the plain search.
  • Deterministic starts. Use the least trimmed squares or the least median of squares fit as the start instead of random subsets.
  • Other losses. Optimal ρ\rho functions, or a Huber loss in the M-stage. A monotone ψ\psi gives a unique M-stage solution, but leverage points then have more influence.
  • Inference. Use the sandwich covariance of the M-stage with s^\hat s fixed. Robust tests and robust model selection build on it.
  • Robust multivariate methods. For location and scatter, the analogous two-stage idea starts from the minimum covariance determinant.

When to use it

Use MM-regression as the default robust linear regression when outliers in yy or bad leverage points in xx are possible and you want an efficiency close to least squares on clean data. Use plain least squares with Cook's distance and leverage diagnostics when the data are clean or the outliers are few and easy to see. Use RANSAC in geometric fitting with a known inlier threshold. Use the Huber M-estimator in regression only when xx has no outliers.

Pitfalls

  • The constant bb depends on how ρ\rho is scaled. With ρ\rho scaled to a maximum of 1, b=1/2b = 1/2. With the biweight ρ\rho of maximum c02/6c_0^2/6, the same estimator needs b=c02/12b = c_0^2/12. Mixing the two conventions gives a wrong scale.
  • Too few subsets. With a large pp and many outliers, all random subsets can contain an outlier, and the S-stage fails. Use Fast-S or a deterministic start.
  • Updating the scale. The scale must stay fixed in the M-stage. Recomputing it from the M-stage residuals destroys the breakdown guarantee.
  • Efficiency is asymptotic. With few points per coefficient, the efficiency on clean data can be well below 95%.
  • A local solution. The M-stage finds a stationary point near the start. A different start can give a different answer.
  • Singular weighted designs. With factor variables or many zero weights, the weighted design can be singular. Check the rank.

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.

mm_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mm-estimator/. The authors are listed in prov/MBJNZK.jsonl.

import itertools
import math
import random

# Biweight constants with rho normalized to a maximum of 1.
C0 = 1.54764  # S-step: E rho_C0(Z) = 1/2 at N(0, 1), breakdown point 1/2
B = 0.5
C1 = 4.685  # M-step: 95% efficiency at the normal


def rho(u, c):
    """Biweight rho normalized to max 1: 1 - (1 - (u/c)^2)^3 inside, 1 outside."""
    v = (u / c) ** 2
    if v >= 1.0:
        return 1.0
    return 1.0 - (1.0 - v) ** 3


def weight(u, c):
    """psi(u)/u up to a constant factor: (1 - (u/c)^2)^2 inside, 0 outside."""
    v = (u / c) ** 2
    return 0.0 if v >= 1.0 else (1.0 - v) ** 2


def psi(u, c):
    return u * weight(u, c)


def solve(a, b):
    """Solve the square system a z = b by Gaussian elimination with partial pivoting.

    Returns None if the matrix is singular (to rounding).
    """
    p = len(a)
    m = [list(map(float, row)) + [float(v)] for row, v in zip(a, b)]
    scale = max((abs(v) for row in a for v in row), default=0.0) or 1.0
    for col in range(p):
        piv = max(range(col, p), key=lambda r: abs(m[r][col]))
        if abs(m[piv][col]) <= 1e-12 * scale:
            return None
        m[col], m[piv] = m[piv], m[col]
        for r in range(col + 1, p):
            f = m[r][col] / m[col][col]
            if f:
                for k in range(col, p + 1):
                    m[r][k] -= f * m[col][k]
    z = [0.0] * p
    for r in range(p - 1, -1, -1):
        z[r] = (m[r][p] - sum(m[r][k] * z[k] for k in range(r + 1, p))) / m[r][r]
    return z


def residuals(x, y, beta):
    return [yi - sum(a * b for a, b in zip(row, beta)) for row, yi in zip(x, y)]


def m_scale(r, c=C0, b=B, iters=200):
    """The M-scale s > 0 with mean(rho_c(r_i / s)) = b, by bisection.

    Returns 0 if at most n b residuals are nonzero (an exact fit of that many points).
    """
    n = len(r)
    nz = [abs(v) for v in r if v != 0]
    if len(nz) <= n * b:  # @line L12
        return 0.0
    lo = min(nz) / c  # h(lo) = len(nz)/n > b
    hi = math.sqrt(3.0 * sum(v * v for v in r) / (n * b)) / c + max(nz)  # h(hi) <= b
    for _ in range(iters):  # @line L13
        mid = (lo + hi) / 2
        if mid in (lo, hi):
            break
        if sum(rho(v / mid, c) for v in r) / n > b:  # @line L14
            lo = mid
        else:
            hi = mid
    return hi


def weighted_ls(x, y, w):
    p = len(x[0])
    a = [[sum(wi * row[i] * row[j] for wi, row in zip(w, x)) for j in range(p)] for i in range(p)]
    rhs = [sum(wi * row[i] * yi for wi, row, yi in zip(w, x, y)) for i in range(p)]
    return solve(a, rhs)


def s_estimate(x, y, subsets=500, seed=0):
    """Approximate S-estimate: the elemental fit with the least M-scale over random p-subsets.

    If subsets is None, all p-subsets are tried.
    """
    n, p = len(x), len(x[0])
    rng = random.Random(seed)
    if subsets is None:
        pool = itertools.combinations(range(n), p)
    else:
        pool = (rng.sample(range(n), p) for _ in range(subsets))
    best = None
    for idx in pool:  # @line L1
        beta = solve([x[i] for i in idx], [y[i] for i in idx])  # @line L2
        if beta is None:
            continue
        s = m_scale(residuals(x, y, beta))  # @line L3
        if best is None or s < best[1]:  # @line L4
            best = (beta, s)
    if best is None:
        raise ValueError("every subset was singular")
    return best


def m_objective(x, y, beta, s, c=C1):
    return sum(rho(v / s, c) for v in residuals(x, y, beta))


def mm_estimate(x, y, subsets=500, seed=0, tol=1e-10, max_iter=500, trace=None):
    """MM-estimate of regression: S-start and M-scale, then biweight IRLS with c = 4.685.

    x is a list of n rows of length p (put a column of ones in it for an intercept).
    Returns (beta, s). If trace is a list, the M-step iterates are appended to it.
    """
    beta, s = s_estimate(x, y, subsets, seed)  # @line L5
    if s == 0:
        return beta, s  # @line L5
    if trace is not None:
        trace.append(beta)
    for _ in range(max_iter):  # @line L6
        r = residuals(x, y, beta)  # @line L7
        w = [weight(v / s, C1) for v in r]  # @line L8
        new = weighted_ls(x, y, w)  # @line L9
        if new is None:
            raise ValueError("the weighted design is singular")
        if trace is not None:
            trace.append(new)
        done = max(abs(a - b) for a, b in zip(new, beta)) <= tol * (1.0 + max(abs(v) for v in beta))
        beta = new  # @line L11
        if done:  # @line L10
            break
    return beta, s


def ols(x, y):
    return weighted_ls(x, y, [1.0] * len(y))
test_mm_estimator.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mm-estimator/. The authors are listed in prov/MBJNZK.jsonl.

import math
import random

import pytest

from mm_estimator import (
    B, C0, C1, m_objective, m_scale, mm_estimate, ols, psi, residuals, rho, s_estimate,
)

XS = list(range(1, 11))
YS = [3.1, 4.8, 7.2, 9.1, 10.8, 13.2, 15.0, 16.9, 2.0, 1.0]
X = [[1.0, float(v)] for v in XS]


def test_m_scale_by_hand() -> None:
    # Four residuals of size 1: rho(1/s) = 1/2, so s = 1 / (c0 sqrt(1 - 2^(-1/3))).
    s = m_scale([1, -1, 1, -1])
    assert s == pytest.approx(1 / (C0 * math.sqrt(1 - 2 ** (-1 / 3))), rel=1e-12)
    # At most n b nonzero residuals: an exact fit of half the points gives scale 0.
    assert m_scale([0, 0, 5, -7]) == 0.0


def test_m_scale_is_consistent_at_the_normal() -> None:
    rng = random.Random(1)
    r = [rng.gauss(0.0, 2.0) for _ in range(20000)]
    assert m_scale(r) == pytest.approx(2.0, rel=0.03)


def test_page_example() -> None:
    assert ols(X, YS) == pytest.approx([7.306667, 0.182424], abs=1e-6)
    beta_s, s = s_estimate(X, YS, subsets=None)
    assert beta_s == pytest.approx([37 / 30, 59 / 30], abs=1e-9)  # the line through (4, 9.1) and (7, 15.0)
    assert sum(rho(v / s, C0) for v in residuals(X, YS, beta_s)) / len(YS) == pytest.approx(B, abs=1e-12)
    beta, s2 = mm_estimate(X, YS, subsets=None)
    assert s2 == s
    assert beta == pytest.approx([1.058707, 1.990247], abs=1e-6)


def test_m_step_descent_and_stationarity() -> None:
    rng = random.Random(2)
    for _ in range(15):
        n, p = rng.randint(20, 40), rng.choice([2, 3])
        x = [[1.0] + [rng.gauss(0.0, 1.0) for _ in range(p - 1)] for _ in range(n)]
        y = [1.0 + sum(row[1:]) + rng.gauss(0.0, 0.5) for row in x]
        for i in rng.sample(range(n), n // 5):
            y[i] += rng.uniform(10.0, 30.0)
        trace = []
        beta, s = mm_estimate(x, y, subsets=60, seed=rng.randint(0, 10**6), trace=trace)
        q = [m_objective(x, y, b, s) for b in trace]
        assert all(b <= a + 1e-12 for a, b in zip(q, q[1:]))
        assert q[-1] <= q[0]
        r = residuals(x, y, beta)
        for j in range(p):
            assert abs(sum(psi(v / s, C1) * row[j] for v, row in zip(r, x))) <= 1e-6 * n
        # The scale solves the M-scale equation at the S residuals.
        b0 = trace[0]
        assert sum(rho(v / s, C0) for v in residuals(x, y, b0)) / n == pytest.approx(B, abs=1e-9)


def test_s_step_takes_the_least_scale() -> None:
    rng = random.Random(3)
    n = 9
    x = [[1.0, float(i)] for i in range(n)]
    y = [2.0 * i + rng.gauss(0.0, 1.0) for i in range(n)]
    beta, s = s_estimate(x, y, subsets=None)
    from mm_estimator import solve
    for i in range(n):
        for j in range(i + 1, n):
            b = solve([x[i], x[j]], [y[i], y[j]])
            assert m_scale(residuals(x, y, b)) >= s


def test_exact_fit_of_a_majority() -> None:
    x = [[1.0, float(i)] for i in range(10)]
    y = [3.0 - 0.5 * i for i in range(10)]
    y[1], y[4], y[7] = 50.0, -40.0, 99.0
    beta, s = mm_estimate(x, y, subsets=None)
    assert s == 0.0
    assert beta == pytest.approx([3.0, -0.5], abs=1e-12)


def test_contaminated_regression_error_is_measured() -> None:
    # 30% bad leverage points: OLS slope is far off, MM stays near the true slope 2.
    rng = random.Random(4)
    n = 60
    xs = [rng.uniform(0.0, 10.0) for _ in range(n)]
    ys = [1.0 + 2.0 * v + rng.gauss(0.0, 1.0) for v in xs]
    for i in range(int(0.3 * n)):
        xs[i], ys[i] = rng.uniform(25.0, 30.0), rng.uniform(-5.0, 0.0)
    x = [[1.0, v] for v in xs]
    b_ols = ols(x, ys)
    b_mm, _ = mm_estimate(x, ys, subsets=200, seed=5)
    assert abs(b_ols[1] - 2.0) > 1.0
    assert abs(b_mm[1] - 2.0) < 0.15


def test_efficiency_on_clean_data_is_measured() -> None:
    # On clean normal errors the MM and OLS slopes are close; the variance ratio over
    # replications is measured, and must be near the 95% of the theory.
    rng = random.Random(6)
    d_ols, d_mm = [], []
    for _ in range(40):
        xs = [rng.uniform(0.0, 1.0) for _ in range(40)]
        x = [[1.0, v] for v in xs]
        y = [rng.gauss(0.0, 1.0) for _ in xs]
        d_ols.append(ols(x, y)[1])
        d_mm.append(mm_estimate(x, y, subsets=30, seed=rng.randint(0, 10**6))[0][1])
    v_ols = sum(v * v for v in d_ols) / len(d_ols)
    v_mm = sum(v * v for v in d_mm) / len(d_mm)
    assert 0.75 < v_ols / v_mm <= 1.1

History

Rousseeuw (1984) introduced the least median of squares, the first affine equivariant regression estimator with breakdown point one half. Rousseeuw and Yohai (1984) defined S-estimators, which have high breakdown and are asymptotically normal, but have low efficiency. Yohai (1987) combined an S-estimate of scale with an efficient M-step and proved that the result keeps both properties. Salibián-Barrera and Yohai (2006) gave the Fast-S algorithm that most software uses for the first stage.

References

  1. Víctor J. Yohai, High breakdown-point and high efficiency robust estimates for regression, The Annals of Statistics 15(2), 1987, pp. 642 to 656 (the MM-estimator, its breakdown point and its efficiency at the normal)
  2. Peter J. Rousseeuw and Víctor J. Yohai, Robust regression by means of S-estimators, in Robust and Nonlinear Time Series Analysis, Lecture Notes in Statistics 26, Springer, 1984, pp. 256 to 272 (S-estimators of regression, the M-scale and their breakdown point)
  3. Matías Salibián-Barrera and Víctor J. Yohai, A fast algorithm for S-regression estimates, Journal of Computational and Graphical Statistics 15(2), 2006, pp. 414 to 427 (random subsets with local improvement steps for the S-estimate)
  4. 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, Chapter 5 (S-estimators, MM-estimators, the choice of the constants and the computation by subsampling)
  5. Peter J. Rousseeuw and Annick M. Leroy, Robust Regression and Outlier Detection, Wiley, 1987, Chapter 3 (high-breakdown regression and the subsampling algorithm)

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