Algorithm Search⌘K

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
Properties
randomizedexact in exact arithmeticnot in placeofflinerandomizedregression equivariant
Origin
Andrew F. Siegel, Jiří Matoušek, David M. Mount, Nathan S. Netanyahu, Peter J. Rousseeuw, 1982

Repeated median regression fits a line y=a+bxy = a + b x in two steps of medians. For each data point, take the median of the slopes from it to all the other points. The slope bb is the median of these nn 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 O(n2)O(n^2) time. This page gives a simple randomized selection in O(nlog⁡2n)O(n \log^2 n) 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 nn points (xi,yi)(x_i, y_i), at least two with different xx. For xi≠xjx_i \ne x_j, sij=(yj−yi)/(xj−xi)s_{ij} = (y_j - y_i)/(x_j - x_i). Point ii has did_i slopes, one for each jj with xj≠xix_j \ne x_i. Siegel's estimator is

b=med⁡i med⁡j:xj≠xisij,a=med⁡i(yi−bxi).b = \operatorname{med}_i \ \operatorname{med}_{j : x_j \ne x_i} s_{ij}, \qquad a = \operatorname{med}_i (y_i - b x_i).

On this page each median of the slope is an order statistic, so that bb is always one of the slopes: the inner median is the high median mim_i, the (⌊di/2⌋+1)(\lfloor d_i/2 \rfloor + 1)-th smallest of the slopes of ii, and the outer median is the low median, the ⌈n′/2⌉\lceil n'/2 \rceil-th smallest of the mim_i over the n′n' points with di>0d_i > 0. The intercept aa is the usual median, with the mean of the two middle values for even nn. Siegel also defines a repeated median intercept; see the variants.

The algorithm

For a value vv and a point jj, let ℓj(v)\ell_j(v) and ej(v)e_j(v) be the numbers of slopes of jj that are <v< v and ≤v\le v. Then mj<vm_j < v exactly when ℓj(v)≥kj\ell_j(v) \ge k_j, and mj≤vm_j \le v exactly when ej(v)≥kje_j(v) \ge k_j. So one pass of per-point inversion counting tells, for every point at once, on which side of vv its median lies, without computing the median. The algorithm is randomized quickselect over the implicit list of point medians.

  1. REPEATED-MEDIAN(x, y)
  2. 1d_j ← the number of slopes of j, for all j ▷ per-point inversion counts at −∞, +∞
  3. 2k_j ← ⌊d_j/2⌋ + 1; K ← ⌈n'/2⌉ ▷ n' = the number of points with d_j > 0
  4. 3lo ← −∞; hi ← +∞
  5. 4A ← the points with d_j > 0 ▷ the points with lo < m_j < hi
  6. 5loop
  7. 6pick i uniformly from A; v ← m_i, the k_i-th smallest slope of point i
  8. 7for all j: ℓ_j ← ℓ_j(v), e_j ← e_j(v) ▷ one merge sort for each count
  9. 8cl ← #{j : ℓ_j ≥ k_j}; ce ← #{j : e_j ≥ k_j} ▷ the medians < v and ≤ v
  10. 9if cl < K ≤ ce then b ← v and leave the loop
  11. 10if K ≤ cl then hi ← v else lo ← v
  12. 11A ← the points j of A with lo < m_j < hi ▷ from the counts saved at lo and hi
  13. 12a ← the median of y_j − b·x_j
  14. 13return (b, a)

Per-point counts. As on the Theil-Sen page, list the points by y−lo⋅xy - lo \cdot x and count the inversions of the values y−hi⋅xy - hi \cdot x; the inversions are the pairs with lo<sij<hilo < s_{ij} < hi. 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 O(nlog⁡n)O(n \log n) time. Then ℓj(v)\ell_j(v) is the count of jj for (−∞,v)(-\infty, v), and ej(v)=dje_j(v) = d_j minus the count for (v,+∞)(v, +\infty).

Example

Take the data of the Theil-Sen page, with one wild value:

jj 1 2 3 4 5 6
xjx_j 1 2 3 4 5 6
yjy_j 2 3 5 6 8 40
slopes of jj, 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
mjm_j (3rd of 5) 3/2 5/3 3/2 3/2 5/3 35/3

Each point has dj=5d_j = 5 slopes and kj=3k_j = 3. The wild point 6 has a wild median, but it is one vote of six. With K=3K = 3, the sorted medians 3/2,3/2,3/2,5/3,5/3,35/33/2, 3/2, 3/2, 5/3, 5/3, 35/3 give b=3/2b = 3/2. The residuals yj−32xjy_j - \tfrac32 x_j are 12,0,12,0,12,31\tfrac12, 0, \tfrac12, 0, \tfrac12, 31, so a=12a = \tfrac12. The fit is y=12+32xy = \tfrac12 + \tfrac32 x. Theil-Sen gives y=−16+53xy = -\tfrac16 + \tfrac53 x, and least squares y=−9.93+5.886 xy = -9.93 + 5.886\,x.

A run of the selection. Suppose line L6 picks point 2, so v=5/3v = 5/3. The medians below 5/35/3 are those of points 1, 3, 4, so cl=3cl = 3; with points 2 and 5, ce=5ce = 5. Since K=3≤clK = 3 \le cl, line L10 sets hi=5/3hi = 5/3, and AA becomes {1,3,4}\{1, 3, 4\}. Next, line L6 picks point 4, so v=3/2v = 3/2, with cl=0cl = 0 and ce=3ce = 3. Now 0<3≤30 < 3 \le 3, and b=3/2b = 3/2.

Correctness

The per-point counts are right because a pair {i,j}\{i, j\} 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 #{mj≤lo}<K≤#{mj<hi}\#\{m_j \le lo\} < K \le \#\{m_j < hi\}, so the answer bb is always the median of some point of AA, and vv is returned only when #{mj<v}<K≤#{mj≤v}\#\{m_j < v\} < K \le \#\{m_j \le v\}, which holds exactly when v=bv = b. Each round that does not return removes at least the pivot point from AA, so the loop ends.

Breakdown point. For clean data with distinct xx, the breakdown point in the replacement sense is εn∗=⌊n/2⌋/n\varepsilon^*_n = \lfloor n/2 \rfloor / n. With m=⌊n/2⌋m = \lfloor n/2 \rfloor 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 bb 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 (x1,y1),…,(xn,yn)(x_1, y_1), \ldots, (x_n, y_n). For xi≠xjx_i \ne x_j, sij=sji=(yj−yi)/(xj−xi)s_{ij} = s_{ji} = (y_j - y_i)/(x_j - x_i). Point ii has did_i slopes, one for each jj with xj≠xix_j \ne x_i. For di>0d_i > 0, its median is mim_i, the kik_i-th smallest of its slopes with ki=⌊di/2⌋+1k_i = \lfloor d_i/2 \rfloor + 1 (the high median). Let n′n' be the number of points with di>0d_i > 0 and K=⌈n′/2⌉K = \lceil n'/2 \rceil. The repeated median slope bb is the KK-th smallest of the n′n' values mim_i (the low median). For a value vv and a point jj, ℓj(v)\ell_j(v) and ej(v)e_j(v) are the numbers of slopes of jj that are <v< v and ≤v\le v.

Part 1. The per-point counts

The keys of the points at a slope ss are yi−sxiy_i - s x_i, with the limit orders (xi,yi)(x_i, y_i) at −∞-\infty and (−xi,yi)(-x_i, y_i) at +∞+\infty, as on the Theil-Sen page.

Lemma 1. For lo<hilo < hi, list the points by the key at lolo, ties by the key at hihi, and let ww be the keys at hihi in this order. The pair {i,j}\{i, j\} is an inversion of ww if and only if xi≠xjx_i \ne x_j and lo<sij<hilo < s_{ij} < hi.

Proof. For xi<xjx_i < x_j, (yj−sxj)−(yi−sxi)=(xj−xi)(sij−s)(y_j - s x_j) - (y_i - s x_i) = (x_j - x_i)(s_{ij} - s). So the key of jj is above the key of ii at lolo exactly when sij>los_{ij} > lo (at −∞-\infty, always), and below it at hihi exactly when sij<his_{ij} < hi (at +∞+\infty, always). The opposite pattern would need sij<lo<hi<sijs_{ij} < lo < hi < s_{ij}. Pairs with xi=xjx_i = x_j compare by yy at every ss, so they keep their order. Pairs tied at lolo are listed in their order at hihi. So the inversions are the pairs in opposite strict order at lolo and at hihi, which are the pairs with lo<sij<hilo < s_{ij} < hi. □\square

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 (a,b)(a, b), aa before bb and wa>wbw_a > w_b, in exactly one merge: the one where aa is in the left half and bb in the right half. In that merge, when the right item bb is output, the left items not yet output are exactly the left items >wb> w_b, and bb gets their number. When a left item aa is output, the right items already output are exactly the right items <wa< w_a, and aa gets their number. So each inversion adds 1 to both its points. □\square

So line L7 computes $\ell_j(v) = $ count(−∞,v)j(-\infty, v)_j and $e_j(v) = d_j - $ count(v,+∞)j(v, +\infty)_j for all jj in O(nlog⁡n)O(n \log n) time, and line L1 computes $d_j = $ count(−∞,+∞)j(-\infty, +\infty)_j. Then

mj<v  ⟺  ℓj(v)≥kj,mj≤v  ⟺  ej(v)≥kj,m_j < v \iff \ell_j(v) \ge k_j, \qquad m_j \le v \iff e_j(v) \ge k_j,

because the kjk_j-th smallest slope is below vv exactly when at least kjk_j slopes are.

Part 2. The selection

Lemma 3. A value vv is the KK-th smallest of the mjm_j if and only if #{j:mj<v}<K≤#{j:mj≤v}\#\{j : m_j < v\} < K \le \#\{j : m_j \le v\}.

Proof. As for any multiset: the KK-th smallest is ≤v\le v exactly when at least KK values are ≤v\le v, and it is not <v< v exactly when fewer than KK values are <v< v. □\square

Invariant. At line L5, with lolo and hihi the last values set at line L10 (first −∞-\infty and +∞+\infty), the set AA is {j:lo<mj<hi}\{j : lo < m_j < hi\}, and #{j:mj≤lo}<K≤#{j:mj<hi}\#\{j : m_j \le lo\} < K \le \#\{j : m_j < hi\}. So b=mjb = m_j for some j∈Aj \in A.

Proof. At the start every mjm_j is finite, so AA is all kept points, and 0<K≤n′0 < K \le n'. In a round, line L9 returns vv if Lemma 3 says it is bb. Otherwise either K≤cl=#{mj<v}K \le cl = \#\{m_j < v\}, and line L10 sets hi←vhi \leftarrow v, or ce=#{mj≤v}<Kce = \#\{m_j \le v\} < K, and it sets lo←vlo \leftarrow v. In both cases the inequality holds for the new interval. Line L11 keeps the jj with ej(lo)<kje_j(lo) < k_j (mj>lom_j > lo) and ℓj(hi)≥kj\ell_j(hi) \ge k_j (mj<him_j < hi), using the counts saved at the last change of each end. The values mjm_j in (lo,hi)(lo, hi) number #{mj<hi}−#{mj≤lo}≥1\#\{m_j < hi\} - \#\{m_j \le lo\} \ge 1, and bb is one of them. □\square

Termination. The pivot v=miv = m_i comes from a point i∈Ai \in A. If the round does not return, the new interval excludes vv, so ii leaves AA. So ∣A∣|A| drops by at least one in every round, and the loop ends after at most n′n' rounds with the answer, because AA is never empty. The value returned is bb by Lemma 3.

Expected number of rounds. The pivot is the median of a uniformly random point of AA. This is randomized quickselect over the multiset {mj:j∈A}\{m_j : j \in A\}: with probability at least 1/21/2 the pivot has rank between ∣A∣/4|A|/4 and 3∣A∣/43|A|/4 in it, and then at least a quarter of AA leaves. So the expected number of rounds is O(log⁡n)O(\log n). Each round sorts the slopes of one point and runs three merge sorts, O(nlog⁡n)O(n \log n) time. The expected total is O(nlog⁡2n)O(n \log^2 n), and the worst case is O(n2log⁡n)O(n^2 \log n).

Part 3. The breakdown point

Assume the clean data have distinct xx, so di=n−1d_i = n - 1 for all ii. Replace mm points by arbitrary points.

Lemma 4. Among DD numbers, FF of them free and the rest fixed, the kk-th smallest can be sent to +∞+\infty exactly when F≥D−k+1F \ge D - k + 1, to −∞-\infty exactly when F≥kF \ge k, and otherwise it lies between the smallest and the largest fixed number.

Proof. To send the kk-th smallest up, at least D−k+1D - k + 1 values must be large; the fixed ones are bounded. If F≥D−k+1F \ge D - k + 1, send all free values up. The other side is the same. If neither holds, at least one fixed value is ≤\le and one is ≥\ge the kk-th smallest. □\square

Upper bound, m=⌊n/2⌋m = \lfloor n/2 \rfloor points suffice. Put the jj-th bad point at x=max⁡ixi+jx = \max_i x_i + j and y=j2ty = j^2 t with t→∞t \to \infty. All slopes that involve a bad point then tend to +∞+\infty together. A clean point has D=n−1D = n - 1 slopes, F=mF = m of them free, and k=⌊(n−1)/2⌋+1k = \lfloor (n-1)/2 \rfloor + 1, so D−k+1=⌈(n−1)/2⌉=⌊n/2⌋=mD - k + 1 = \lceil (n-1)/2 \rceil = \lfloor n/2 \rfloor = m, and its median goes to +∞+\infty. So do the medians of the bad points, whose slopes are all free. So all nn medians, and bb, go to +∞+\infty.

Lower bound, m≤⌊n/2⌋−1m \le \lfloor n/2 \rfloor - 1 points do not suffice. Let [smin⁡,smax⁡][s_{\min}, s_{\max}] be the range of the slopes among the clean points; it does not depend on the bad points. Since n−m≥2n - m \ge 2 clean points have distinct xx, every point has a slope, so n′=nn' = n.

Take a clean point, and let cc bad points share its xx. It has D=n−1−cD = n - 1 - c slopes, F=m−cF = m - c of them free, and k=⌊D/2⌋+1k = \lfloor D/2 \rfloor + 1, so D−k+1=⌈D/2⌉≤kD - k + 1 = \lceil D/2 \rceil \le k. Now ⌈(n−1)/2⌉≤n/2\lceil (n-1)/2 \rceil \le n/2, so

⌈D2⌉≥n−1−c2≥⌈n−12⌉−12−c2>⌈n−12⌉−1−c≥m−c=F,\Big\lceil \frac D2 \Big\rceil \ge \frac{n - 1 - c}{2} \ge \Big\lceil \frac{n-1}2 \Big\rceil - \frac12 - \frac c2 > \Big\lceil \frac{n-1}2 \Big\rceil - 1 - c \ge m - c = F,

using m≤⌊n/2⌋−1=⌈(n−1)/2⌉−1m \le \lfloor n/2 \rfloor - 1 = \lceil (n-1)/2 \rceil - 1. By Lemma 4, the median of the clean point lies between two of its clean slopes, so in [smin⁡,smax⁡][s_{\min}, s_{\max}].

So at least n−mn - m of the nn point medians are in [smin⁡,smax⁡][s_{\min}, s_{\max}], and at most mm are free. The outer median has K=⌈n/2⌉K = \lceil n/2 \rceil and n−K+1=⌊n/2⌋+1n - K + 1 = \lfloor n/2 \rfloor + 1, both larger than mm. By Lemma 4 again, b∈[smin⁡,smax⁡]b \in [s_{\min}, s_{\max}] whatever the bad points are.

So the breakdown point in the replacement sense is

εn∗=⌊n/2⌋n⟶12.□\varepsilon^*_n = \frac{\lfloor n/2 \rfloor}{n} \longrightarrow \frac12. \qquad \square

Complexity

  • One round sorts the slopes of one point and runs three merge sorts: O(nlog⁡n)O(n \log n) time and O(n)O(n) space.
  • Number of rounds. The pivot is the median of a random active point, so this is quickselect on the n′n' medians: O(log⁡n)O(\log n) rounds in expectation, at most n′n' in the worst case.
  • Total. O(nlog⁡2n)O(n \log^2 n) expected time and O(n)O(n) space. The worst case is O(n2log⁡n)O(n^2 \log n), and the answer is always exact.
  • Faster algorithms. Matoušek, Mount and Netanyahu (1998) give a randomized algorithm in O(nlog⁡n)O(n \log n) 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 O(nlog⁡2n)O(n \log^2 n) time.
  • The direct method computes each point's median by quickselect: O(n2)O(n^2) time and O(n)O(n) space. For a few thousand points this is fast enough.

Properties

  • Breakdown point ⌊n/2⌋/n\lfloor n/2 \rfloor / n, the most a regression equivariant estimator can have, up to rounding. The values are 2/52/5, 5/105/10, 50/10050/100, 500/1000500/1000 for n=5,10,100,1000n = 5, 10, 100, 1000; compare 2/52/5, 3/103/10, 30/10030/100, 293/1000293/1000 for Theil-Sen.
  • Exact fit. If all points lie on one line, every slope equals its slope, and so does bb.
  • Regression equivariant. Adding c+dxc + d x to yy adds dd to bb and cc to aa.
  • Not affine equivariant in x and y together. The fit depends on which variable is called yy; this is true of all the slope methods on these pages.
  • Efficiency. In a simulation with n=50n = 50 equally spaced xx 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 a=med⁡imed⁡j≠i(xjyi−xiyj)/(xj−xi)a = \operatorname{med}_i \operatorname{med}_{j \ne i} (x_j y_i - x_i y_j)/(x_j - x_i), 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 qq coefficients: compute the exact fit through each qq-subset of points, then take qq nested medians over the indices. The breakdown point stays near 1/2, but the cost grows like nqn^q.
  • Averaged medians. Siegel uses the usual median, with the mean of the two middle values. Then bb 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 O(n)O(n) 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 xi=xjx_i = x_j have no slope. A point whose xx 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.

repeated_median_regression.pyI0RawGitHub
# 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 O(nlog⁡2n)O(n \log^2 n) deterministic algorithm in 1992, and Matoušek, Mount and Netanyahu (1998) an O(nlog⁡n)O(n \log n) expected time algorithm.

References

  1. 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)
  2. 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))
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example