Algorithmcore
Theil-Sen estimator
Also called Sen's slope estimator, median of pairwise slopes.
Estimates the slope of a line by the median of the slopes through all pairs of points. It breaks down at about 29 percent and can be computed in O(n log n) time.
- Time
- O(n^2 log n) worstO(n log 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
- Henri Theil, Pranab Kumar Sen, Richard Cole, Jeffrey S. Salowe, William L. Steiger, Endre Szemerédi, Jiří Matoušek, 1950
The Theil-Sen estimator fits a line to points in the plane. The slope is the median of the slopes of the lines through all pairs of points, and the intercept is the median of the residuals . It needs no tuning constant, it is exact for data on a line, and more than a quarter of the points must be bad before it can be carried away: the breakdown point is percent. There are slopes, but the median can be found in time, because the number of slopes below a value is an inversion count.
In plain words
Draw a line through each pair of points and write down how steep it is. A wild point spoils only the lines that go through it. Sort all the steepness values and take the middle one as the slope of the fit. Then slide the line up or down until half the points are above it.
To find the middle value we do not need to list all the lines. For a trial slope, tilt the plane so that lines of that slope become flat. Two points whose order changes when the tilt passes from very steep down to the trial slope form a line steeper than the trial slope. Counting such swaps is the classic inversion count, which merge sort does quickly. A few random trial slopes then trap the middle value in a short interval.
The problem
The input is points , at least two with different . For with , the slope is ; pairs with are skipped, as in Sen (1968). Let be the number of slopes. The output is
where the median of an even number of values is the mean of the two middle ones. In the regression notation with rows, this is a fit of the simple model with and coefficient vector .
The algorithm
For a value , let and be the numbers of slopes and . COUNT returns the number of slopes in the open interval ; then $c_<(v) = $ COUNT and $c_\le(v) = N - $ COUNT. SELECT-SLOPE is the randomized slope selection of Matoušek (1991), with and .
SELECT-SLOPE(x, y, k) ▷ the k-th smallest pairwise slope- 1
lo ← −∞; hi ← +∞ - 2
below ← 0 ▷ the number of slopes ≤ lo - 3
inside ← COUNT(lo, hi) ▷ the number of slopes in (lo, hi) - 4
while inside > 4r do - 5
S ← r slopes drawn uniformly from those in (lo, hi), sorted - 6
t ← (k − below) · r / inside ▷ where the k-th slope should fall in S - 7
lo' ← S[⌊t⌋ − δ]; hi' ← S[⌊t⌋ + δ] ▷ an index outside S keeps lo or hi - 8
if c<(lo') < k ≤ c≤(lo') then return lo'; if c<(hi') < k ≤ c≤(hi') then return hi' - 9
if c≤(lo') < k ≤ c<(hi') then - 10
lo ← lo'; hi ← hi'; below ← c≤(lo'); inside ← c<(hi') − c≤(lo') - 11
▷ otherwise the sample missed the k-th slope: draw a new sample - 12
C ← the slopes in (lo, hi), listed by the merge sort of COUNT - 13
return the (k − below)-th smallest value of C COUNT(lo, hi) ▷ the number of slopes s with lo < s < hi- 14
list the points by y − lo·x, ties by y − hi·x ▷ at −∞ order by (x, y), at +∞ by (−x, y) - 15
return the number of inversions of the values y − hi·x in this list, by merge sort THEIL-SEN(x, y)- 16
N ← COUNT(−∞, +∞) ▷ the pairs with x_i ≠ x_j - 17
b ← the median of the N slopes, by SELECT-SLOPE (two calls if N is even) - 18
a ← the median of y_i − b·x_i; return (b, a)
The key fact behind COUNT: for , . So the order of the two values changes exactly when passes , and a pair whose order differs at and at is a pair with . Line L5 samples a slope in by picking a uniform random inversion; a Fenwick tree gives the number of inversions that end at each position and finds the partner of a chosen one, all in time.
Example
Take six points with one wild value:
| 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 2 | 3 | 5 | 6 | 8 | 40 |
The 15 pairwise slopes, sorted, are
The five largest are the five slopes through point 6. The median is the 8th value, . The residuals are , with median . The fit is , close to the line of the first five points. Least squares gives , pulled up by point 6.
Counting by inversions. To find , list the points by and compute :
The inversions, pairs with , are , and . So : the slopes . The count adds the four slopes equal to . For the 8th slope, Lemma 4 of the proof says that exactly when :
| is it the 8th slope? | |||
|---|---|---|---|
| 3/2 | 3 | 7 | no, too small |
| 5/3 | 7 | 8 | yes |
| 2 | 8 | 10 | no, too large |
With there are only 15 slopes, fewer than , so the loop of line L4 does not run, and line L12 lists the slopes directly. For (79 800 slopes) the test file runs the sampling rounds.
Correctness
COUNT is correct because of the sign identity above: a pair with is in opposite strict order at and at exactly when . Pairs with equal keep their order at every , so they are never counted, and pairs tied at are listed in their order at , so they are not counted either. Hence COUNT returns the number of inversions of a sequence, which merge sort computes in time.
SELECT-SLOPE keeps the invariant , so the -th slope stays in . It returns an end of the interval only after it has checked , which holds exactly when . Line L13 picks the -th slope inside the interval, which is . The random sample affects only the running time, never the answer.
Breakdown point. Replace of points with distinct . The slopes among the clean points do not move. A median of numbers of which are fixed and are free stays bounded if and only if . The bad points can make slopes as large as they like at once, by sitting far to the right on a steep parabola. So the least that breaks the estimator is the least with , and as , gives . The full proofs are below.
Proof: COUNT counts the slopes in an interval by inversions, SELECT-SLOPE returns the k-th slope, and the Theil-Sen slope breaks down at about 1 - 1/sqrt(2)full
Setting. The data are . For a pair with , the slope is . Pairs with have no slope and are skipped. is the number of slopes, and are the slopes in sorted order, with repeats. For a value , and are the numbers of slopes and .
For a finite , the key of point at is . The key at is the pair , and the key at is , both compared in lexicographic order. These are the orders of for very negative and for very large.
Part 1. Counting
Lemma 1 (sign of a key difference). Let . For finite , has the sign of . The key of is larger than the key of at , and smaller at . If , the keys of and compare in the same way at every , finite or not.
Proof. , and . At , because ; at , . If , every comparison reduces to the comparison of and .
Call a pair discordant for if its two keys are in strict opposite order at and at .
Lemma 2. For (each finite or infinite), the number of discordant pairs is the number of slopes in the open interval .
Proof. A pair with is never discordant, by Lemma 1. For , Lemma 1 says that the key of is above the key of at exactly when , and below it at exactly when . The other discordant case would need and , which is impossible. So the pair is discordant exactly when .
Lemma 3 (COUNT). Lines L14 and L15 return the number of discordant pairs, in time.
Proof. Line L14 lists the points in the order of the key at , with ties broken by the key at . Let be the keys at in that order. A pair tied at appears with its keys at in nondecreasing order, so it is not an inversion of , and it is not discordant. A pair in strict order at is an inversion of exactly when its keys at are in strict opposite order. So the inversions of are the discordant pairs. The merge sort count of counting inversions takes time.
So $N = $ COUNT, $c_<(s) = $ COUNT and $c_\le(s) = N - $ COUNT. In particular, the number of slopes below is the number of inversions of the sequence when the points are listed by (ties in listed by ).
Part 2. Selection
Lemma 4. A value equals if and only if .
Proof. If , the slopes below are among , and are . Conversely, at least slopes are , so , and fewer than are , so .
Lemma 5 (sampling). Each slope drawn at line L5 is uniform over the slopes in , and the draws are independent.
Proof. Use the sequence of Lemma 3. For each position , let be the number of earlier positions with ; a Fenwick tree over the ranks of gives all in time. List the inversions by , and for a fixed by the rank of . This list has entries, one for each slope in by Lemma 3. A uniform integer picks entry : the position is where the prefix sums of pass , and the partner is found by a find--th query in the Fenwick tree of the earlier positions. Independent uniform integers give independent uniform entries.
Invariant of the loop. At line L4, , is the number of slopes in , and . So .
Proof. At the start, and , so , and . In a round, line L8 computes and at the new ends, and returns an end only when Lemma 4 says it is . Line L10 changes the interval only when , which is the invariant for , since the number of slopes in is . Otherwise the old values stay.
At line L12 the invariant holds, so the slopes in are , and line L13 returns the -th smallest of them, which is . Line L12 lists the inversions of by the merge sort that counts them, which takes time.
One round succeeds with probability at least 7/8. Index the slopes in as in sorted order, and let be the index of . Let be the number of the draws with index , and the number with index . Then with mean , the value of line L6, and with mean . The sample is sorted and indexed from 0. The low end is at most when , and the high end is at least when . The code takes and , so , with . Chebyshev's inequality, with variance at most , gives
(If or , that end stays at or , which is safe.) So with probability at least , , and the round either returns or shrinks the interval. Matoušek (1991) shows that after a successful round the expected number of slopes left in the interval is . With and , two successful rounds bring to , below the stop value . So the expected number of rounds is , each round takes time, and the expected total time is . The correctness above does not depend on this analysis; only the time does.
Part 3. The estimator
Line L17 takes the median of the slopes: for odd , and the mean of and for even . Line L18 takes the median of the residuals as the intercept. If is replaced by , each slope grows by , so grows by , and each residual grows by , so grows by .
Part 4. The breakdown point
Assume the clean data have distinct . Replace of the points by arbitrary points. Let be the number of slopes among the clean points; these values do not change. Let be the number of slopes that involve a replaced point; , with equality when all values are distinct. The total is .
Lemma 6. The median of numbers, of them fixed and of them free, stays bounded over all values of the free numbers if and only if .
Proof. The -th smallest of the numbers can be sent to exactly when (send all free numbers up), and to exactly when ; otherwise it lies between two fixed numbers. The median uses and , and . So the median is bounded exactly when , that is , that is .
The free slopes can all be sent to together: put the -th replaced point at and . Its slope to a clean point is about divided by a positive distance, and the slope between replaced points is ; all grow without bound as . Equal values only lower . So the Theil-Sen slope can be carried to infinity by points exactly when , that is
For example for , for , and for . As , , and gives
Complexity
- COUNT takes time and space.
- SELECT-SLOPE. Each round takes time for a sample of slopes and four counts. A round succeeds with probability at least (the proof uses Chebyshev's inequality), and Matoušek (1991) shows that a successful round leaves slopes in the interval in expectation, where is the number before it. Starting from , about two successful rounds reach slopes. So the expected time is . In the worst case, a run of unlucky samples ends in line L12 with all slopes, which costs time.
- Theil-Sen runs one or two selections and one median, in expected time.
- Lower bound. Slope selection takes time in the algebraic decision tree model, so these bounds are optimal; Cole and others (1989) call their algorithm optimal in this sense.
- The direct method lists the slopes and uses quickselect: expected time and space. It is simpler and is fast enough for a few thousand points.
Properties
- Breakdown point with , in the replacement version of the breakdown point page, for data with distinct . The values for some are below; the limit is .
| 5 | 10 | 20 | 50 | 100 | 1000 | |
|---|---|---|---|---|---|---|
| 2 | 3 | 6 | 15 | 30 | 293 |
- Exact fit. If all points lie on one line, every slope equals its slope, so the fit is the line.
- Regression equivariant. Adding to each adds to and to . Scaling or by a nonzero constant scales in the same way. The test file checks the first rule exactly.
- Efficiency. Under normal errors the estimator is almost as precise as least squares. In a simulation with equally spaced and 2000 samples of standard normal noise, the variance of the least squares slope was 0.93 of the variance of the Theil-Sen slope. This is a measured value, not a theorem; Sen (1968) gives the asymptotic theory.
- Distribution free interval. The slope is the value of at which Kendall's tau between and is zero. Order statistics of the slopes give a confidence interval for the slope from the null distribution of Kendall's tau (Sen 1968), see Kendall tau distance.
Variants and improvements
- Deterministic optimal selection. Cole, Salowe, Steiger and Szemerédi (1989) select the -th slope in worst-case time with parametric search. Katz and Sharir (1993) and Brönnimann and Chazelle (1998) gave simpler deterministic algorithms, with expanders and with cuttings.
- Other randomized versions. Dillencourt, Mount and Netanyahu (1992) give a practical randomized algorithm in the same spirit.
- Repeated median. Siegel's repeated median takes, for each point, the median of its slopes to the others, and then the median of these values. Its breakdown point is 50 percent.
- Weighted versions. The weighted median of the slopes with weights is a rank-based estimator of the slope that gives more weight to pairs far apart in . It is more efficient when the values are unevenly spread.
- Hodges-Lehmann analogy. The Hodges-Lehmann estimator of location is the median of pairwise means, the same idea one dimension down. Selecting among pairwise differences is the problem of the k-th smallest pair distance.
- Trend tests. In hydrology and climate data, the slope is reported with the Mann-Kendall trend test as "Sen's slope".
When to use it
Use Theil-Sen for a straight line in two variables when a minority of the points may be wrong, when the errors may be heavy tailed, or when you do not want to choose a tuning constant. It is a good default for robust trend estimates in time series. With more than about 29 percent bad points use the repeated median or least median of squares. With many predictors there is no direct analog with the same guarantees; use a robust multiple regression such as the MM-estimator.
Pitfalls
- Tied x values. Pairs with have no slope. Skipping them, as Sen does, is standard. Do not put them in as ; that changes the median.
- The intercept. There are several conventions: the median of (used here), or (Conover). They differ in general. Say which one you use.
- Even N. With an even number of slopes, take the mean of the two middle ones, or say that you take the lower one. Libraries differ.
- Floating-point slopes. With almost equal values, the slope is huge and inexact. For exact answers on rational data, compare against and do not divide.
- Breakdown is not 50 percent. About 29 percent of points with arbitrary and can carry the slope away. Bad leverage points are enough.
- Quadratic memory. Listing all slopes needs values, which is 5 GB of doubles for . The selection method needs memory.
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/theil-sen-estimator/. The authors are listed in prov/VFQ6SW.jsonl.
import random
from fractions import Fraction
from math import isqrt
NEG_INF = "-inf"
POS_INF = "+inf"
def _key(s, x, y, i):
"""Sort key of point i for the order of z = y - s x at the slope s.
At s = -inf the order is by (x, y); at s = +inf it is by (-x, y).
These are the limits of the order of y - s x.
"""
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 _inversions(w):
"""Number of pairs a < b with w[a] > w[b], by merge sort. O(n log n)."""
def sort(lo, hi):
if hi - lo <= 1:
return w[lo:hi], 0
mid = (lo + hi) // 2
left, cl = sort(lo, mid)
right, cr = sort(mid, hi)
out, c, i = [], cl + cr, 0
for v in right:
while i < len(left) and left[i] <= v:
out.append(left[i])
i += 1
c += len(left) - i # every left item still waiting is > v
out.append(v)
out.extend(left[i:])
return out, c
return sort(0, len(w))[1]
def _sequence(lo, hi, x, y):
"""The hi-keys listed in the order of the lo-keys (ties by hi-key)."""
n = len(x)
order = sorted(range(n), key=lambda i: (_key(lo, x, y, i), _key(hi, x, y, i)))
return order, [_key(hi, x, y, i) for i in order]
def count_between(lo, hi, x, y):
"""Number of pairwise slopes s with lo < s < hi (lo, hi may be infinite).
A pair is counted exactly when the order of y - s x at lo and at hi
disagree, so this is an inversion count.
"""
order, w = _sequence(lo, hi, x, y) # @line L14
return _inversions(w) # @line L15
def count_less(s, x, y):
"""Number of slopes < s, as the inversions of y - s x in x order."""
return count_between(NEG_INF, s, x, y)
def count_at_most(s, x, y):
"""Number of slopes <= s."""
return count_between(NEG_INF, POS_INF, x, y) - count_between(s, POS_INF, x, y)
def _slope(x, y, i, j):
return Fraction(y[j] - y[i]) / (x[j] - x[i])
def _enumerate(lo, hi, x, y):
"""All slopes strictly between lo and hi, by merge sort. O(n log n + C)."""
order, w = _sequence(lo, hi, x, y)
items = list(zip(w, order))
out = []
def sort(seq):
if len(seq) <= 1:
return seq
mid = len(seq) // 2
left, right = sort(seq[:mid]), sort(seq[mid:])
merged, i = [], 0
for v in right:
while i < len(left) and left[i][0] <= v[0]:
merged.append(left[i])
i += 1
for a in left[i:]:
out.append(_slope(x, y, a[1], v[1]))
merged.append(v)
merged.extend(left[i:])
return merged
sort(items)
return out
def _sample(lo, hi, x, y, r, rng):
"""r slopes drawn uniformly, with replacement, from those in (lo, hi)."""
order, w = _sequence(lo, hi, x, y)
n = len(w)
vals = sorted(set(w))
rank = {v: k + 1 for k, v in enumerate(vals)}
m = len(vals)
tree = [0] * (m + 1)
def add(i):
while i <= m:
tree[i] += 1
i += i & -i
def prefix(i):
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
def kth(k): # smallest rank with prefix(rank) >= k
pos, step = 0, 1 << m.bit_length()
while step:
if pos + step <= m and tree[pos + step] < k:
pos += step
k -= tree[pos]
step >>= 1
return pos + 1
inv = []
for b in range(n): # inv[b] = #{a < b : w[a] > w[b]}
inv.append(b - prefix(rank[w[b]]))
add(rank[w[b]])
total = sum(inv)
picks = sorted(rng.randrange(total) for _ in range(r))
tree = [0] * (m + 1)
bucket = [[] for _ in range(m + 1)]
out, acc, p = [], 0, 0
for b in range(n):
rb = rank[w[b]]
while p < len(picks) and picks[p] < acc + inv[b]:
t = picks[p] - acc # the t-th (0-based) earlier item with a larger key
below = prefix(rb)
rk = kth(below + t + 1)
a = bucket[rk][below + t - prefix(rk - 1)]
out.append(_slope(x, y, a, order[b]))
p += 1
acc += inv[b]
add(rb)
bucket[rb].append(order[b])
return out
def select_slope(x, y, k, rng=None):
"""The k-th smallest (1-based) pairwise slope, in expected O(n log n) time."""
rng = rng or random.Random(0)
n = len(x)
lo, hi = NEG_INF, POS_INF # @line L1
below = 0 # number of slopes <= lo # @line L2
inside = count_between(lo, hi, x, y) # @line L3
r = max(n, 32)
while inside > 4 * r: # @line L4
sample = sorted(_sample(lo, hi, x, y, r, rng)) # @line L5
t = (k - below) * r / inside # @line L6
delta = 2 * isqrt(r) + 2 # at least 2 sqrt(r)
a, b = int(t) - delta, int(t) + delta
new_lo = sample[a] if a >= 0 else lo # @line L7
new_hi = sample[b] if b < r else hi
nb = below if new_lo == lo else count_at_most(new_lo, x, y) # @line L8
if new_lo != lo and count_less(new_lo, x, y) < k <= nb:
return new_lo
nlt = (below + inside) if new_hi == hi else count_less(new_hi, x, y)
if new_hi != hi and nlt < k <= count_at_most(new_hi, x, y):
return new_hi
if nb < k <= nlt: # @line L9
lo, hi, below, inside = new_lo, new_hi, nb, nlt - nb # @line L10
# else the sample missed; draw a new one # @line L11
cand = sorted(_enumerate(lo, hi, x, y)) # @line L12
return cand[k - below - 1] # @line L13
def theil_sen(x, y, rng=None):
"""Theil-Sen slope and intercept: the median of the pairwise slopes,
then the median of y - b x. Pairs with equal x are skipped."""
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]
total = count_between(NEG_INF, POS_INF, x, y) # pairs with distinct x # @line L16
if total == 0:
raise ValueError("need two points with different x")
rng = rng or random.Random(0)
if total % 2 == 1: # @line L17
b = select_slope(x, y, (total + 1) // 2, rng)
else:
b = (select_slope(x, y, total // 2, rng) + select_slope(x, y, total // 2 + 1, rng)) / 2
res = sorted(yi - b * xi for xi, yi in zip(x, y)) # @line L18
m = len(res)
a = (res[(m - 1) // 2] + res[m // 2]) / 2
return b, a
def naive_slopes(x, y):
"""All pairwise slopes with x_i != x_j, sorted. O(n^2 log n)."""
n = len(x)
return sorted(Fraction(y[j] - y[i]) / (x[j] - x[i])
for i in range(n) for j in range(i + 1, n) if x[i] != x[j])
def breakdown_count(n):
"""Least number m of replaced points that can carry the slope to infinity,
for clean data with distinct x: the least m with C(n - m, 2) <= C(n, 2)/2."""
total = n * (n - 1) // 2
m = 0
while 2 * ((n - m) * (n - m - 1) // 2) > total:
m += 1
return m
test_theil_sen_estimator.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/theil-sen-estimator/. The authors are listed in prov/VFQ6SW.jsonl.
import random
from fractions import Fraction
from math import comb
from statistics import median
import pytest
from theil_sen_estimator import (
NEG_INF, POS_INF, breakdown_count, count_at_most, count_between,
count_less, naive_slopes, select_slope, theil_sen,
)
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]
slopes = naive_slopes(x, y)
assert len(slopes) == 15
b, a = theil_sen(x, y)
assert b == Fraction(5, 3)
assert a == Fraction(-1, 6)
# The count of slopes below 3/2 is the inversion count of y - 1.5 x.
assert count_less(Fraction(3, 2), F(x), F(y)) == 3
assert count_at_most(Fraction(3, 2), F(x), F(y)) == 7
def test_counts_against_all_slopes() -> None:
rng = random.Random(11)
for _ in range(300):
n = rng.randint(1, 12)
x = F(rng.randint(0, 5) for _ in range(n))
y = F(rng.randint(-5, 5) for _ in range(n))
slopes = naive_slopes(x, y)
assert count_between(NEG_INF, POS_INF, x, y) == len(slopes)
probes = [Fraction(rng.randint(-12, 12), rng.randint(1, 4))] + slopes[:2]
for s in probes:
assert count_less(s, x, y) == sum(1 for v in slopes if v < s)
assert count_at_most(s, x, y) == sum(1 for v in slopes if v <= s)
lo = s - Fraction(rng.randint(1, 30), 3)
assert count_between(lo, s, x, y) == sum(1 for v in slopes if lo < v < s)
def test_selection_against_sorting_small() -> None:
rng = random.Random(12)
for _ in range(150):
n = rng.randint(2, 12)
x = F(rng.randint(0, 5) for _ in range(n))
y = F(rng.randint(-5, 5) for _ in range(n))
slopes = naive_slopes(x, y)
for k in range(1, len(slopes) + 1):
assert select_slope(x, y, k, random.Random(k)) == slopes[k - 1]
def test_selection_against_sorting_large() -> None:
# Large enough that the sampling rounds run before the final enumeration.
rng = random.Random(13)
n = 400
x = [rng.randint(0, 10**6) for _ in range(n)]
y = [rng.randint(0, 10**6) for _ in range(n)]
slopes = naive_slopes(x, y)
xs, ys = F(x), F(y)
for k in (1, 2, len(slopes) // 3, len(slopes) // 2, len(slopes) - 1, len(slopes)):
assert select_slope(xs, ys, k, random.Random(k)) == slopes[k - 1]
def test_theil_sen_against_naive_median() -> None:
rng = random.Random(14)
for _ in range(200):
n = rng.randint(2, 15)
x = [rng.randint(0, 6) for _ in range(n)]
y = [rng.randint(-9, 9) for _ in range(n)]
slopes = naive_slopes(x, y)
if not slopes:
with pytest.raises(ValueError):
theil_sen(x, y)
continue
b, a = theil_sen(x, y)
assert b == median(slopes)
assert a == median([Fraction(yi) - b * xi for xi, yi in zip(x, y)])
def test_exact_line_and_equivariance() -> None:
x = [0, 1, 3, 4, 7, 9]
y = [Fraction(5) - Fraction(2, 3) * v for v in x]
assert theil_sen(x, y) == (Fraction(-2, 3), 5)
rng = random.Random(15)
x = [rng.randint(0, 50) for _ in range(30)]
y = [rng.randint(0, 50) for _ in range(30)]
b, a = theil_sen(x, y)
# Adding the line 3 + 2x to y adds 2 to the slope and 3 to the intercept.
b2, a2 = theil_sen(x, [yi + 3 + 2 * xi for xi, yi in zip(x, y)])
assert (b2, a2) == (b + 2, a + 3)
def test_breakdown_count() -> None:
assert [breakdown_count(n) for n in (5, 10, 100, 1000)] == [2, 3, 30, 293]
for n in range(3, 200):
m = breakdown_count(n)
assert 2 * comb(n - m, 2) <= comb(n, 2) < 2 * comb(n - m + 1, 2)
def test_breakdown_by_adversary() -> None:
rng = random.Random(16)
n = 10
m_star = breakdown_count(n) # 3
xc = list(range(n))
yc = [rng.randint(0, 5) for _ in range(n)]
clean = naive_slopes(xc, yc)
# m* - 1 bad points of any kind leave the slope inside the clean range.
for _ in range(200):
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)
b, _ = theil_sen(x, y)
assert clean[0] <= b <= clean[-1]
# m* bad points far to the right on a steep parabola carry it away.
x, y = list(xc), list(yc)
last = None
for t in (10, 10**3, 10**5):
for j in range(m_star):
x[j] = n + j
y[j] = (j + 1) ** 2 * t
b, _ = theil_sen(x, y)
assert last is None or b > 50 * last
last = b
History
Theil (1950) proposed the median of the pairwise slopes as a rank-invariant estimate, in a series of three papers. Sen (1968) treated tied values, linked the estimator to Kendall's tau, and derived its distribution. Rousseeuw and Leroy (1987) put it in the framework of breakdown and computed its breakdown point of 29.3 percent. The computational question, selecting a slope without listing all of them, became a central problem of computational geometry in the 1980s: Cole, Salowe, Steiger and Szemerédi (1989) solved it in optimal time, and Matoušek (1991) gave a short randomized algorithm based on inversion counting.
References
- Henri Theil, A rank-invariant method of linear and polynomial regression analysis, I, II and III, Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen 53, 1950, pp. 386 to 392, 521 to 525 and 1397 to 1412, Part I (the slope as the median of the pairwise slopes)
- Pranab Kumar Sen, Estimates of the regression coefficient based on Kendall's tau, Journal of the American Statistical Association 63(324), 1968, pp. 1379 to 1389 (pairs with tied x, the confidence interval from Kendall's tau, and the asymptotic distribution)
- Richard Cole, Jeffrey S. Salowe, William L. Steiger and Endre Szemerédi, Optimal slope selection, SIAM Journal on Computing 18(4), 1989, pp. 792 to 810, The whole paper (a deterministic O(n log n) algorithm for the k-th smallest pairwise slope)
- Jiří Matoušek, Randomized optimal algorithm for slope selection, Information Processing Letters 39(4), 1991, pp. 183 to 187 (selection by random sampling and inversion counting, O(n log n) expected time)
- Michael B. Dillencourt, David M. Mount and Nathan S. Netanyahu, A randomized algorithm for slope selection, International Journal of Computational Geometry and Applications 2(1), 1992, pp. 1 to 27, The whole paper (a practical randomized slope selection)
- Peter J. Rousseeuw and Annick M. Leroy, Robust Regression and Outlier Detection, Wiley, 1987, Chapter 2 (simple regression, with the Theil-Sen and repeated median slopes and their breakdown points)
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 VFQ6SW Edit this page History Report an error Markdown