Algorithmadvanced
Repeated median regression
Also called Siegel's repeated median.
Siegel's slope estimate: for each point take the median of its slopes to the others, then the median of those. It is the first regression estimator with breakdown point 1/2.
- Time
- O(n^2 log n) worstO(n log^2 n) expected
- Space
- O(n) extra
- Where
- n = the number of data points
- Model
- Real RAM
- Properties
- randomizedexact in exact arithmeticnot in placeofflinerandomizedregression equivariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew F. Siegel, Jiří Matoušek, David M. Mount, Nathan S. Netanyahu, Peter J. Rousseeuw, 1982
Repeated median regression fits a line in two steps of medians. For each data point, take the median of the slopes from it to all the other points. The slope is the median of these medians. Siegel (1982) introduced it as the first regression estimator whose breakdown point is 50 percent: almost half the points can be replaced before the slope can be carried away. The direct method takes time. This page gives a simple randomized selection in expected time, built on the inversion counts of the Theil-Sen estimator.
In plain words
Each point votes for a slope. To choose its vote, a point looks at the lines from itself to every other point and takes the middle steepness. A good point sees mostly good partners, so its vote is sensible even if many partners are bad. Then we take the middle of all the votes.
A bad point can spoil its own vote and one line for every good point. A good point keeps a sensible vote while fewer than half of its lines are spoiled, so the fit survives almost half bad points. The Theil-Sen estimator pools all the lines in one big vote, and there the bad lines win once about 29 percent of the points are bad.
The problem
The input is points , at least two with different . For , . Point has slopes, one for each with . Siegel's estimator is
On this page each median of the slope is an order statistic, so that is always one of the slopes: the inner median is the high median , the -th smallest of the slopes of , and the outer median is the low median, the -th smallest of the over the points with . The intercept is the usual median, with the mean of the two middle values for even . Siegel also defines a repeated median intercept; see the variants.
The algorithm
For a value and a point , let and be the numbers of slopes of that are and . Then exactly when , and exactly when . So one pass of per-point inversion counting tells, for every point at once, on which side of its median lies, without computing the median. The algorithm is randomized quickselect over the implicit list of point medians.
REPEATED-MEDIAN(x, y)- 1
d_j ← the number of slopes of j, for all j ▷ per-point inversion counts at −∞, +∞ - 2
k_j ← ⌊d_j/2⌋ + 1; K ← ⌈n'/2⌉ ▷ n' = the number of points with d_j > 0 - 3
lo ← −∞; hi ← +∞ - 4
A ← the points with d_j > 0 ▷ the points with lo < m_j < hi - 5
loop - 6
pick i uniformly from A; v ← m_i, the k_i-th smallest slope of point i - 7
for all j: ℓ_j ← ℓ_j(v), e_j ← e_j(v) ▷ one merge sort for each count - 8
cl ← #{j : ℓ_j ≥ k_j}; ce ← #{j : e_j ≥ k_j} ▷ the medians < v and ≤ v - 9
if cl < K ≤ ce then b ← v and leave the loop - 10
if K ≤ cl then hi ← v else lo ← v - 11
A ← the points j of A with lo < m_j < hi ▷ from the counts saved at lo and hi - 12
a ← the median of y_j − b·x_j - 13
return (b, a)
Per-point counts. As on the Theil-Sen page, list the points by and count the inversions of the values ; the inversions are the pairs with . During the merge sort, when a right item is output, the left items still waiting are larger, and when a left item is output, the right items already out are smaller. Adding these numbers to the items gives every point its own count in time. Then is the count of for , and minus the count for .
Example
Take the data of the Theil-Sen page, with one wild value:
| 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 2 | 3 | 5 | 6 | 8 | 40 | |
| slopes of , sorted | 1, 4/3, 3/2, 3/2, 38/5 | 1, 3/2, 5/3, 2, 37/4 | 1, 3/2, 3/2, 2, 35/3 | 1, 4/3, 3/2, 2, 17 | 3/2, 3/2, 5/3, 2, 32 | 38/5, 37/4, 35/3, 17, 32 |
| (3rd of 5) | 3/2 | 5/3 | 3/2 | 3/2 | 5/3 | 35/3 |
Each point has slopes and . The wild point 6 has a wild median, but it is one vote of six. With , the sorted medians give . The residuals are , so . The fit is . Theil-Sen gives , and least squares .
A run of the selection. Suppose line L6 picks point 2, so . The medians below are those of points 1, 3, 4, so ; with points 2 and 5, . Since , line L10 sets , and becomes . Next, line L6 picks point 4, so , with and . Now , and .
Correctness
The per-point counts are right because a pair is an inversion exactly when its slope is in the open interval, and the merge sort charges each inversion once to each of its two points. The loop keeps the invariant , so the answer is always the median of some point of , and is returned only when , which holds exactly when . Each round that does not return removes at least the pivot point from , so the loop ends.
Breakdown point. For clean data with distinct , the breakdown point in the replacement sense is . With bad points far to the right on a steep parabola, every point has at least half of its slopes huge, so every high median is huge. With fewer bad points, each good point has fewer free slopes than its median needs, so its median stays within the range of the clean slopes; more than half the medians are such, so stays there too. The full proofs are below.
Proof: The per-point counts are inversion counts, the selection returns the repeated median slope, and the breakdown point is floor(n/2)/nfull
Setting. The data are . For , . Point has slopes, one for each with . For , its median is , the -th smallest of its slopes with (the high median). Let be the number of points with and . The repeated median slope is the -th smallest of the values (the low median). For a value and a point , and are the numbers of slopes of that are and .
Part 1. The per-point counts
The keys of the points at a slope are , with the limit orders at and at , as on the Theil-Sen page.
Lemma 1. For , list the points by the key at , ties by the key at , and let be the keys at in this order. The pair is an inversion of if and only if and .
Proof. For , . So the key of is above the key of at exactly when (at , always), and below it at exactly when (at , always). The opposite pattern would need . Pairs with compare by at every , so they keep their order. Pairs tied at are listed in their order at . So the inversions are the pairs in opposite strict order at and at , which are the pairs with .
Lemma 2. The merge sort in per_point_between adds to each point the number of inversions it belongs to.
Proof. Merge sort counts each inversion , before and , in exactly one merge: the one where is in the left half and in the right half. In that merge, when the right item is output, the left items not yet output are exactly the left items , and gets their number. When a left item is output, the right items already output are exactly the right items , and gets their number. So each inversion adds 1 to both its points.
So line L7 computes $\ell_j(v) = $ count and $e_j(v) = d_j - $ count for all in time, and line L1 computes $d_j = $ count. Then
because the -th smallest slope is below exactly when at least slopes are.
Part 2. The selection
Lemma 3. A value is the -th smallest of the if and only if .
Proof. As for any multiset: the -th smallest is exactly when at least values are , and it is not exactly when fewer than values are .
Invariant. At line L5, with and the last values set at line L10 (first and ), the set is , and . So for some .
Proof. At the start every is finite, so is all kept points, and . In a round, line L9 returns if Lemma 3 says it is . Otherwise either , and line L10 sets , or , and it sets . In both cases the inequality holds for the new interval. Line L11 keeps the with () and (), using the counts saved at the last change of each end. The values in number , and is one of them.
Termination. The pivot comes from a point . If the round does not return, the new interval excludes , so leaves . So drops by at least one in every round, and the loop ends after at most rounds with the answer, because is never empty. The value returned is by Lemma 3.
Expected number of rounds. The pivot is the median of a uniformly random point of . This is randomized quickselect over the multiset : with probability at least the pivot has rank between and in it, and then at least a quarter of leaves. So the expected number of rounds is . Each round sorts the slopes of one point and runs three merge sorts, time. The expected total is , and the worst case is .
Part 3. The breakdown point
Assume the clean data have distinct , so for all . Replace points by arbitrary points.
Lemma 4. Among numbers, of them free and the rest fixed, the -th smallest can be sent to exactly when , to exactly when , and otherwise it lies between the smallest and the largest fixed number.
Proof. To send the -th smallest up, at least values must be large; the fixed ones are bounded. If , send all free values up. The other side is the same. If neither holds, at least one fixed value is and one is the -th smallest.
Upper bound, points suffice. Put the -th bad point at and with . All slopes that involve a bad point then tend to together. A clean point has slopes, of them free, and , so , and its median goes to . So do the medians of the bad points, whose slopes are all free. So all medians, and , go to .
Lower bound, points do not suffice. Let be the range of the slopes among the clean points; it does not depend on the bad points. Since clean points have distinct , every point has a slope, so .
Take a clean point, and let bad points share its . It has slopes, of them free, and , so . Now , so
using . By Lemma 4, the median of the clean point lies between two of its clean slopes, so in .
So at least of the point medians are in , and at most are free. The outer median has and , both larger than . By Lemma 4 again, whatever the bad points are.
So the breakdown point in the replacement sense is
Complexity
- One round sorts the slopes of one point and runs three merge sorts: time and space.
- Number of rounds. The pivot is the median of a random active point, so this is quickselect on the medians: rounds in expectation, at most in the worst case.
- Total. expected time and space. The worst case is , and the answer is always exact.
- Faster algorithms. Matoušek, Mount and Netanyahu (1998) give a randomized algorithm in expected time. It keeps an interval of slopes and samples slopes inside it, as Matoušek's slope selection does, and tracks for each point how many of its slopes lie below, inside and above. Their paper also gives a simpler algorithm in time.
- The direct method computes each point's median by quickselect: time and space. For a few thousand points this is fast enough.
Properties
- Breakdown point , the most a regression equivariant estimator can have, up to rounding. The values are , , , for ; compare , , , for Theil-Sen.
- Exact fit. If all points lie on one line, every slope equals its slope, and so does .
- Regression equivariant. Adding to adds to and to .
- Not affine equivariant in x and y together. The fit depends on which variable is called ; this is true of all the slope methods on these pages.
- Efficiency. In a simulation with equally spaced and 2000 samples of standard normal noise, the variance of the least squares slope was 0.73 of the variance of the repeated median slope. Theil-Sen gave 0.93 in the same setting. These are measured values, not theorems. The repeated median buys its higher breakdown with some efficiency.
Variants and improvements
- Repeated median intercept. Siegel (1982) also defines , the repeated median of the intercepts of the pairwise lines. It is also robust; the median of the residuals used here is simpler.
- Several predictors. Siegel's definition extends to a model with coefficients: compute the exact fit through each -subset of points, then take nested medians over the indices. The breakdown point stays near 1/2, but the cost grows like .
- Averaged medians. Siegel uses the usual median, with the mean of the two middle values. Then need not be a slope, and the selection above does not apply directly; the direct method is easy.
- Online and moving windows. For time series, the repeated median over a sliding window gives a robust trend filter, updated in time per step by keeping the slopes in sorted order.
When to use it
Use the repeated median for a robust line in two variables when up to half the points may be wrong, and when you want a fit with a closed form, no random search and no tuning constant. It is a good start for an iterative method, such as an MM-estimator step. If at most a quarter of the points may be bad, Theil-Sen is more efficient. For a fit that also gives an outlier map, least trimmed squares is the common choice.
Pitfalls
- Median conventions. Libraries differ in the inner and outer medians: mean of the middle pair, low median, or high median. The breakdown point is the same, but the answers differ on small samples. Say which one you use.
- Tied x values. Pairs with have no slope. A point whose is shared by all others has no slopes; leave it out of the outer median.
- Bounded is not unbiased. Below the breakdown point the slope stays in the range of the clean slopes, but almost half bad points can still move it far inside that range. A high breakdown point is a guarantee against disaster, not a promise of a good fit.
- Quadratic memory. Storing all slopes is not needed; compute the slopes of one point at a time.
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/repeated-median-regression/. The authors are listed in prov/DYDSMR.jsonl.
import random
from fractions import Fraction
NEG_INF = "-inf"
POS_INF = "+inf"
def _key(s, x, y, i):
"""Sort key of point i for the order of y - s x at the slope s."""
if s == NEG_INF:
return (x[i], y[i])
if s == POS_INF:
return (-x[i], y[i])
return (y[i] - s * x[i],)
def per_point_between(lo, hi, x, y):
"""cnt[i] = number of j with lo < s_ij < hi, for every point i.
The pairs counted are the inversions of the hi-keys listed in the order
of the lo-keys; merge sort charges each inversion to both its ends.
O(n log n) time.
"""
n = len(x)
order = sorted(range(n), key=lambda i: (_key(lo, x, y, i), _key(hi, x, y, i)))
items = [(_key(hi, x, y, i), i) for i in order]
cnt = [0] * n
def sort(seq):
if len(seq) <= 1:
return seq
mid = len(seq) // 2
left, right = sort(seq[:mid]), sort(seq[mid:])
out, i, j = [], 0, 0
for v in right:
while i < len(left) and left[i][0] <= v[0]:
cnt[left[i][1]] += j # right items already out are smaller
out.append(left[i])
i += 1
cnt[v[1]] += len(left) - i # left items still waiting are larger
out.append(v)
j += 1
for item in left[i:]:
cnt[item[1]] += j
out.append(item)
return out
sort(items)
return cnt
def _slopes_of(i, x, y):
return [Fraction(y[j] - y[i]) / (x[j] - x[i]) for j in range(len(x)) if x[j] != x[i]]
def repeated_median_slope(x, y, rng=None):
"""Siegel's repeated median slope, with order-statistic medians:
inner = high median (floor(d/2) + 1)-th smallest of the d slopes of a point,
outer = low median ceil(n'/2)-th smallest of the n' point medians.
Randomized selection over the point medians, O(n log^2 n) expected time."""
rng = rng or random.Random(0)
n = len(x)
d = per_point_between(NEG_INF, POS_INF, x, y) # @line L1
keep = [i for i in range(n) if d[i] > 0]
if not keep:
raise ValueError("need two points with different x")
k = [d[i] // 2 + 1 for i in range(n)] # @line L2
K = (len(keep) + 1) // 2
le_lo = [0] * n # slopes of j <= lo, at lo = -inf # @line L3
lt_hi = list(d) # slopes of j < hi, at hi = +inf
active = list(keep) # @line L4
while True: # @line L5
i = rng.choice(active) # @line L6
v = sorted(_slopes_of(i, x, y))[k[i] - 1]
above = per_point_between(v, POS_INF, x, y) # @line L7
lt = per_point_between(NEG_INF, v, x, y)
le = [d[j] - above[j] for j in range(n)]
cl = sum(1 for j in keep if lt[j] >= k[j]) # m_j < v # @line L8
ce = sum(1 for j in keep if le[j] >= k[j]) # m_j <= v
if cl < K <= ce: # @line L9
return v
if K <= cl: # @line L10
lt_hi = lt
else:
le_lo = le
# m_j > lo iff fewer than k_j slopes of j are <= lo; m_j < hi likewise.
active = [j for j in active if le_lo[j] < k[j] and lt_hi[j] >= k[j]] # @line L11
def repeated_median(x, y, rng=None):
"""Slope b by the repeated median, intercept a = median of y - b x."""
if len(x) != len(y):
raise ValueError("x and y differ in length")
x = [Fraction(v) for v in x]
y = [Fraction(v) for v in y]
b = repeated_median_slope(x, y, rng)
res = sorted(yi - b * xi for xi, yi in zip(x, y)) # @line L12
m = len(res)
return b, (res[(m - 1) // 2] + res[m // 2]) / 2 # @line L13
def naive_repeated_median_slope(x, y):
"""Direct O(n^2 log n) version with the same order-statistic medians."""
x = [Fraction(v) for v in x]
y = [Fraction(v) for v in y]
meds = []
for i in range(len(x)):
s = sorted(_slopes_of(i, x, y))
if s:
meds.append(s[len(s) // 2])
if not meds:
raise ValueError("need two points with different x")
meds.sort()
return meds[(len(meds) + 1) // 2 - 1]
def breakdown_count(n):
"""Least number of replaced points that can carry the slope away,
for clean data with distinct x: floor(n/2)."""
return n // 2
test_repeated_median_regression.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/repeated-median-regression/. The authors are listed in prov/DYDSMR.jsonl.
import random
from fractions import Fraction
import pytest
from repeated_median_regression import (
NEG_INF, POS_INF, breakdown_count, naive_repeated_median_slope,
per_point_between, repeated_median, repeated_median_slope,
)
def F(v):
return [Fraction(t) for t in v]
def test_page_example() -> None:
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 6, 8, 40]
assert naive_repeated_median_slope(x, y) == Fraction(3, 2)
b, a = repeated_median(x, y)
assert b == Fraction(3, 2)
assert a == Fraction(1, 2)
def test_per_point_counts_against_brute_force() -> None:
rng = random.Random(21)
for _ in range(300):
n = rng.randint(1, 10)
x = F(rng.randint(0, 4) for _ in range(n))
y = F(rng.randint(-4, 4) for _ in range(n))
lo = Fraction(rng.randint(-10, 10), rng.randint(1, 3))
hi = lo + Fraction(rng.randint(1, 20), 3)
for a, b in ((NEG_INF, POS_INF), (NEG_INF, hi), (lo, POS_INF), (lo, hi)):
got = per_point_between(a, b, x, y)
for i in range(n):
want = 0
for j in range(n):
if x[j] == x[i]:
continue
s = (y[j] - y[i]) / (x[j] - x[i])
if (a == NEG_INF or s > a) and (b == POS_INF or s < b):
want += 1
assert got[i] == want
def test_against_naive_small() -> None:
rng = random.Random(22)
for t in range(400):
n = rng.randint(2, 12)
x = [rng.randint(0, 5) for _ in range(n)]
y = [rng.randint(-6, 6) for _ in range(n)]
if len(set(x)) == 1:
with pytest.raises(ValueError):
repeated_median_slope(F(x), F(y))
continue
want = naive_repeated_median_slope(x, y)
assert repeated_median_slope(F(x), F(y), random.Random(t)) == want
def test_against_naive_large() -> None:
rng = random.Random(23)
n = 200
x = [rng.randint(0, 10**6) for _ in range(n)]
y = [rng.randint(0, 10**6) for _ in range(n)]
want = naive_repeated_median_slope(x, y)
for seed in range(3):
assert repeated_median_slope(F(x), F(y), random.Random(seed)) == want
def test_exact_line_and_equivariance() -> None:
x = [0, 1, 3, 4, 7, 9, 12]
y = [Fraction(5) - Fraction(2, 3) * v for v in x]
assert repeated_median(x, y) == (Fraction(-2, 3), 5)
rng = random.Random(24)
x = [rng.randint(0, 50) for _ in range(25)]
y = [rng.randint(0, 50) for _ in range(25)]
b, a = repeated_median(x, y)
b2, a2 = repeated_median(x, [yi + 3 + 2 * xi for xi, yi in zip(x, y)])
assert (b2, a2) == (b + 2, a + 3)
def test_breakdown() -> None:
rng = random.Random(25)
for n in (9, 10):
m_star = breakdown_count(n)
xc = list(range(n))
yc = [rng.randint(0, 5) for _ in range(n)]
lo = min((yc[j] - yc[i]) / (j - i) for i in range(n) for j in range(i + 1, n))
hi = max((yc[j] - yc[i]) / (j - i) for i in range(n) for j in range(i + 1, n))
# m* - 1 bad points, of any kind, keep the slope in the clean range.
for _ in range(100):
x, y = list(xc), list(yc)
for i in rng.sample(range(n), m_star - 1):
x[i] = rng.randint(-10**6, 10**6)
y[i] = rng.randint(-10**6, 10**6)
if len(set(x)) < n:
continue
assert lo <= naive_repeated_median_slope(x, y) <= hi
# m* bad points far right on a steep parabola carry it away.
last = None
for t in (10, 10**3, 10**5):
x, y = list(xc), list(yc)
for j in range(m_star):
x[j] = n + j
y[j] = (j + 1) ** 2 * t
b = repeated_median_slope(F(x), F(y))
assert b == naive_repeated_median_slope(x, y)
assert last is None or b > 50 * last
last = b
History
Andrew Siegel published the repeated median in Biometrika in 1982. It answered the question, raised by the work of Hampel and others on breakdown, whether a regression estimator can resist almost half of the data being bad. Rousseeuw and Leroy (1987) placed it next to least median of squares, the other early estimator with a 50 percent breakdown point. The question of computing it fast was studied in computational geometry: Stein and Werman gave an deterministic algorithm in 1992, and Matoušek, Mount and Netanyahu (1998) an expected time algorithm.
References
- Andrew F. Siegel, Robust regression using repeated medians, Biometrika 69(1), 1982, pp. 242 to 244 (the repeated median slope and intercept, and the breakdown point of 50 percent)
- Jiří Matoušek, David M. Mount and Nathan S. Netanyahu, Efficient randomized algorithms for the repeated median line estimator, Algorithmica 20(2), 1998, pp. 136 to 150 (a randomized algorithm in O(n log n) expected time and a simpler one in O(n log^2 n))
- Peter J. Rousseeuw, Nathan S. Netanyahu and David M. Mount, New statistical and computational results on the repeated median line, in S. Morgenthaler, E. Ronchetti and W. A. Stahel (eds.), New Directions in Statistical Data Analysis and Robustness, Birkhäuser, Basel, 1993, pp. 177 to 194, The whole paper (statistical properties of the repeated median line and its computation)
- Peter J. Rousseeuw and Annick M. Leroy, Robust Regression and Outlier Detection, Wiley, 1987, Chapter 2 (the repeated median in simple regression, compared with the Theil-Sen slope and least median of squares)
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 DYDSMR Edit this page History Report an error Markdown