Algorithm Search⌘K

Algorithmcore

Huber M-estimator

Also called Huber estimator of location.

Huber's M-estimator with a loss that is quadratic near zero and linear beyond a threshold. It is minimax for the variance under the contamination model.

Time
Θ(n log n) worst · average · best
Space
Θ(n) extra
Where
n = the sample size
Properties
deterministicexact in exact arithmeticnot in placeofflinenot randomized
Origin
Peter J. Huber, 1964

The Huber M-estimator of location is the M-estimator with the loss ρk(u)=u2/2\rho_k(u) = u^2/2 for ∣u∣≤k|u| \le k and k∣u∣−k2/2k|u| - k^2/2 beyond. Small residuals count as in least squares, and large residuals count only linearly, so a few gross errors cannot pull the estimate far. With the scale fixed, the estimating function is piecewise linear and monotone, and its root can be found exactly by a search over its 2n2n breakpoints. Huber proved in 1964 that a suitable kk makes this estimator minimax for the asymptotic variance over the contamination model.

In plain words

You want the center of some measurements, and a few of them may be wrong. The mean listens to every point with a force that grows with its distance, so one far point pulls hard. The Huber estimate lets each point pull with a force that grows with its distance only up to a limit. A point far away pulls exactly as hard as a point at the limit. The estimate is the place where the pulls from the left and from the right cancel. The limit is a number of typical spreads, and the typical spread comes from a robust measure that outliers do not change.

The problem

The input is a sample x1,…,xnx_1, \ldots, x_n of real numbers, a tuning constant k>0k > 0 and a scale σ>0\sigma > 0. By default σ\sigma is the normalized median absolute deviation, σ^=MAD/Φ−1(3/4)\hat\sigma = \mathrm{MAD}/\Phi^{-1}(3/4), computed once before the location. Put

ψk(u)=max⁡(−k,min⁡(k,u)),Λ(θ)=∑i=1nψk ⁣(xi−θσ).\psi_k(u) = \max(-k, \min(k, u)), \qquad \Lambda(\theta) = \sum_{i=1}^n \psi_k\!\left(\frac{x_i - \theta}{\sigma}\right).

The output is a minimizer of Q(θ)=∑iρk((xi−θ)/σ)Q(\theta) = \sum_i \rho_k((x_i - \theta)/\sigma), which is the same as a root of Λ\Lambda. The roots form a closed interval. The algorithm returns its midpoint, so the output is unique.

The algorithm

Λ\Lambda is continuous, nonincreasing, and linear between consecutive points of the set B={xi±kσ}B = \{x_i \pm k\sigma\}. So it is enough to find the two breakpoints around the root and solve one linear equation.

  1. HUBER(x, k, σ) ▷ x[1 .. n], k > 0
  2. 1if σ is not given then σ ← MAD(x)/Φ⁻¹(3/4); if σ = 0 then return the median of x
  3. 2b[0 .. M] ← the sorted distinct values of x_i − kσ and x_i + kσ
  4. 3Λ(θ) = Σ ψ_k((x_i − θ)/σ) ▷ O(n) per evaluation
  5. 4t ← the least index with Λ(b[t]) ≤ 0 ▷ binary search; Λ(b[0]) = nk > 0
  6. 5θ_lo ← b[t−1] + (b[t] − b[t−1]) · Λ(b[t−1]) / (Λ(b[t−1]) − Λ(b[t]))
  7. 6u ← the greatest index with Λ(b[u]) ≥ 0 ▷ binary search; Λ(b[M]) = −nk < 0
  8. 7θ_hi ← b[u] + (b[u+1] − b[u]) · Λ(b[u]) / (Λ(b[u]) − Λ(b[u+1]))
  9. 8return (θ_lo + θ_hi)/2

Line L5 finds the least root and line L7 the greatest root. If Λ(b[t])<0\Lambda(b[t]) < 0, then u=t−1u = t - 1 and the two lines give the same point.

Example

Take x=(1,4,5,6,8,30)x = (1, 4, 5, 6, 8, 30), k=3/2k = 3/2 and σ=2\sigma = 2, so kσ=3k\sigma = 3. The sorted breakpoints are b=(−2,1,2,3,4,5,7,8,9,11,27,33)b = (-2, 1, 2, 3, 4, 5, 7, 8, 9, 11, 27, 33), with M=11M = 11. The binary searches evaluate Λ\Lambda at these points:

θ\theta clipped scaled residuals ψk((xi−θ)/2)\psi_k((x_i - \theta)/2) Λ(θ)\Lambda(\theta)
3 −1,12,1,32,32,32-1, \tfrac12, 1, \tfrac32, \tfrac32, \tfrac32 5
5 −32,−12,0,12,32,32-\tfrac32, -\tfrac12, 0, \tfrac12, \tfrac32, \tfrac32 32\tfrac32
7 −32,−32,−1,−12,12,32-\tfrac32, -\tfrac32, -1, -\tfrac12, \tfrac12, \tfrac32 −52-\tfrac52
9 −32,−32,−32,−32,−12,32-\tfrac32, -\tfrac32, -\tfrac32, -\tfrac32, -\tfrac12, \tfrac32 −5-5

Line L4 gives b[t]=7b[t] = 7, and line L6 gives b[u]=5b[u] = 5. Both lines L5 and L7 give θ=5+2⋅3/23/2+5/2=234=5.75\theta = 5 + 2 \cdot \frac{3/2}{3/2 + 5/2} = \frac{23}{4} = 5.75. Check: at 5.755.75 the clipped residuals are −32,−78,−38,18,98,32-\tfrac32, -\tfrac78, -\tfrac38, \tfrac18, \tfrac98, \tfrac32, and they sum to 0. The mean is 9, pulled up by the value 30, and the median is 5.5. The MAD of this sample is 2, so the default scale is 2/0.6745=2.9652/0.6745 = 2.965. With the default k=1.345k = 1.345 the estimate is also 5.755.75, because then only the points 1 and 30 are clipped, both at kσ=3.988k\sigma = 3.988.

Correctness

ψk\psi_k is continuous and nondecreasing, so Λ\Lambda is continuous and nonincreasing. Between two consecutive breakpoints, every point is either in the clipped part on the left, in the clipped part on the right, or in the linear part, and it stays there. So Λ\Lambda is linear on each closed segment between consecutive breakpoints, and linear interpolation between two breakpoints gives an exact root. QQ is convex and differentiable with Q′(θ)=−Λ(θ)/σQ'(\theta) = -\Lambda(\theta)/\sigma, so its minimizers are exactly the roots of Λ\Lambda. The binary searches keep the facts Λ(b[t−1])>0≥Λ(b[t])\Lambda(b[t-1]) > 0 \ge \Lambda(b[t]) and Λ(b[u])≥0>Λ(b[u+1])\Lambda(b[u]) \ge 0 > \Lambda(b[u+1]), so they find the segments that hold the least and the greatest root. The full proof is in proofs/correctness.md.

Proof: HUBER returns the midpoint of the set of minimizers of the Huber objectivefull

Setting. x1,…,xnx_1, \ldots, x_n are real, n≥1n \ge 1, k>0k > 0 and σ>0\sigma > 0 (the case σ=0\sigma = 0 ends at line L1). Put c=kσc = k\sigma, Q(θ)=∑iρk((xi−θ)/σ)Q(\theta) = \sum_i \rho_k((x_i - \theta)/\sigma) and Λ(θ)=∑iψk((xi−θ)/σ)\Lambda(\theta) = \sum_i \psi_k((x_i - \theta)/\sigma). Let b[0]<⋯<b[M]b[0] < \cdots < b[M] be the distinct values of xi±cx_i \pm c.

Lemma 1. Λ\Lambda is continuous and nonincreasing on R\mathbb R, and linear on each segment [b[j],b[j+1]][b[j], b[j+1]].

Proof. ψk\psi_k is continuous and nondecreasing, and θ↦(xi−θ)/σ\theta \mapsto (x_i - \theta)/\sigma is continuous and decreasing. So each term is continuous and nonincreasing, and so is the sum. Take θ\theta in the open segment (b[j],b[j+1])(b[j], b[j+1]). No value xi±cx_i \pm c lies in it, so for each ii the sign of xi−θ−cx_i - \theta - c and of xi−θ+cx_i - \theta + c is the same for all θ\theta in the segment. So each ii is in one of three fixed classes: xi−θ>cx_i - \theta > c (the term is kk), xi−θ<−cx_i - \theta < -c (the term is −k-k), or ∣xi−θ∣≤c|x_i - \theta| \le c (the term is (xi−θ)/σ(x_i - \theta)/\sigma). Each term is an affine function of θ\theta on the open segment, so Λ\Lambda is affine there. By continuity it is affine on the closed segment. □\square

Lemma 2. The minimizers of QQ are exactly the roots of Λ\Lambda, and they form a nonempty closed interval inside [b[0],b[M]][b[0], b[M]].

Proof. ρk\rho_k is convex and differentiable with ρk′=ψk\rho_k' = \psi_k: on ∣u∣<k|u| < k the derivative is uu, on ∣u∣>k|u| > k it is ±k\pm k, and at u=±ku = \pm k both one-sided derivatives are ±k\pm k. So QQ is convex and differentiable with Q′(θ)=−Λ(θ)/σQ'(\theta) = -\Lambda(\theta)/\sigma. A differentiable convex function is minimal at θ\theta if and only if its derivative is 0 there. At θ=b[0]=min⁡xi−c\theta = b[0] = \min x_i - c every xi−θ≥cx_i - \theta \ge c, so Λ(b[0])=nk>0\Lambda(b[0]) = nk > 0. In the same way Λ(b[M])=−nk<0\Lambda(b[M]) = -nk < 0. By continuity there is a root in (b[0],b[M])(b[0], b[M]). A nonincreasing function is positive left of its least root and negative right of its greatest root, and the root set of a continuous monotone function is a closed interval. □\square

Lemma 3 (line L4 and line L5). Line L4 ends with Λ(b[t−1])>0≥Λ(b[t])\Lambda(b[t-1]) > 0 \ge \Lambda(b[t]), and line L5 gives the least root θlo\theta_{lo} of Λ\Lambda.

Proof. The search keeps the invariant Λ(b[lo−1])>0\Lambda(b[lo - 1]) > 0 and Λ(b[hi])≤0\Lambda(b[hi]) \le 0. It holds at the start with lo=1lo = 1 and hi=Mhi = M by Lemma 2. A step with Λ(b[mid])≤0\Lambda(b[mid]) \le 0 sets hi=midhi = mid, and a step with Λ(b[mid])>0\Lambda(b[mid]) > 0 sets lo=mid+1lo = mid + 1, so the invariant holds. The range [lo,hi][lo, hi] shrinks at each step and the loop ends with lo=hi=tlo = hi = t. Since Λ\Lambda is nonincreasing and Λ(b[t−1])>0\Lambda(b[t-1]) > 0, no root is ≤b[t−1]\le b[t-1]. By Lemma 1, Λ\Lambda is affine on [b[t−1],b[t]][b[t-1], b[t]], it goes from a positive value to a value ≤0\le 0, so it has exactly one root in this segment, at the point that line L5 computes. This is the least root. □\square

Lemma 4 (line L6 and line L7). Line L6 ends with Λ(b[u])≥0>Λ(b[u+1])\Lambda(b[u]) \ge 0 > \Lambda(b[u+1]), and line L7 gives the greatest root θhi\theta_{hi}.

Proof. The same argument with the invariant Λ(b[lo])≥0\Lambda(b[lo]) \ge 0 and Λ(b[hi+1])<0\Lambda(b[hi + 1]) < 0, which holds at the start with lo=0lo = 0 and hi=M−1hi = M - 1. No root is ≥b[u+1]\ge b[u+1], and on [b[u],b[u+1]][b[u], b[u+1]] the affine function Λ\Lambda goes from a value ≥0\ge 0 to a negative value, so its unique root there is the greatest root. □\square

Theorem. HUBER returns the midpoint of the set of minimizers of QQ.

Proof. By Lemma 2 this set is [θlo,θhi][\theta_{lo}, \theta_{hi}], and by Lemmas 3 and 4 lines L5 and L7 compute its two ends. Line L8 returns (θlo+θhi)/2(\theta_{lo} + \theta_{hi})/2. □\square

When the root is unique. If some xix_i satisfies ∣xi−θ^∣<c|x_i - \hat\theta| < c at a root θ^\hat\theta, then Λ\Lambda has slope at most −1/σ-1/\sigma near θ^\hat\theta and the root is unique. If the root set is a segment of positive length, then Λ=0\Lambda = 0 on it, so no point is in the linear class on its interior.

Complexity

  • Time. The sort in line L2 takes Θ(nlog⁡n)\Theta(n \log n). Each binary search evaluates Λ\Lambda at O(log⁡n)O(\log n) points, and each evaluation costs Θ(n)\Theta(n). The MAD needs two medians, which take expected Θ(n)\Theta(n) with quickselect. So the total is Θ(nlog⁡n)\Theta(n \log n).
  • Space. Θ(n)\Theta(n) for the breakpoints.
  • Arithmetic. With rational data, kk and σ\sigma, all steps are exact, and the root satisfies Λ(θ^)=0\Lambda(\hat\theta) = 0 exactly. The default scale contains Φ−1(3/4)\Phi^{-1}(3/4), which is irrational, so in practice the result is a floating-point number.

Properties

The page proves the breakdown point below. The influence function is proved on the influence function page. The optimality results are cited.

  • Influence function. At the normal law with the scale fixed at its true value σ\sigma, IF(x)=σ ψk((x−μ)/σ)/(2Φ(k)−1)\mathrm{IF}(x) = \sigma\,\psi_k((x - \mu)/\sigma)/(2\Phi(k) - 1). It is bounded, and the standardized gross-error sensitivity is k/(2Φ(k)−1)k/(2\Phi(k) - 1).
  • Efficiency at the normal. The asymptotic variance at N(0,1)N(0, 1) is Eψk(Z)2/(2Φ(k)−1)2\mathrm E\psi_k(Z)^2 / (2\Phi(k) - 1)^2, with Eψk(Z)2=2Φ(k)−1−2kφ(k)+2k2(1−Φ(k))\mathrm E\psi_k(Z)^2 = 2\Phi(k) - 1 - 2k\varphi(k) + 2k^2(1 - \Phi(k)). A numerical evaluation gives:
kk 1.0 1.345 1.5 2.0
asymptotic variance 1.1073 1.0526 1.0371 1.0104
efficiency 0.903 0.950 0.964 0.990
gross-error sensitivity 1.465 1.637 1.731 2.095

So k=1.345k = 1.345 gives 95% efficiency at the normal.

  • Minimax variance (cited). For the model (1−ε)Φ+εH(1 - \varepsilon)\Phi + \varepsilon H with HH symmetric, the Huber estimator with kk solving 2φ(k)/k−2(1−Φ(k))=ε/(1−ε)2\varphi(k)/k - 2(1 - \Phi(k)) = \varepsilon/(1 - \varepsilon) minimizes the maximum asymptotic variance over the model (Huber 1964). The least favorable law has a normal center and exponential tails. A numerical solution gives:
ε\varepsilon 0.01 0.05 0.10 0.20
minimax kk 1.945 1.398 1.140 0.862
  • Optimal B-robustness (cited). Among location M-estimators with a bound on the gross-error sensitivity, the Huber estimator has the least asymptotic variance at the normal (Hampel, Ronchetti, Rousseeuw and Stahel 1986, Chapter 2).
  • Breakdown point ⌈n/2⌉/n\lceil n/2 \rceil / n with the MAD scale (proved). Replace m<n/2m < n/2 points by any values, and let c1≤c2c_1 \le c_2 be the least and the greatest of the clean points and R=c2−c1R = c_2 - c_1. For θ>c2+kσ\theta > c_2 + k\sigma every clean term is −k-k, so Λ(θ)≤−(n−m)k+mk<0\Lambda(\theta) \le -(n - m)k + mk < 0. In the same way Λ(θ)>0\Lambda(\theta) > 0 for θ<c1−kσ\theta < c_1 - k\sigma. So every root lies in [c1−kσ,c2+kσ][c_1 - k\sigma, c_2 + k\sigma]. The median of the new sample lies in [c1,c2][c_1, c_2], because more than half of the points are clean. So more than half of the absolute deviations are at most RR, which gives MAD≤R\mathrm{MAD} \le R and σ≤R/Φ−1(3/4)\sigma \le R/\Phi^{-1}(3/4). If σ=0\sigma = 0, the output is the median, which is also in [c1,c2][c_1, c_2]. So the estimate stays bounded. With m=⌈n/2⌉m = \lceil n/2 \rceil points at one far value ss, the median and the estimate follow ss. This is the largest value that a translation equivariant estimator can have (see the breakdown point page). With a fixed scale the same argument gives the same bound.
  • Equivariance. With the MAD scale, the estimate is location and scale equivariant: T(ax+b)=aT(x)+bT(ax + b) = aT(x) + b for a≠0a \ne 0. With a fixed σ\sigma it is only location equivariant.
  • Limits. If kσk\sigma is larger than the range of the sample, all residuals are in the linear part and the estimate is the mean. As k→0k \to 0 the estimate tends to a median.

Variants and improvements

  • Iteratively reweighted means. Start at the median and repeat θ←∑wixi/∑wi\theta \leftarrow \sum w_i x_i / \sum w_i with wi=min⁡(1,kσ/∣xi−θ∣)w_i = \min(1, k\sigma/|x_i - \theta|). Each step does not increase QQ, and the iteration converges to a root. It is the form that extends to regression; see iteratively reweighted least squares (Holland and Welsch 1977).
  • Newton steps. θ←θ+σΛ(θ)/∣I(θ)∣\theta \leftarrow \theta + \sigma\Lambda(\theta)/|I(\theta)|, where I(θ)I(\theta) is the set of points in the linear part. On the segment that holds the root, one step is exact, because Λ\Lambda is linear there.
  • One-step Huber. Start at the median and do one Newton step. It has the same first-order asymptotics as the full estimator.
  • Joint scale (Proposal 2). Solve two equations at once: Λ(θ)=0\Lambda(\theta) = 0 and ∑ψk((xi−θ)/σ)2=(n−1) Eψk(Z)2\sum \psi_k((x_i - \theta)/\sigma)^2 = (n - 1)\,\mathrm E\psi_k(Z)^2 (Huber 1964). Its breakdown point depends on kk and is lower than one half (Huber 1984).
  • Regression. Replace xi−θx_i - \theta by the residual yi−xiTβy_i - x_i^{\mathsf T}\beta. The objective is still convex, but the breakdown point under leverage points is 1/n1/n. Use the MM-estimator when the design can contain outliers.
  • Redescending loss. The Tukey biweight sets the influence of far points to 0, at the cost of a nonconvex objective.

When to use it

Use it as the default robust estimate of location for data that are roughly normal with some outliers or heavy tails. It keeps about 95% of the efficiency of the mean at the normal and has the highest possible breakdown point with the MAD scale. Use the median if you need the simplest rule. Use the Tukey biweight if gross outliers are frequent and must have no influence. Use the trimmed mean if you need a rule that is easy to explain. Use the Hodges-Lehmann estimator if you want a rank method with a matching test.

Pitfalls

  • No scale. Without σ\sigma the estimate is not scale equivariant: k=1.345k = 1.345 in meters and in millimeters gives different results. Always divide by a robust scale.
  • The standard deviation as scale. Outliers inflate it, so kσk\sigma grows and nothing is clipped. Use the MAD or another robust scale.
  • Zero MAD. If more than half of the values are equal, the MAD is 0. The method then returns the median. A different robust scale, such as QnQ_n, avoids this.
  • A root set that is an interval. If no residual is in the linear part near the root, Λ\Lambda is 0 on a whole segment. For x=(0,10)x = (0, 10), k=1k = 1 and σ=1\sigma = 1, every θ\theta in [1,9][1, 9] is a root. The algorithm returns the midpoint 5. Iterative solvers can stop anywhere in the segment.
  • Stopping rules. IRLS converges only linearly when many points are clipped. The exact method above has no tolerance to choose.
  • Asymmetric contamination. The minimax theorem assumes symmetric contamination. Under one-sided contamination the estimate has a bias of order ε\varepsilon, as every location estimator does (see the contamination model).

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.

huber_m_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/huber-m-estimator/. The authors are listed in prov/ASDS28.jsonl.

from fractions import Fraction
from statistics import NormalDist

# Phi^{-1}(3/4): the MAD of N(0, 1).
Q3 = NormalDist().inv_cdf(0.75)


def psi(u, k):
    """Huber's psi: u clipped to [-k, k]."""
    if u > k:
        return k
    if u < -k:
        return -k
    return u


def rho(u, k):
    """Huber's loss: u^2/2 for |u| <= k, k|u| - k^2/2 beyond."""
    a = abs(u)
    return u * u / 2 if a <= k else k * a - k * k / 2


def exact_median(xs):
    """Median; exact (int or Fraction) for int or Fraction data."""
    s = sorted(xs)
    n = len(s)
    if n % 2 == 1:
        return s[n // 2]
    lo, hi = s[n // 2 - 1], s[n // 2]
    if isinstance(lo, (int, Fraction)) and isinstance(hi, (int, Fraction)):
        return Fraction(lo + hi, 2)
    return (lo + hi) / 2


def mad_scale(xs):
    """Normalized MAD: median |x - median| divided by Phi^{-1}(3/4)."""
    m = exact_median(xs)
    return float(exact_median([abs(v - m) for v in xs])) / Q3


def objective(xs, theta, k, sigma):
    """sum rho_k((x_i - theta)/sigma)."""
    return sum(rho((v - theta) / sigma, k) for v in xs)


def estimating_function(xs, theta, k, sigma):
    """Lambda(theta) = sum psi_k((x_i - theta)/sigma): continuous, nonincreasing, piecewise linear."""
    return sum(psi((v - theta) / sigma, k) for v in xs)


def huber_location(xs, k=1.345, sigma=None):
    """Huber M-estimate of location with a fixed scale.

    sigma defaults to the normalized MAD of xs. The result is the midpoint of the
    set of roots of Lambda, which is also the set of minimizers of the objective.
    With int or Fraction data and Fraction k and sigma the result is exact.
    Time O(n log n).
    """
    x = list(xs)
    if not x:
        raise ValueError("empty sample")
    if not k > 0:
        raise ValueError("k must be positive")
    if sigma is None:
        sigma = mad_scale(x)  # @line L1
    if sigma == 0:
        return exact_median(x)  # @line L1
    if sigma < 0:
        raise ValueError("sigma must be positive")
    c = k * sigma
    b = sorted({v - c for v in x} | {v + c for v in x})  # @line L2

    def lam(t):
        return estimating_function(x, t, k, sigma)  # @line L3

    # Lambda(b[0]) = n k > 0 and Lambda(b[-1]) = -n k < 0.
    lo, hi = 1, len(b) - 1
    while lo < hi:  # @line L4
        mid = (lo + hi) // 2
        if lam(b[mid]) <= 0:
            hi = mid
        else:
            lo = mid + 1
    t = lo
    l0, l1 = lam(b[t - 1]), lam(b[t])
    theta_lo = b[t - 1] + (b[t] - b[t - 1]) * l0 / (l0 - l1)  # @line L5

    lo, hi = 0, len(b) - 2
    while lo < hi:  # @line L6
        mid = (lo + hi + 1) // 2
        if lam(b[mid]) >= 0:
            lo = mid
        else:
            hi = mid - 1
    u = lo
    m0, m1 = lam(b[u]), lam(b[u + 1])
    theta_hi = b[u] + (b[u + 1] - b[u]) * m0 / (m0 - m1)  # @line L7
    return (theta_lo + theta_hi) / 2  # @line L8


def huber_irls(xs, k=1.345, sigma=None, tol=1e-12, max_iter=500):
    """The usual iteration: weighted means with weights min(1, k sigma / |x - theta|)."""
    x = [float(v) for v in xs]
    if sigma is None:
        sigma = mad_scale(x)
    theta = float(exact_median(x))
    if sigma == 0:
        return theta
    c = k * sigma
    for _ in range(max_iter):
        w = [1.0 if abs(v - theta) <= c else c / abs(v - theta) for v in x]
        new = sum(wi * v for wi, v in zip(w, x)) / sum(w)
        if abs(new - theta) <= tol * (1.0 + abs(theta)):
            return new
        theta = new
    return theta
test_huber_m_estimator.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/huber-m-estimator/. The authors are listed in prov/ASDS28.jsonl.

import random
from fractions import Fraction

import pytest

from huber_m_estimator import (
    estimating_function, exact_median, huber_irls, huber_location, mad_scale, objective,
)


def test_page_example() -> None:
    x = [1, 4, 5, 6, 8, 30]
    k, sigma = Fraction(3, 2), Fraction(2)
    assert huber_location(x, k, sigma) == Fraction(23, 4)
    assert estimating_function(x, Fraction(5), k, sigma) == Fraction(3, 2)
    assert estimating_function(x, Fraction(7), k, sigma) == Fraction(-5, 2)
    assert estimating_function(x, Fraction(23, 4), k, sigma) == 0
    # With the default k = 1.345 and the normalized MAD scale (MAD = 2) the clipping is symmetric.
    assert mad_scale(x) == pytest.approx(2.965204437011204)
    assert huber_location(x) == pytest.approx(5.75, abs=1e-12)


def test_flat_root_set_gives_midpoint() -> None:
    # Lambda = 0 on [1, 9]: no residual is inside (-k sigma, k sigma) there.
    assert huber_location([0, 10], 1, 1) == 5
    assert huber_location([0, 0, 10, 10], Fraction(1), Fraction(1)) == 5


def test_root_is_exact_with_fractions() -> None:
    rng = random.Random(1)
    for _ in range(300):
        n = rng.randint(1, 25)
        x = [rng.randint(-50, 50) for _ in range(n)]
        k = Fraction(rng.randint(1, 30), 10)
        sigma = Fraction(rng.randint(1, 40), 7)
        t = huber_location(x, k, sigma)
        assert estimating_function(x, t, k, sigma) == 0


def test_against_fine_grid_of_the_objective() -> None:
    rng = random.Random(2)
    for _ in range(20):
        n = rng.randint(2, 30)
        x = [rng.gauss(0.0, 1.0) for _ in range(n)]
        for _ in range(rng.randint(0, n // 3)):
            x[rng.randrange(n)] = rng.uniform(5.0, 50.0)
        k, sigma = 1.345, mad_scale(x)
        t = huber_location(x, k, sigma)
        lo, hi = min(x), max(x)
        steps = 4000
        h = (hi - lo) / steps
        grid = [lo + i * h for i in range(steps + 1)]
        vals = [objective(x, g, k, sigma) for g in grid]
        j = min(range(len(grid)), key=vals.__getitem__)
        # t is a minimizer: no grid point is lower.
        assert objective(x, t, k, sigma) <= vals[j] + 1e-9
        # If some residual is inside the quadratic zone, the minimizer is unique and the
        # best grid point is one of the two grid points around it.
        if any(abs(v - t) < k * sigma for v in x):
            assert abs(grid[j] - t) <= h * (1 + 1e-9)


def test_irls_agrees() -> None:
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(3, 40)
        x = [rng.gauss(10.0, 3.0) for _ in range(n)] + [rng.uniform(100, 1000) for _ in range(n // 5)]
        assert huber_irls(x) == pytest.approx(huber_location(x), abs=1e-8)


def test_limits_mean_and_median() -> None:
    rng = random.Random(4)
    for _ in range(100):
        n = rng.randint(1, 15)
        x = [rng.randint(-30, 30) for _ in range(n)]
        # k sigma larger than the range: every residual is inside, the estimate is the mean.
        assert huber_location(x, Fraction(1000), Fraction(1)) == Fraction(sum(x), n)
        # Distinct values, odd n, tiny k: the estimate is the median.
        y = rng.sample(range(-100, 100), 2 * rng.randint(0, 6) + 1)
        assert huber_location(y, Fraction(1, 1000), Fraction(1)) == exact_median(y)


def test_equivariance() -> None:
    rng = random.Random(5)
    for _ in range(50):
        x = [rng.gauss(0.0, 1.0) for _ in range(rng.randint(3, 20))]
        t = huber_location(x)
        a, b = rng.choice([-3.0, 0.5, 7.0]), rng.uniform(-10, 10)
        assert huber_location([a * v + b for v in x]) == pytest.approx(a * t + b, abs=1e-9)


def test_empirical_breakdown() -> None:
    # Move m points to a far value s. For m < n/2 the estimate stays in
    # [min clean - k R / q, max clean + k R / q] with R the clean range (the page proves this).
    # For m = ceil(n/2) it follows s.
    rng = random.Random(6)
    k = 1.345
    for n in (5, 6, 9, 10, 15):
        clean_all = [rng.uniform(0.0, 10.0) for _ in range(n)]
        for s in (1e6, 1e12):
            for m in range((n + 1) // 2 + 1):
                clean = clean_all[: n - m]
                x = clean + [s] * m
                t = huber_location(x, k)
                if 2 * m < n:
                    r = (max(clean) - min(clean)) / 0.6744897501960817
                    assert min(clean) - k * r - 1e-9 <= t <= max(clean) + k * r + 1e-9
                else:
                    assert t >= s / 4


def test_errors() -> None:
    with pytest.raises(ValueError):
        huber_location([])
    with pytest.raises(ValueError):
        huber_location([1, 2], k=0)
    # Zero MAD: the median is returned.
    assert huber_location([3, 3, 3, 3, 100]) == 3

History

Huber (1964) introduced the estimator, proved its minimax property for the symmetric contaminated normal, and gave Proposal 2 for the joint estimation of scale. The influence function approach of Hampel gave it a second optimality: Hampel, Ronchetti, Rousseeuw and Stahel (1986) present it as the optimal B-robust estimator of location. Holland and Welsch (1977) studied the reweighting algorithms for this and other weight functions in regression. Huber (1984) studied the finite-sample breakdown of M-estimators with a preliminary scale.

References

  1. Peter J. Huber, Robust estimation of a location parameter, The Annals of Mathematical Statistics 35(1), 1964, pp. 73 to 101 (the estimator, the minimax theorem for the contaminated normal, and the joint estimation of location and scale)
  2. Peter J. Huber and Elvezio M. Ronchetti, Robust Statistics, second edition, Wiley, 2009, Chapter 3 (M-estimators of location) and Chapter 4 (the minimax variance results)
  3. 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 2 (location M-estimators, the choice of k, the MAD scale and the iterative algorithms)
  4. Frank R. Hampel, Elvezio M. Ronchetti, Peter J. Rousseeuw and Werner A. Stahel, Robust Statistics, The Approach Based on Influence Functions, Wiley, 1986, Chapter 2 (the Huber estimator as the optimal B-robust estimator of location)
  5. Peter J. Huber, Finite sample breakdown of M- and P-estimators, The Annals of Statistics 12(1), 1984, pp. 119 to 126 (breakdown of M-estimators of location with a preliminary scale)
  6. Paul W. Holland and Roy E. Welsch, Robust regression using iteratively reweighted least-squares, Communications in Statistics, Theory and Methods 6(9), 1977, pp. 813 to 827 (iteratively reweighted least squares for Huber and other weight functions)

Where this leads

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