Foundations to Frontier
Tests
D. Classical Machine Learning › D1 Linear Models for Regression

Theil–Sen Estimator

The Theil–Sen estimator fits a line by taking the median of the slopes between all pairs of points, then the median of the implied intercepts. It needs no tuning, has a breakdown point of about 29% (bad x and bad y alike), keeps about 95% of least-squares efficiency on Gaussian data, and beats least squares under heavy-tailed noise. Siegel's repeated median raises the breakdown point to 50%. This page covers the estimator, its link to Kendall's tau, Sen's confidence interval, breakdown and efficiency, fast algorithms, and the multivariate extension. In the exercises you implement Theil–Sen, the repeated median and Sen's interval and compare their breakdown with least squares; then you estimate a satellite clock's drift rate under Gaussian, Student-t, Cauchy and glitchy noise.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Let every pair vote

Take any two points and they suggest a slope. With 25 points there are 300 pairs, so 300 suggestions. Most pairs of good points suggest roughly the true slope; pairs involving a bad point suggest something wild, in random directions. The Theil–Sen estimator picks the middle suggestion (the median), so the wild ones cannot drag it.

Theil–Sen: let every pair vote on the slope
pairwise slopes (−1.5 to 1.5)
slope: true 0.60 · Theil–Sen 0.63 · OLS 0.47 · 378 pairwise slopes · outlier share 14%
Orange line and bar: the Theil–Sen fit (median slope); grey: least squares; green tick: the true slope. Pairs of two good points cluster around 0.6; pairs involving an outlier scatter. Theil–Sen breaks down once outliers touch about 29% of points, because then more than half of all pairs involve an outlier.
Why engineers care

Trend estimation in noisy, glitchy time series is everywhere: clock drift, sensor degradation, orbit decay, and climate trends. Theil–Sen gives a robust trend with no thresholds to tune and an honest confidence interval, which is why it is the standard trend estimator (as “Sen’s slope”) in hydrology and climate science.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The Theil–Sen slope is…
  2. 2. Does Theil–Sen need a threshold to be tuned?
  3. 3. In the demo, leverage outliers…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

Points: (0, 1), (1, 3), (2, 5), (3, 7), (4, 30). The last one is an outlier; the true line is y = 1 + 2x.

The 10 pairwise slopes:

  • the six pairs among the first four points all give 2;
  • the pairs with (4, 30) give 29/4 = 7.25, 27/3 = 9, 25/2 = 12.5 and 23/1 = 23.

Sorted: 2, 2, 2, 2, 2, 2, 7.25, 9, 12.5, 23. The median (average of the 5th and 6th) is 2.

Intercept: the median of yᵢ − 2xᵢ = 1, 1, 1, 1, 22 is 1. The fit is exactly y = 1 + 2x. Least squares gives slope 6.2.

The steps in plain English:

  1. For every pair of points with different x, compute the slope between them.
  2. The slope estimate is the median of these slopes.
  3. The intercept is the median of yᵢ − slope × xᵢ.
  4. Optional: read a confidence interval off the sorted slopes (Sen’s method).
📝 Quick check (Level 1)
0/3 answered
  1. 1. How many pairwise slopes for 10 points?
  2. 2. The intercept is…
  3. 3. Pairs with equal x are…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

The estimator

Slope: m̂ = median of Sᵢⱼ = (yⱼ − yᵢ)/(xⱼ − xᵢ) over all pairs i below j with xᵢ ≠ xⱼ.

Intercept: b̂ = median of (yᵢ − m̂xᵢ).

Link to Kendall’s tau. m̂ is the value of m that makes Kendall’s rank correlation between x and the residuals y − mx equal to zero. This gives a distribution-free test and confidence interval.

Sen’s confidence interval. With N pairwise slopes sorted, and C = z·√(n(n − 1)(2n + 5)/18) (the standard deviation of Kendall’s S statistic), the interval runs from the slope ranked (N − C)/2 to the slope ranked (N + C)/2. It assumes nothing about the noise distribution.

Siegel’s repeated median: m̂ = medianᵢ medianⱼ Sᵢⱼ. It takes the median slope from each point, then the median of those, and raises the breakdown point to 50%.

from scipy.stats import theilslopes, siegelslopes
slope, intercept, lo, hi = theilslopes(y, x, alpha=0.95)     # slope, intercept and Sen's 95% CI
slope_rm, intercept_rm = siegelslopes(y, x)
from sklearn.linear_model import TheilSenRegressor            # multivariate (spatial-median) version
model = TheilSenRegressor(random_state=0).fit(X, y)

Use it when you fit a single trend line, the noise may be heavy-tailed or glitchy, and you want no tuning. Prefer RANSAC with more than about 30% outliers or for multi-parameter models; prefer least squares on clean Gaussian data when every bit of efficiency matters.

🐍 Exercise 1: Theil–Sen and the repeated median
Implement pairwise slopes, the Theil–Sen line, Siegel's repeated median and Sen's confidence interval; show that with 20% outliers in x and y both robust fits recover the true slope while the OLS slope changes sign, that at 40% Theil–Sen breaks but the repeated median holds, and that Sen's interval covers the true slope on clean data.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Theil–Sen's slope makes which statistic zero?
  2. 2. Siegel's repeated median has breakdown point…
  3. 3. scipy's theilslopes returns…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Breakdown, efficiency and cost

Breakdown point. Suppose a fraction ε of points are bad. A pair is clean only if both points are good, which happens for a share (1 − ε)² of pairs. The median stays bounded while clean pairs are the majority: (1 − ε)² ≥ ½. This gives ε* = 1 − 1/√2 ≈ 29.3%.

The repeated median takes a median per point first, so it survives until half the points are bad.

Efficiency. At Gaussian noise the asymptotic relative efficiency of Theil–Sen versus least squares is about 0.91–0.95, depending on the design (3/π ≈ 0.955 for evenly spaced x). Under heavy tails it is far more efficient. Exercise 2 measures 0.94 for Gaussian, 1.66 for Student-t(3), and thousands for Cauchy, where least squares has no finite variance.

Computation:

  • naive: O(n²) slopes plus a median, so O(n²) time and memory;
  • exact O(n log n) algorithms exist (Cole, Salowe, Steiger and Szemerédi, 1989), and a simple randomised selection algorithm runs in expected O(n log n) (Matoušek, 1991);
  • for large n, a random subsample of pairs is enough in practice.

Multivariate versions. There is no unique pairwise slope with p predictors. scikit-learn fits exact solutions on random subsets of p + 1 points and takes their spatial median (the point that minimises the sum of Euclidean distances). The breakdown point then falls with p.

Interview questions.

  • Why 29% and not 50%? Each pairwise slope involves two points, so contamination of pairs is 1 − (1 − ε)².
  • Theil–Sen versus Huber? Theil–Sen resists bad x values (leverage) and needs no scale or δ. Huber is cheaper, multivariate and more efficient on clean data, but breaks with one leverage point.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Breakdown point of Theil–Sen?
  2. 2. Naive Theil–Sen costs…
  3. 3. scikit-learn's multivariate Theil–Sen aggregates subset fits by…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Measuring a clock’s drift through glitches

History.

  • Theil (1950) proposed the median of pairwise slopes in a series of papers on rank-invariant regression.
  • Sen (1968) derived its distribution-free confidence interval from Kendall’s tau.
  • Siegel (1982) introduced the repeated median, the first regression estimator with a 50% breakdown point.
  • Sen’s slope with the Mann–Kendall trend test became the standard tool for environmental trend analysis.

Exercise 1. 60 points on y = 3 − 0.7x (σ = 0.3).

  • With 20% of points replaced by random points (x in 0–30, y in 5–25), Theil–Sen gives a slope of −0.660 and the repeated median −0.670. The OLS slope is +0.491: the sign flips.
  • At 40% contamination, Theil–Sen breaks (+0.267). The repeated median still gives −0.584.
  • On clean data, Sen’s 95% interval [−0.725, −0.673] covers −0.7.

Exercise 2: satellite clock drift. Setup: 40 hourly offsets, true drift 0.5 ns/h, 400 simulated logs per noise type. The table shows the RMSE of the estimated drift rate in ns/h, with efficiency relative to OLS in brackets.

Noise OLS Theil–Sen Repeated median
Gaussian 0.0132 0.0136 (0.94) 0.0157 (0.71)
Student-t, 3 d.o.f. 0.0235 0.0182 (1.66) 0.0193 (1.48)
Cauchy 2.19 0.0247 0.0231
10% glitches (+20 ns) 0.0804 0.0175 (21) 0.0185 (19)
  • On Gaussian noise, Theil–Sen loses only 6% of OLS efficiency (theory: 3/π ≈ 0.955). The repeated median pays more for its higher breakdown.
  • Under heavy tails and glitches, the robust estimators are far better: 1.7 times as efficient with t(3) noise and 21 times with glitches.
  • Under Cauchy noise, OLS is useless (its error has no finite variance). The medians are barely affected.
🐍 Exercise 2 (research): clock drift under heavy-tailed noise
Simulate 40 hourly clock offsets drifting at 0.5 ns/h with Gaussian, Student-t(3), Cauchy or glitchy noise; estimate the drift by OLS, Theil–Sen and the repeated median; report the RMSE and efficiency relative to OLS over 400 logs.

Theil–Sen in AI, robotics and aerospace

  • Clock and sensor drift: robust drift rates for oscillators, gyroscope bias and battery fade.
  • Orbit decay and degradation trends: trends in telemetry with occasional bad frames.
  • Climate and hydrology: Sen’s slope plus the Mann–Kendall test for long-term trends.
  • Robust feature engineering: per-window trend features that tolerate spikes.

References

  1. H. Theil (1950). “A rank-invariant method of linear and polynomial regression analysis.” Proceedings of the Royal Netherlands Academy of Sciences 53.
  2. P. K. Sen (1968). “Estimates of the regression coefficient based on Kendall’s tau.” JASA 63(324).
  3. A. F. Siegel (1982). “Robust regression using repeated medians.” Biometrika 69(1).
  4. J. Matoušek (1991). “Randomized optimal algorithm for slope selection.” Information Processing Letters 39(4).
  5. X. Dang, H. Peng, X. Wang, H. Zhang (2008). “Theil–Sen estimators in a multiple linear regression model.” Technical report, University of Mississippi.