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
- Model
- Real RAM
- Properties
- deterministicexact in exact arithmeticnot in placeofflinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter J. Huber, 1964
The Huber M-estimator of location is the M-estimator with the loss for and 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 breakpoints. Huber proved in 1964 that a suitable 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 of real numbers, a tuning constant and a scale . By default is the normalized median absolute deviation, , computed once before the location. Put
The output is a minimizer of , which is the same as a root of . The roots form a closed interval. The algorithm returns its midpoint, so the output is unique.
The algorithm
is continuous, nonincreasing, and linear between consecutive points of the set . So it is enough to find the two breakpoints around the root and solve one linear equation.
HUBER(x, k, σ) ▷ x[1 .. n], k > 0- 1
if σ is not given then σ ← MAD(x)/Φ⁻¹(3/4); if σ = 0 then return the median of x - 2
b[0 .. M] ← the sorted distinct values of x_i − kσ and x_i + kσ - 3
Λ(θ) = Σ ψ_k((x_i − θ)/σ) ▷ O(n) per evaluation - 4
t ← the least index with Λ(b[t]) ≤ 0 ▷ binary search; Λ(b[0]) = nk > 0 - 5
θ_lo ← b[t−1] + (b[t] − b[t−1]) · Λ(b[t−1]) / (Λ(b[t−1]) − Λ(b[t])) - 6
u ← the greatest index with Λ(b[u]) ≥ 0 ▷ binary search; Λ(b[M]) = −nk < 0 - 7
θ_hi ← b[u] + (b[u+1] − b[u]) · Λ(b[u]) / (Λ(b[u]) − Λ(b[u+1])) - 8
return (θ_lo + θ_hi)/2
Line L5 finds the least root and line L7 the greatest root. If , then and the two lines give the same point.
Example
Take , and , so . The sorted breakpoints are , with . The binary searches evaluate at these points:
| clipped scaled residuals | ||
|---|---|---|
| 3 | 5 | |
| 5 | ||
| 7 | ||
| 9 |
Line L4 gives , and line L6 gives . Both lines L5 and L7 give . Check: at the clipped residuals are , 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 . With the default the estimate is also , because then only the points 1 and 30 are clipped, both at .
Correctness
is continuous and nondecreasing, so 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 is linear on each closed segment between consecutive breakpoints, and linear interpolation between two breakpoints gives an exact root. is convex and differentiable with , so its minimizers are exactly the roots of . The binary searches keep the facts and , 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. are real, , and (the case ends at line L1). Put , and . Let be the distinct values of .
Lemma 1. is continuous and nonincreasing on , and linear on each segment .
Proof. is continuous and nondecreasing, and is continuous and decreasing. So each term is continuous and nonincreasing, and so is the sum. Take in the open segment . No value lies in it, so for each the sign of and of is the same for all in the segment. So each is in one of three fixed classes: (the term is ), (the term is ), or (the term is ). Each term is an affine function of on the open segment, so is affine there. By continuity it is affine on the closed segment.
Lemma 2. The minimizers of are exactly the roots of , and they form a nonempty closed interval inside .
Proof. is convex and differentiable with : on the derivative is , on it is , and at both one-sided derivatives are . So is convex and differentiable with . A differentiable convex function is minimal at if and only if its derivative is 0 there. At every , so . In the same way . By continuity there is a root in . 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.
Lemma 3 (line L4 and line L5). Line L4 ends with , and line L5 gives the least root of .
Proof. The search keeps the invariant and . It holds at the start with and by Lemma 2. A step with sets , and a step with sets , so the invariant holds. The range shrinks at each step and the loop ends with . Since is nonincreasing and , no root is . By Lemma 1, is affine on , it goes from a positive value to a value , so it has exactly one root in this segment, at the point that line L5 computes. This is the least root.
Lemma 4 (line L6 and line L7). Line L6 ends with , and line L7 gives the greatest root .
Proof. The same argument with the invariant and , which holds at the start with and . No root is , and on the affine function goes from a value to a negative value, so its unique root there is the greatest root.
Theorem. HUBER returns the midpoint of the set of minimizers of .
Proof. By Lemma 2 this set is , and by Lemmas 3 and 4 lines L5 and L7 compute its two ends. Line L8 returns .
When the root is unique. If some satisfies at a root , then has slope at most near and the root is unique. If the root set is a segment of positive length, then on it, so no point is in the linear class on its interior.
Complexity
- Time. The sort in line L2 takes . Each binary search evaluates at points, and each evaluation costs . The MAD needs two medians, which take expected with quickselect. So the total is .
- Space. for the breakpoints.
- Arithmetic. With rational data, and , all steps are exact, and the root satisfies exactly. The default scale contains , 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 , . It is bounded, and the standardized gross-error sensitivity is .
- Efficiency at the normal. The asymptotic variance at is , with . A numerical evaluation gives:
| 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 gives 95% efficiency at the normal.
- Minimax variance (cited). For the model with symmetric, the Huber estimator with solving 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:
| 0.01 | 0.05 | 0.10 | 0.20 | |
|---|---|---|---|---|
| minimax | 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 with the MAD scale (proved). Replace points by any values, and let be the least and the greatest of the clean points and . For every clean term is , so . In the same way for . So every root lies in . The median of the new sample lies in , because more than half of the points are clean. So more than half of the absolute deviations are at most , which gives and . If , the output is the median, which is also in . So the estimate stays bounded. With points at one far value , the median and the estimate follow . 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: for . With a fixed it is only location equivariant.
- Limits. If is larger than the range of the sample, all residuals are in the linear part and the estimate is the mean. As the estimate tends to a median.
Variants and improvements
- Iteratively reweighted means. Start at the median and repeat with . Each step does not increase , 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. , where is the set of points in the linear part. On the segment that holds the root, one step is exact, because 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: and (Huber 1964). Its breakdown point depends on and is lower than one half (Huber 1984).
- Regression. Replace by the residual . The objective is still convex, but the breakdown point under leverage points is . 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 the estimate is not scale equivariant: in meters and in millimeters gives different results. Always divide by a robust scale.
- The standard deviation as scale. Outliers inflate it, so 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 , avoids this.
- A root set that is an interval. If no residual is in the linear part near the root, is 0 on a whole segment. For , and , every in 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 , 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ASDS28 Edit this page History Report an error Markdown