Algorithmadvanced
Least median of squares
Also called LMS regression.
Rousseeuw's regression that minimizes the median of the squared residuals. It has breakdown point near 1/2 but converges slowly, at rate n^(-1/3).
- Time
- O(n^3 log n) worst · best
- Space
- O(n^2) extra
- Where
- n = the number of data points (simple regression)
- Model
- Real RAM
- Properties
- deterministicexact in exact arithmeticnot in placeofflineregression equivariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter J. Rousseeuw, J. Michael Steele, William L. Steiger, Diane L. Souvaine, Herbert Edelsbrunner, 1984
Least median of squares (LMS) fits a regression by making the median of the squared residuals as small as possible, where least squares makes their sum small. Rousseeuw (1984) introduced it as the first estimator with a breakdown point near 1/2 in any dimension: almost half the data can be replaced before the fit can be carried away. For a line, the fit is the centre of the narrowest strip that holds just over half of the points. The price is statistical: the estimate converges at the slow rate , so LMS is used to find outliers and to start better estimators, not as a final fit.
In plain words
Lay a straight band of some width over the scatter plot and slide and tilt it until it covers just over half the points. Make the band as narrow as possible. The centre line of the narrowest band is the LMS line. Points far outside the band do not matter at all, so a large group of bad points cannot pull the line, as long as the good points are the majority.
For a fixed tilt, finding the best band is easy: look at the points along the band direction, sort them, and take the shortest run that covers enough of them. The best tilt is always one where two points touch the same edge of the band, so it is enough to try the tilt through each pair of points.
The problem
The input is points . In the notation with rows, this is the simple model with . For a line , the residuals are , and the objective is
The output is a minimizer and the value . This is the "median" of the name, in the version that gives the best breakdown point for a line. For coefficients, Rousseeuw and Leroy use .
The algorithm
The exact algorithm for a line tries every pairwise slope and finds the best intercept for each slope by a scan.
LMS-LINE(x, y)- 1
h ← ⌊n/2⌋ + 1 - 2
T ← the slopes (y_j − y_i)/(x_j − x_i) of all pairs with x_i ≠ x_j ▷ T ← {0} if there is none - 3
for each s in T do - 4
(a, ρ) ← BEST-INTERCEPT(s) - 5
keep (s, a, ρ) if ρ is the smallest so far - 6
return the kept s, a, and the objective ρ² BEST-INTERCEPT(s) ▷ the best a for a fixed slope s- 7
z ← the values y_i − s·x_i, sorted - 8
for i ← 1 to n − h + 1: the width of window i is z[i + h − 1] − z[i] - 9
i* ← a narrowest window; return ((z[i*] + z[i* + h − 1])/2, its width / 2)
Random subsets for many predictors. With coefficients, the same idea gives the PROGRESS algorithm of Rousseeuw and Leroy (1987): draw many random sets of points, fit the exact line or plane through each, adjust its intercept by BEST-INTERCEPT, and keep the best. The result is an approximation, and the number of draws needed to see one clean set with probability when a fraction is bad is , the same count as for RANSAC (see the RANSAC iteration bound).
Example
Take seven points; points 5, 6 and 7 are bad.
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
| 2 | 4 | 5 | 8 | 30 | 33 | 1 |
Here . For the slope of points 1 and 2, the values are . Sorted, they are , and the windows of four values have widths . The narrowest is , so and the half-width is . Some other slopes give:
| slope | best | half-width |
|---|---|---|
| 1 | 5/2 | 3/2 |
| 3/2 | 5/4 | 3/4 |
| 2 | −1/2 | 1/2 |
| 5/2 | −3/2 | 1 |
| 3 | −5/2 | 3/2 |
The best over all 21 pairwise slopes is , so the LMS line is , with : points 1 to 4 have residuals . Least squares gives , tilted by the three bad points. A brute force over all sets of four points and their best Chebyshev lines gives the same ; the test file checks this.
Correctness
For a fixed slope, the -th smallest is at most exactly when an interval of length holds of the values , and the shortest such interval is a window of consecutive sorted values. So BEST-INTERCEPT is exact. For the slope, the best band for a set of points has width , which is convex and piecewise linear in , with breakpoints only at slopes of pairs in . It tends to infinity at both ends, unless all points of share one , so it attains its minimum at a pairwise slope. Taking the minimum over all slopes in therefore gives the global minimum. The full proofs are below.
Proof: The best intercept is the centre of the narrowest window, and the best slope is a pairwise slope, so LMS-LINE is exactfull
Setting. The data are with , and . For a line , the residuals are , and the objective is the -th smallest of . LMS-LINE must return that minimize , and the value . Write , so .
Part 1. A fixed slope
Lemma 1. Fix , and let be the sorted values . Let , attained at . Then , attained at .
Proof. For , holds exactly when at least values lie in the interval . An interval that holds of the sorted values holds consecutive ones, , so its length is at least . So for all . The interval of length centred at the given holds the values , so equality holds there.
Lines L7 to L9 compute exactly this, in time for the sort and for the scan.
Part 2. The slope
For a set of indices, let , the width of at slope .
Lemma 2. .
Proof. A window of consecutive sorted values is a set with width equal to the window length, so . Any set of values spans at least consecutive sorted values, so its width is at least the length of some window, and .
Lemma 3. If the points of do not all have the same , then attains its minimum at a slope of two points . If they all have the same , is constant.
Proof. Each is linear in . The maximum of finitely many linear functions is convex and piecewise linear, and it changes from one function to another only where two of them are equal, that is at some . The minimum is concave and piecewise linear with breakpoints of the same kind. So is convex and piecewise linear, and all its breakpoints are pairwise slopes of points of . If for some , then as , so is not a single linear piece and has a breakpoint. A convex piecewise linear function that tends to at both ends has its minimum at a breakpoint. If all in are equal, every is constant.
Theorem 4. , where is the set of pairwise slopes of line L2 (or when all are equal). So LMS-LINE returns an optimal line and the value .
Proof. By Lemmas 1 and 2, . Take that attains the outer minimum. If its points have two different values, Lemma 3 gives a minimizing slope in . If not, is constant, and any slope, in particular one in , gives the same value. In both cases some has , and for every . Lines L3 to L5 take the best , and line L4 takes its best intercept by Lemma 1.
Part 3. Cost
, and each slope costs , so LMS-LINE takes time. Storing takes space; looping over the pairs without storing them takes extra space.
What is cited, not proved
The breakdown point for simple regression in general position with this (Rousseeuw 1984; Rousseeuw and Leroy 1987, Chapter 3) and the convergence rate (stated by Rousseeuw 1984 and proved in the framework of Kim and Pollard 1990) are cited on the page. They are not proved here.
Complexity
- LMS-LINE as written. slopes, each with a sort: time. It needs extra space if the pairs are looped over without storing .
- Faster exact algorithms for the line. Steele and Steiger (1986) studied the objective and gave an exact algorithm. Souvaine and Steele (1987) use the dual line arrangement: time and space, or time and space. Edelsbrunner and Souvaine (1990) reach time and space with a guided topological sweep.
- Higher dimension. The exact problem with coefficients takes about time by the same kind of enumeration, which is why random subsets are used in practice. Each random subset costs for the intercept adjustment.
Properties
- Breakdown point for a line in general position (Rousseeuw 1984; Rousseeuw and Leroy 1987, Chapter 3), in the replacement version . Bad points may have any and ; leverage points cannot break it either.
- Exact fit property. If at least points lie exactly on one line, the LMS line is that line, whatever the others are: that line has objective 0, and no other line can hold points, because two lines share at most one point. The test file checks this with 6 of 10 points on a line.
- Slow convergence. For clean data with a smooth error density, the LMS estimate converges at the rate , not (Rousseeuw 1984). Kim and Pollard (1990) prove limit theorems for estimators of this kind, with LMS as an example. This rate is cited here, not proved. In practice, LMS has very low efficiency under normal errors.
- Regression, scale and affine equivariant. Adding a line to , scaling , or changing the coordinates of by an affine map changes the fit in the matching way.
- Not unique, not continuous. Several lines can tie, and a small change of one point can make the fit jump between two far-apart lines. The objective has many local minima.
Variants and improvements
- Least trimmed squares minimizes the sum of the smallest squared residuals. It has the same breakdown point, converges at the rate , and has a fast heuristic, FAST-LTS. Rousseeuw and Van Driessen recommend it over LMS.
- Reweighted least squares. After LMS, give weight 0 to points whose standardized residual is large (for example above 2.5 in units of a robust scale), and fit least squares to the rest. This recovers efficiency and keeps the breakdown point.
- MM-estimators. An MM-estimator starts from a high-breakdown fit such as LMS or LTS and improves it by an M-step with a fixed robust scale, reaching high efficiency.
- Least quantile of squares. Any between and gives a valid estimator, with breakdown point about .
- Approximation algorithms. In computational geometry, LMS is the problem of the narrowest slab that holds points, and there are approximation algorithms with a guaranteed factor.
When to use it
Use LMS as an exploratory tool and as a starting point: to find which points do not fit the main linear pattern, and to start an iterative estimator. For a line in two variables with fewer than a few thousand points, the exact algorithm is practical. For a final fit, use a reweighted fit, LTS, or an MM-estimator. For a quick robust line with less than 29 percent of bad points, Theil-Sen is simpler and more efficient.
Pitfalls
- Using LMS as the final fit. Its rate means large sampling error, even with clean data.
- Too few random subsets. With PROGRESS, the number of draws must grow quickly with and with the fraction of bad points; with too few draws the result is just a poor fit, with no warning.
- Forgetting the intercept adjustment. The line through points is rarely the best line with that slope. BEST-INTERCEPT is cheap and lowers the objective.
- The meaning of median. With , as some software uses, the breakdown point is lower by about and the exact fit property needs more points. Say which you use.
- Floating point. The narrowest window compares differences of nearly equal values. Ties between bands are common in rounded data; report them.
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/least-median-of-squares/. The authors are listed in prov/0GC0T5.jsonl.
import random
from fractions import Fraction
def coverage(n):
"""h = floor(n/2) + 1, the number of residuals the fit must cover."""
return n // 2 + 1
def best_intercept(s, x, y, h):
"""For a fixed slope s: the intercept that minimises the h-th smallest
|y - s x - a|, and the half-width of the narrowest window of h values
of z = y - s x. O(n log n)."""
z = sorted(yi - s * xi for xi, yi in zip(x, y)) # @line L7
best = None
for i in range(len(z) - h + 1): # @line L8
w = z[i + h - 1] - z[i]
if best is None or w < best[0]:
best = (w, i)
w, i = best
return (z[i] + z[i + h - 1]) / 2, w / 2 # @line L9
def lms_line(x, y):
"""Exact least median of squares line for simple regression.
The best slope is among the pairwise slopes (or any slope if all x are
equal), so try each one with its best intercept. O(n^3 log n) time.
Returns (slope, intercept, objective) with objective = the h-th smallest
squared residual.
"""
x = [Fraction(v) for v in x]
y = [Fraction(v) for v in y]
n = len(x)
if n < 2:
raise ValueError("need at least two points")
h = coverage(n) # @line L1
slopes = {(y[j] - y[i]) / (x[j] - x[i]) # @line L2
for i in range(n) for j in range(i + 1, n) if x[i] != x[j]}
if not slopes:
slopes = {Fraction(0)}
best = None
for s in sorted(slopes): # @line L3
a, r = best_intercept(s, x, y, h) # @line L4
if best is None or r < best[2]: # @line L5
best = (s, a, r)
s, a, r = best
return s, a, r * r # @line L6
def lms_random(x, y, trials, rng=None):
"""PROGRESS-style approximation: slopes through random pairs of points,
each with its best intercept. O(trials * n log n) time."""
rng = rng or random.Random(0)
x = [Fraction(v) for v in x]
y = [Fraction(v) for v in y]
n = len(x)
h = coverage(n)
best = None
for _ in range(trials):
i, j = rng.sample(range(n), 2)
if x[i] == x[j]:
continue
s = (y[j] - y[i]) / (x[j] - x[i])
a, r = best_intercept(s, x, y, h)
if best is None or r < best[2]:
best = (s, a, r)
if best is None:
raise ValueError("no pair with different x was drawn")
s, a, r = best
return s, a, r * r
def hth_squared_residual(s, a, x, y):
"""The objective of the line y = a + s x."""
r = sorted((Fraction(yi) - a - s * Fraction(xi)) ** 2 for xi, yi in zip(x, y))
return r[coverage(len(x)) - 1]
test_least_median_of_squares.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-median-of-squares/. The authors are listed in prov/0GC0T5.jsonl.
import random
from fractions import Fraction
from itertools import combinations
from least_median_of_squares import (
best_intercept, coverage, hth_squared_residual, lms_line, lms_random,
)
def chebyshev_error(pts):
"""Minimax error of the best line through pts (distinct x), by the
de la Vallee Poussin rule: the largest levelled error over all triples."""
if len(pts) < 3:
return Fraction(0)
best = Fraction(0)
for (xa, ya), (xb, yb), (xc, yc) in combinations(sorted(pts), 3):
on_line = ya + (yc - ya) * (xb - xa) / (xc - xa)
best = max(best, abs(yb - on_line) / 2)
return best
def brute_force_objective(x, y):
"""min over h-subsets of the squared Chebyshev error of the subset."""
pts = [(Fraction(a), Fraction(b)) for a, b in zip(x, y)]
h = coverage(len(pts))
return min(chebyshev_error(sub) for sub in combinations(pts, h)) ** 2
def test_page_example() -> None:
x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 4, 5, 8, 30, 33, 1]
s, a, obj = lms_line(x, y)
assert (s, a, obj) == (2, Fraction(-1, 2), Fraction(1, 4))
assert hth_squared_residual(s, a, x, y) == obj
assert obj == brute_force_objective(x, y)
def test_against_subset_brute_force() -> None:
rng = random.Random(31)
for _ in range(120):
n = rng.randint(4, 9)
x = rng.sample(range(-8, 9), n)
y = [rng.randint(-8, 8) for _ in range(n)]
s, a, obj = lms_line(x, y)
assert obj == brute_force_objective(x, y)
assert hth_squared_residual(s, a, x, y) == obj
def test_fixed_slope_intercept_is_optimal() -> None:
rng = random.Random(32)
for _ in range(200):
n = rng.randint(2, 9)
x = [Fraction(rng.randint(-5, 5)) for _ in range(n)]
y = [Fraction(rng.randint(-5, 5)) for _ in range(n)]
s = Fraction(rng.randint(-6, 6), rng.randint(1, 3))
h = coverage(n)
a, r = best_intercept(s, x, y, h)
assert hth_squared_residual(s, a, x, y) == r * r
# No other intercept from a fine grid does better.
for t in range(-60, 61):
assert hth_squared_residual(s, Fraction(t, 4), x, y) >= r * r
def test_ties_in_x() -> None:
rng = random.Random(33)
for _ in range(100):
n = rng.randint(3, 8)
x = [rng.randint(0, 3) for _ in range(n)]
y = [rng.randint(-5, 5) for _ in range(n)]
s, a, obj = lms_line(x, y)
# Compare with every line through two points and every slope on a grid.
for t in range(-40, 41):
sl = Fraction(t, 4)
ai, r = best_intercept(sl, [Fraction(v) for v in x], [Fraction(v) for v in y], coverage(n))
assert obj <= r * r
def test_exact_fit_and_outliers() -> None:
# 6 of 10 points on y = 3 - 2x, the rest anywhere: LMS finds the line.
x = list(range(10))
y = [3 - 2 * v for v in x]
for i, v in zip((1, 4, 6, 9), (100, -50, 77, 0)):
y[i] = v
assert lms_line(x, y) == (-2, 3, 0)
def test_random_pairs_never_beat_exact() -> None:
rng = random.Random(34)
for _ in range(40):
n = rng.randint(5, 14)
x = [rng.randint(0, 20) for _ in range(n)]
y = [rng.randint(0, 20) for _ in range(n)]
if len(set(x)) == 1:
continue
exact = lms_line(x, y)[2]
approx = lms_random(x, y, 30, random.Random(n))[2]
assert approx >= exact
# With many draws every pair is seen, and the answer is exact.
assert lms_random(x, y, 3000, random.Random(n))[2] == exact
History
Rousseeuw introduced least median of squares in 1984, following Hampel's suggestion to replace the sum in least squares by a median. It was the first regression estimator equivariant under affine changes of with a breakdown point near 1/2 in every dimension. The book of Rousseeuw and Leroy (1987) made it a standard tool, with the PROGRESS program. Exact algorithms for the line came from computational geometry: Steele and Steiger (1986), Souvaine and Steele (1987), and Edelsbrunner and Souvaine (1990). Kim and Pollard (1990) put its slow rate in the general theory of cube root asymptotics. From the 1990s, least trimmed squares, with FAST-LTS (Rousseeuw and Van Driessen 2006), replaced LMS as the default high breakdown regression.
References
- Peter J. Rousseeuw, Least median of squares regression, Journal of the American Statistical Association 79(388), 1984, pp. 871 to 880 (the definition, the breakdown point, the convergence rate n^(-1/3), and the random subset algorithm)
- Peter J. Rousseeuw and Annick M. Leroy, Robust Regression and Outlier Detection, Wiley, 1987, Chapter 3 (the breakdown point of LMS for the coverage h) and Chapter 5 (the PROGRESS algorithm with random subsets and the intercept adjustment)
- JeongHoon Kim and David Pollard, Cube root asymptotics, The Annals of Statistics 18(1), 1990, pp. 191 to 219 (the n^(-1/3) rate and the limit distribution of estimators of this type, with least median of squares as an example)
- J. Michael Steele and William L. Steiger, Algorithms and complexity for least median of squares regression, Discrete Applied Mathematics 14(1), 1986, pp. 93 to 100, The whole paper (the structure of the LMS objective for a line and an exact algorithm)
- Diane L. Souvaine and J. Michael Steele, Time- and space-efficient algorithms for least median of squares regression, Journal of the American Statistical Association 82(399), 1987, pp. 794 to 801 (the LMS line in O(n^2) time and space, and in O(n^2 log n) time and O(n) space, by the dual line arrangement)
- Herbert Edelsbrunner and Diane L. Souvaine, Computing least median of squares regression lines and guided topological sweep, Journal of the American Statistical Association 85(409), 1990, pp. 115 to 119, The whole paper (the LMS line in O(n^2) time and O(n) space)
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 0GC0T5 Edit this page History Report an error Markdown