Algorithmadvanced
Hodges-Lehmann estimator
Also called Hodges-Lehmann shift estimator, median of Walsh averages.
Estimates a location as the median of all pairwise averages, or a shift as the median of all pairwise differences. It inverts the Wilcoxon test and breaks down at 29 percent.
- Time
- O(n^3) worstΘ(n log n) average · best
- Space
- Θ(n) extra
- Where
- N = the number of Walsh averages or differences; n = the sample size (m + n for two samples)
- Model
- Real RAM
- Properties
- randomizedexact in exact arithmeticnot in placeofflinerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joseph L. Hodges Jr., Erich L. Lehmann, 1963
The Hodges-Lehmann estimator of location is the median of the Walsh averages with . The two-sample version estimates a shift as the median of the differences . Both come from rank tests: they are the values of the parameter at which the Wilcoxon signed-rank test or the Mann-Whitney test is most balanced. The estimator has 95.5 percent efficiency at the normal law and breaks down at percent contamination. Listing all averages costs , but a selection in a sorted matrix finds the median in expected time.
In plain words
Take every pair of values in the sample, and also each value with itself, and write down the midpoint of the pair. The estimate is the middle one of all these midpoints. A single wild value spoils only the midpoints that use it, and those are a small share. So the result stays near the bulk of the data. It is close to the mean when the data are clean, and close to the median when they are not.
To find the middle midpoint fast, sort the sample first. Then the midpoints form a table in which each row and each column increases. You can count how many entries of such a table are below a guess in one sweep, and that lets you close in on the middle entry without listing all of them.
The problem
One sample. Input . Output
the median of numbers, with the average of the two middle values when is even.
Two samples. Input and . Output over the pairs.
Both are the median of a set with and sorted ascending and nondecreasing. For one sample, $a = b = $ sorted and ; the answer is half the median sum. For two samples, $a = $ sorted , $b = $ sorted and . Each row is nondecreasing in , and each column is nondecreasing in . This is a sorted matrix.
The algorithm
SELECT-SUM finds the -th smallest cell. It keeps, for each row, an active column range . Every cell left of the range is known to be at most the answer, and every cell right of it is known to be at least the answer. Each round takes a random active cell as pivot , counts the cells and in the whole matrix, and moves the bounds past .
SELECT-SUM(a, b, L, k) ▷ k-th smallest of a[i] + b[j], j ≥ L[i]- 1
for each row i: lo[i] ← L[i], hi[i] ← n − 1 - 2
loop - 3
W ← Σ max(0, hi[i] − lo[i] + 1) ▷ active cells - 4
pick an active cell (i, j) uniformly at random; v ← a[i] + b[j] - 5
(c≤, le[ ]) ← COUNT(v, ≤); (c<, lt[ ]) ← COUNT(v, <) - 6
if c< ≥ k then for each i: hi[i] ← min(hi[i], lt[i]) - 7
else if c≤ ≥ k then return v - 8
else for each i: lo[i] ← max(lo[i], le[i] + 1) HODGES-LEHMANN(x)- 9
sort x; N ← n(n + 1)/2; k ← ⌈N/2⌉ - 10
s1 ← SELECT-SUM(x, x, (0, 1, ..., n − 1), k) - 11
s2 ← s1 if N is odd or COUNT(s1, ≤) ≥ k + 1, else the least cell > s1 - 12
return (s1 + s2)/4 COUNT(v, ≤) ▷ staircase walk over the rows- 13
j ← n − 1, c ← 0; for i ← 0 to m − 1 do - 14
while j ≥ 0 and a[i] + b[j] > v do j ← j − 1 - 15
le[i] ← j ▷ last column with a cell ≤ v - 16
c ← c + max(0, j − L[i] + 1)
COUNT is the same walk with in line L14. The walk is correct because the last column with can only move left as grows. The least cell greater than in line L11 is the minimum over the rows of the first cell right of , one more walk.
Example
Take , sorted . The matrix of sums , :
| row | sums |
|---|---|
| () | 2, 4, 5, 8, 21 |
| () | 6, 7, 10, 23 |
| () | 8, 11, 24 |
| () | 14, 27 |
| () | 40 |
is odd, so . One run of SELECT-SUM:
| round | pivot | action | |||
|---|---|---|---|---|---|
| 1 | 15 | 2 | 0 | 1 | raise : the cell 2 is out |
| 2 | 14 | 11 | 8 | 9 | lower : cells are out |
| 3 | 7 | 6 | 3 | 4 | raise : cells are out |
| 4 | 4 | 8 | 5 | 7 | raise : cells are out |
| 5 | 1 | 10 | 7 | 8 | : return 10 |
So the median sum is 10 and . The sorted sums are , and the 8th is 10, as found. For comparison, the mean is 7, pulled up by the value 20, and the median is 4.
Correctness
The invariant of the loop: every cell left of the active range of its row is less than the answer , and every cell right of it is greater than . So every cell with value is active, and the active range is never empty. A round with shows that , so every cell is greater than and can leave on the right. A round with shows , so every cell can leave on the left. Otherwise , which means that the -th smallest cell equals . Each round removes at least the pivot, so the loop ends. The full proof is in proofs/correctness.md.
Proof: SELECT-SUM returns the k-th smallest cell, and HODGES-LEHMANN the median of the Walsh averagesfull
Setting. and are sorted, and . The cells are the pairs with , and the value of a cell is . There are cells, and . Let be the sorted cell values (with multiplicity) and . For a value , and are the numbers of cells with value and .
Lemma 0. A value equals if and only if
Proof. If , the cells are among , so , and are , so . Conversely, if (1) holds, then at least cells are , so ; and fewer than cells are , so . Thus .
Lemma 1 (COUNT). For each row , line L15 sets , where (and if there is no such ). Line L16 adds the number of cells in row . So COUNT returns .
Proof. If , then because . So . We show by induction that when row starts. For , . For row , starts at the end value of row , which is . In row , line L14 lowers while . Every column has , because is sorted, and column has . So the loop stops at . The cells of row are the columns , and there are of them. This is the value that line L16 adds. The strict count is the same proof with in place of .
The index only moves down, so one COUNT takes steps.
The parts of a row. In row , the columns are the left part, the columns are the active part, and the columns are the right part. is the number of active cells.
Invariant. At the start of each round of the loop of line L2:
- (I) every left cell has value , and every right cell has value .
Line L1 makes all left and right parts empty, so (I) holds before the first round.
Lemma 2. If (I) holds, then every cell with value is active, and .
Proof. A cell with value is neither nor , so by (I) it is not left and not right. There is at least one such cell, .
Lemma 3 (one round). Assume (I) at the start of a round with pivot . Then the round returns , or (I) holds at the end of the round and is at least 1 smaller.
Proof. By Lemma 2, line L4 can pick an active cell, and is its value. By Lemma 1, line L5 computes , , and the last columns and whose cells are and .
Case (line L6). If , then , which is false by Lemma 0. So . Line L6 sets , and the left parts do not change. A cell that joins the right part of row has a column , so its value is . So (I) holds. The pivot has value , which is not , so its column is , and it leaves the active part.
Case (line L7). By Lemma 0, , and the round returns .
Case (line L8). If , then , which is false by Lemma 0. So . Line L8 sets , and the right parts do not change. A cell that joins the left part of row has a column , so its value is . So (I) holds. The pivot has value , so its column is , and it leaves the active part.
In the first and third cases the active parts only shrink, and the pivot leaves them, so drops by at least 1.
Theorem 1. SELECT-SUM returns , the -th smallest cell value.
Proof. By Lemma 3 and induction, (I) holds at the start of every round. at the start, every round that does not return lowers by at least 1, and at every start by Lemma 2. So the loop returns after at most rounds. It returns only at line L7, and there the value is by Lemma 3.
Theorem 2. HODGES-LEHMANN returns the median of the Walsh averages , .
Proof. After line L9, is sorted. Take and . The cells are the pairs of sorted positions, and each Walsh average is half the value of exactly one cell. So the median of the Walsh averages is half the median of the cell values. Line L9 sets , and by Theorem 1 line L10 gives .
If is odd, the median of the cell values is , line L11 sets , and line L12 returns .
If is even, the median of the cell values is . If , then , so . Else by Lemma 0, so is the least cell value greater than . In row the cells greater than are the columns from to , and the least of them is the first one, because is sorted. The minimum of these first cells over all rows is , which line L11 takes. In both cases line L12 returns , which is half the median of the cell values.
The two-sample estimator uses the same proof with the sorted values , the sorted , and . Then the cells are all the pairs, with the values .
Expected number of rounds. Put the active cells in order by value, with ties broken by position. The pivot is uniform among the active cells. Let be its rank. In the case of line L6, every active cell with value leaves, and there are at least of them. In the case of line L8, every active cell with value leaves, and there are at least of them. If , at least cells leave in both cases. This occurs with probability at least . So in expectation at most 2 rounds make drop by the factor , and the expected number of rounds is at most . With , this is rounds of cost each.
Complexity
- One round costs : line L3 and the random pick scan the rows, and each COUNT is one staircase walk.
- Number of rounds. The pivot is uniform among the active cells. With probability at least its rank among them is in the middle half, and then at least cells leave. So the expected number of rounds is , and the expected time of SELECT-SUM is . The worst case removes one cell per round: for this version. It has probability close to zero, and the deterministic methods below avoid it.
- Total. The sort in line L9 takes . So the expected time is , with extra space for the bounds.
- Naive method. List all averages and select their median with quickselect: expected time and space. With a sort it is .
- Deterministic. Johnson and Mizoguchi (1978) select in in worst-case time, and Frederickson and Johnson select in a sorted matrix in after the sort; see sorted matrix selection.
In exact arithmetic the result is exact: the implementation works with the integer or rational sums and halves once at the end.
Properties
- Location and scale equivariant. , also for , because the set of Walsh averages maps in the same way.
- Link to the signed-rank test (Tukey's identity). For differences with no zeros and distinct , the signed-rank statistic is . Proof. A pair with has its member of larger positive. Assign each such pair to that member. A positive with rank of gets exactly the pairs with , each with a positive sum. So the count is . So counts the Walsh averages above , and is the where crosses its null mean . Inverting the test the same way gives a confidence interval between two order statistics of the Walsh averages.
- Breakdown point (proved here). Let and
Then the finite-sample breakdown point is , and it tends to .
Proof. Replace points. The Walsh averages of two clean points, of them, lie in the range of the clean points. The other averages use a replaced point. If , at most averages are outside . For odd that is at most , so the -th smallest average has at most values below it and above it that could leave the range, and it stays in . For even at most averages leave, so the -th and -th smallest stay in the range, and so does their mean. If , move the points to . Each average with a replaced point is at least , and there are at least of them, so the upper middle average, and with it the median, tends to infinity. For the limit, is the least with , and . So , which gives .
For the values of are . In the contamination model the same number appears: a Walsh average of two independent draws is clean with probability , and the median of their law stays bounded while .
- Efficiency (cited). At a law symmetric about with density , the influence function is and the asymptotic variance is . At the normal this gives , so the efficiency relative to the mean is . Hodges and Lehmann (1956) showed that the efficiency is at least for every symmetric , and it can be infinite for heavy tails.
- Assumptions. The one-sample estimator targets the center of a symmetric law. For a skewed law it estimates the pseudo-median, the median of the law of , which is neither the mean nor the median.
Variants and improvements
- Two-sample shift. The median of ; see above. It inverts the Mann-Whitney test, and it estimates the shift in the model .
- Excluding . Some texts use only . The two versions differ by and have the same asymptotics.
- Deterministic selection. Use the Johnson and Mizoguchi or the Frederickson and Johnson selection for a guaranteed .
- Confidence intervals. The interval with the -th smallest and -th largest Walsh average, with from the null law of , has exact coverage under symmetry. The same selection routine computes both ends.
- Regression. The Theil-Sen estimator is the analogue for a slope: the median of the pairwise slopes, with the same breakdown point .
When to use it
Use it for a location or a shift when the law is roughly symmetric and may have heavy tails. It is the natural point estimate to report next to a Wilcoxon or Mann-Whitney test. It is more efficient than the median at the normal (0.955 against 0.637) and more robust than the mean. Use the median when more than about 29 percent of the data can be bad, and the Huber M-estimator when you also want a smooth estimating equation for a regression.
Pitfalls
- Listing all averages. For there are Walsh averages. The naive method runs out of memory; the selection method does not.
- Even . When is even, the median is the mean of two cells. The second one is not always equal to the first. Find it with one more count, as in line L11.
- Halving early. Halving each sum in floating point before the comparison is harmless, but halving integers with integer division is not. Select on the sums and halve once.
- The breakdown point is not 1/2. About 29 percent bad data is enough to carry the estimate away.
- Ties. Ties in the data are harmless for the estimate, but the exact null law of the test with ties needs the tie-corrected version.
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/hodges-lehmann-estimator/. The authors are listed in prov/WF6BA7.jsonl.
import random
from fractions import Fraction
def count_le(a, b, start, v, strict=False):
"""Count the cells a[i] + b[j] <= v (or < v when strict) with j >= start[i].
a and b are sorted ascending and start is nondecreasing. Returns the count and,
for each row i, the last column last[i] whose cell is <= v (or < v); last[i]
can be below start[i]. One staircase walk: O(len(a) + len(b)).
"""
n = len(b)
j = n - 1
c = 0
last = [0] * len(a)
for i, ai in enumerate(a): # @line L13
if strict:
while j >= 0 and ai + b[j] >= v:
j -= 1
else:
while j >= 0 and ai + b[j] > v: # @line L14
j -= 1
last[i] = j # @line L15
if j >= start[i]:
c += j - start[i] + 1 # @line L16
return c, last
def select_sum(a, b, start, k, rng):
"""Return the k-th smallest (k >= 1) of the cells a[i] + b[j] with j >= start[i].
Randomized selection in the sorted matrix: each round takes a random active
cell as pivot and moves the per-row bounds lo[i] and hi[i] past it.
Expected O((len(a) + len(b)) log N) time for N cells.
"""
m, n = len(a), len(b)
lo = list(start) # @line L1
hi = [n - 1] * m # @line L1
while True: # @line L2
widths = [max(0, hi[i] - lo[i] + 1) for i in range(m)]
w = sum(widths) # @line L3
if w == 0:
raise ValueError("k is out of range")
r = rng.randrange(w) # @line L4
i = 0
while r >= widths[i]:
r -= widths[i]
i += 1
v = a[i] + b[lo[i] + r] # @line L4
cle, le = count_le(a, b, start, v) # @line L5
clt, lt = count_le(a, b, start, v, strict=True) # @line L5
if clt >= k: # @line L6
for t in range(m):
hi[t] = min(hi[t], lt[t])
elif cle >= k: # @line L7
return v
else: # @line L8
for t in range(m):
lo[t] = max(lo[t], le[t] + 1)
def successor_sum(a, b, start, v):
"""Smallest cell value > v, or None. O(len(a) + len(b))."""
_, le = count_le(a, b, start, v)
best = None
for i, ai in enumerate(a):
j = max(le[i] + 1, start[i])
if j < len(b):
s = ai + b[j]
if best is None or s < best:
best = s
return best
def _median_of_cells(a, b, start, total, rng):
"""Median of the multiset of cells (the average of the two middle ones if total is even)."""
k = (total + 1) // 2
s1 = select_sum(a, b, start, k, rng) # @line L10
if total % 2 == 1:
s2 = s1
else:
cle, _ = count_le(a, b, start, s1)
s2 = s1 if cle >= k + 1 else successor_sum(a, b, start, s1) # @line L11
if _exact(a) and _exact(b):
return (Fraction(s1) + Fraction(s2)) / 2
return (s1 + s2) / 2
def _exact(a):
return all(isinstance(v, (int, Fraction)) for v in a)
def hodges_lehmann(xs, seed: int = 0):
"""One-sample Hodges-Lehmann estimate: the median of the Walsh averages (x_i + x_j)/2, i <= j.
Exact (a Fraction) for int or Fraction data. Expected O(n log n) time, O(n) space.
"""
x = sorted(xs) # @line L9
n = len(x)
if n == 0:
raise ValueError("empty sample")
total = n * (n + 1) // 2 # @line L9
med_sum = _median_of_cells(x, x, list(range(n)), total, random.Random(seed)) # @line L10
return med_sum / 2 # @line L12
def hodges_lehmann_shift(xs, ys, seed: int = 0):
"""Two-sample Hodges-Lehmann shift estimate: the median of all y_j - x_i.
Exact for int or Fraction data. Expected O((m + n) log(m n)) time after sorting.
"""
if not xs or not ys:
raise ValueError("empty sample")
a = sorted(-v for v in xs) # ascending, so a[i] = -x in descending order of x
b = sorted(ys)
return _median_of_cells(a, b, [0] * len(a), len(a) * len(b), random.Random(seed))
test_hodges_lehmann_estimator.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hodges-lehmann-estimator/. The authors are listed in prov/WF6BA7.jsonl.
import random
from fractions import Fraction
from statistics import median
import pytest
from hodges_lehmann_estimator import (
count_le, hodges_lehmann, hodges_lehmann_shift, select_sum,
)
def naive_hl(xs):
"""Oracle: list all n(n + 1)/2 Walsh averages, sort, take the median."""
n = len(xs)
walsh = [Fraction(xs[i] + xs[j], 2) for i in range(n) for j in range(i, n)]
return median(walsh)
def naive_shift(xs, ys):
return median([Fraction(y - x) for x in xs for y in ys])
def test_small_by_hand() -> None:
# Walsh averages of (1, 2, 9): 1, 1.5, 5, 2, 5.5, 9 -> sorted 1 1.5 2 5 5.5 9, median 3.5.
assert hodges_lehmann([1, 2, 9]) == Fraction(7, 2)
# (0, 1): averages 0, 0.5, 1, median 0.5.
assert hodges_lehmann([0, 1]) == Fraction(1, 2)
assert hodges_lehmann([5]) == 5
# The example of the page.
assert hodges_lehmann([3, 7, 1, 20, 4]) == 5
# Shift: x = (1, 2), y = (4, 9): differences 3 8 2 7, median 5.
assert hodges_lehmann_shift([1, 2], [4, 9]) == 5
def test_against_all_walsh_averages() -> None:
rng = random.Random(11)
for _ in range(300):
n = rng.randint(1, 40)
xs = [rng.randint(-20, 20) for _ in range(n)]
assert hodges_lehmann(xs, seed=rng.randint(0, 10**6)) == naive_hl(xs)
def test_shift_against_all_differences() -> None:
rng = random.Random(12)
for _ in range(200):
m, n = rng.randint(1, 25), rng.randint(1, 25)
xs = [rng.randint(-9, 9) for _ in range(m)]
ys = [rng.randint(-9, 9) for _ in range(n)]
assert hodges_lehmann_shift(xs, ys, seed=rng.randint(0, 10**6)) == naive_shift(xs, ys)
def test_every_rank_of_select() -> None:
rng = random.Random(13)
for _ in range(40):
n = rng.randint(1, 15)
x = sorted(rng.randint(0, 8) for _ in range(n))
cells = sorted(x[i] + x[j] for i in range(n) for j in range(i, n))
for k in range(1, len(cells) + 1):
assert select_sum(x, x, list(range(n)), k, rng) == cells[k - 1]
def test_count_le_matches_brute_force() -> None:
rng = random.Random(14)
for _ in range(200):
n = rng.randint(1, 12)
x = sorted(rng.randint(0, 10) for _ in range(n))
v = rng.randint(-1, 21)
c, _ = count_le(x, x, list(range(n)), v)
assert c == sum(1 for i in range(n) for j in range(i, n) if x[i] + x[j] <= v)
c, _ = count_le(x, x, list(range(n)), v, strict=True)
assert c == sum(1 for i in range(n) for j in range(i, n) if x[i] + x[j] < v)
def test_large_input_is_fast_and_correct() -> None:
rng = random.Random(15)
xs = [rng.gauss(0.0, 1.0) for _ in range(2000)]
est = hodges_lehmann(xs)
walsh = sorted((xs[i] + xs[j]) / 2 for i in range(0, 2000, 1) for j in range(i, 2000))
assert est == pytest.approx((walsh[len(walsh) // 2 - 1] + walsh[len(walsh) // 2]) / 2, abs=1e-12)
def test_tukey_identity() -> None:
# W+ (sum of the ranks of |d_i| over d_i > 0) equals #{i <= j : d_i + d_j > 0}.
rng = random.Random(16)
for _ in range(200):
n = rng.randint(1, 15)
mags = rng.sample(range(1, 100), n)
d = [m if rng.random() < 0.5 else -m for m in mags]
order = sorted(range(n), key=lambda i: abs(d[i]))
rank = {i: r + 1 for r, i in enumerate(order)}
w_plus = sum(rank[i] for i in range(n) if d[i] > 0)
pairs = sum(1 for i in range(n) for j in range(i, n) if d[i] + d[j] > 0)
assert w_plus == pairs
def finite_breakdown_count(n):
total = n * (n + 1) // 2
need = (total + 1) // 2
return next(m for m in range(n + 1) if total - (n - m) * (n - m + 1) // 2 >= need)
def test_empirical_breakdown() -> None:
# Move k points to a huge t: bounded for k < m*, unbounded at k = m*.
rng = random.Random(17)
for n in (5, 10, 20):
mstar = finite_breakdown_count(n)
clean = [rng.randint(0, 50) for _ in range(n)]
for t in (10**9, 10**18):
for k in range(mstar + 1):
ys = clean[:n - k] + [t] * k
v = hodges_lehmann(ys)
if k < mstar:
assert min(clean[:n - k]) <= v <= max(clean[:n - k])
else:
assert v >= Fraction(t, 4)
assert [finite_breakdown_count(n) for n in (5, 10, 20, 100)] == [2, 4, 6, 30]
def test_errors() -> None:
with pytest.raises(ValueError):
hodges_lehmann([])
with pytest.raises(ValueError):
hodges_lehmann_shift([], [1])
History
Hodges and Lehmann (1963) showed how to turn a rank test into an estimator of location or shift, and they derived the median of the Walsh averages from the signed-rank test. Their 1956 paper had already found the efficiency of the Wilcoxon tests relative to the test: at the normal and never below 0.864. Johnson and Mizoguchi (1978) gave an selection in , and Monahan (1984) published a practical randomized algorithm for the Hodges-Lehmann estimate as ACM Algorithm 616.
References
- J. L. Hodges Jr. and E. L. Lehmann, Estimates of location based on rank tests, The Annals of Mathematical Statistics 34(2), 1963, pp. 598 to 611 (the estimator from the signed-rank and rank-sum tests, and its asymptotic efficiency)
- J. L. Hodges Jr. and E. L. Lehmann, The efficiency of some nonparametric competitors of the t-test, The Annals of Mathematical Statistics 27(2), 1956, pp. 324 to 335 (the efficiency 3/pi at the normal and the lower bound 0.864)
- John F. Monahan, Algorithm 616, fast computation of the Hodges-Lehmann location estimator, ACM Transactions on Mathematical Software 10(3), 1984, pp. 265 to 270 (randomized selection among the Walsh averages in expected O(n log n) time)
- Donald B. Johnson and Tetsuo Mizoguchi, Selecting the Kth element in X + Y and X1 + X2 + ... + Xm, SIAM Journal on Computing 7(2), 1978, pp. 147 to 153 (deterministic selection in X + Y in O(n log n) time)
- Peter J. Huber and Elvezio M. Ronchetti, Robust Statistics, second edition, Wiley, 2009, Chapter 3 (R-estimators, their influence function and breakdown point)
- Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 3 (the one-sample location estimator and its confidence interval) and Chapter 4 (the two-sample shift estimator)
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 WF6BA7 Edit this page History Report an error Markdown