Algorithmintro
Trimmed mean
Also called truncated mean.
The mean of the sample after removing a fixed fraction of the smallest and of the largest values. Its breakdown point tends to that fraction as the sample grows.
- Time
- Θ(n²) worstΘ(n) average · best
- Space
- Θ(n) extra
- Where
- g = the number of values cut from each end; n = the sample size
- Model
- Real RAM
- Properties
- randomizedexact in exact arithmeticnot in placeofflinerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John W. Tukey, Donald H. McLaughlin, 1963
The -trimmed mean drops the smallest and the largest values of a sample and averages the rest. It sits between the mean () and the median ( as large as possible). With between 0.1 and 0.25 it keeps most of the efficiency of the mean at the normal law and resists a fraction of outliers. Two selections find the kept values without a sort, so the cost is expected .
In plain words
Judges score a performance. The organizers drop the highest score and the lowest score, then take the average of the others. One judge who gives an extreme score, by error or by bias, cannot change the result much. The trimmed mean is this rule with a fixed share of scores dropped at each end. To find the scores to keep, you do not need to put all of them in order. You only need to find the scores at the two cut points.
The problem
The input is a sample of real numbers and a fraction , or directly an integer with . Let be the order statistics. The output is
The algorithm
SELECT is quickselect on with a random pivot and a three-way partition. It rearranges the range so that holds the value of rank in the range, with .
TRIMMED-MEAN(x, α) ▷ x[0 .. n − 1], 0 ≤ α < 1/2- 1
n ← |x|, g ← ⌊α n⌋ (in exact arithmetic), A ← a copy of x - 2
if n − 2g < 1 then error - 3
SELECT(A, 0, n − 1, g) ▷ A[g] = x(g+1) - 4
SELECT(A, g, n − 1, n − g − 1) ▷ A[n − g − 1] = x(n−g) - 5
s ← A[g] + A[g + 1] + ... + A[n − g − 1] - 6
return s / (n − 2g)
Line L3 puts the smallest values in . Line L4 works only on the rest, , and puts the largest values at its right end. What is left in the middle is exactly the multiset of kept values, in some order. The order does not matter for a sum.
Example
Take and . Then and .
| step | content of (one possible order) | what is fixed |
|---|---|---|
| L3, rank 2 in | (3, 1, 4, 12, 7, 95, 5, 8, 6, 10) | , |
| L4, rank 7 in | (3, 1, 4, 7, 5, 8, 6, 10, 12, 95) | , |
| L5 | sum 40 |
The result is . The sorted sample is , so the kept values are , as claimed. The mean of the sample is , pulled up by the value 95. The median is . The exact order inside each part depends on the random pivots.
Correctness
The key fact: after SELECT on a range with result position , the range is a permutation of its old content, and . So if you sort each part, the concatenation is sorted. It follows that holds the smallest values of the range, as a multiset, even with ties. After L3, is and is . L4 applies the same fact to this range and splits off its largest values. So is . The proof, with the correctness of the three-way partition, is in proofs/correctness.md.
Proof: TRIMMED-MEAN returns the mean of the middle order statisticsfull
Let be the sorted sample and with . For a list , write for its values in non-decreasing order, and for its multiset. The arithmetic is exact.
Lemma 1 (three-way partition). Let the loop of SELECT start a round on with pivot value . When the inner loop stops, the range is a permutation of its old content, and with the final indices ,
and (the part equal to is not empty).
Proof. The loop keeps the invariant: , , , and is not yet seen. At the start and , and all three parts are empty. Each step looks at . If , the swap with moves an item equal to (or itself when ) to position , and both indices grow. If , the swap puts it at , and shrinks. Otherwise grows. Each step changes the range only by a swap, and shrinks the unseen part by one. The loop ends when , so the unseen part is empty. The pivot is a value of the range, so the middle part holds at least that item.
Lemma 2 (SELECT). After SELECT with , the range is a permutation of its old content, the rest of is unchanged, and
Proof. Invariant of the outer loop: the current window contains , every item left of the window (inside the original range) is at most every item in the window, and every item right of the window is at least every item in the window. It holds at the start. After a round with , the new window contains ; the items in are at least , and so at least every item of the new window (all ). The case is symmetric. The window shrinks by at least one item per round (Lemma 1, the middle part is not empty), so the loop ends. It ends when the window has one item, or when . In the second case , all items of are at most , and all of are at least . With the invariant this gives the claim. Only swaps inside the range change .
Lemma 3 (split). Let satisfy , and let . Then is the multiset of the first entries of , is entry (from 0), and is the multiset of the rest.
Proof. Sort the left part and the right part separately. The list is non-decreasing, because every item on the left is at most and every item on the right is at least . It has the multiset of . A multiset has exactly one non-decreasing list, so this list is . Read off the parts.
Theorem. TRIMMED-MEAN returns .
Proof. Line L1 makes a copy of , so . By Lemmas 2 and 3, after line L3,
Line L4 changes only . Its sorted content is , and the position is at offset in it. By Lemmas 2 and 3, afterwards
So . A sum does not depend on the order of its terms, so line L5 computes , and line L6 divides by the count , which line L2 checks.
Expected cost. Each round of SELECT costs at most comparisons. With a uniform random pivot, the window keeps at most of its items with probability at least : this holds when the pivot rank lies in the middle half. So the expected number of rounds before the window size drops below is at most 2 per level , and the expected total is at most comparisons for a range of items. The two calls cost at most in expectation, and lines L1, L5 and L6 cost . In the worst case each round removes one item, which gives .
Complexity
- Time. Each SELECT takes expected comparisons on a range of items, and at most . The two calls work on and items, and the sum takes additions. So the expected time is and the worst case is . With the median of medians pivot rule, SELECT and the whole method take in the worst case.
- Space. for the copy . If you may change the input, the method runs in place with extra words.
- Sorting. Sorting and summing the middle takes . It is simpler and fast enough for most samples. The selection method matters for large or for repeated use.
In exact arithmetic (integers or fractions) the result is exact. In floating point the sum in line L5 has the usual rounding error of a sum. Use Kahan summation or math.fsum for long samples.
Properties
- Breakdown point , which tends to . The breakdown point page proves it: the kept values stay inside the range of the clean points as long as at most points are replaced.
- Influence function. At a law symmetric about with quantile , it is for , and outside. It is bounded but not redescending (cited, Huber and Ronchetti 2009, Chapter 3).
- Asymptotic variance. For symmetric , it is the variance of the -Winsorized law divided by . Stigler (1973) gave the limit law for every ; when the cut quantiles are not unique, the limit is not normal.
- Efficiency at the normal. A numerical integration gives these efficiencies relative to the mean:
| 0.05 | 0.10 | 0.20 | 0.25 | |
|---|---|---|---|---|
| efficiency | 0.974 | 0.943 | 0.874 | 0.837 |
At the median end the efficiency tends to . For heavy tails, such as a law with 3 degrees of freedom, the trimmed mean beats the mean by a wide margin.
- Equivariance. is location and scale equivariant: for .
- An L-estimator. It is a linear combination of order statistics with weights in the middle and 0 at the ends.
Variants and improvements
- Winsorized mean. Replace the smallest values by and the largest by , then average. It has the same breakdown point.
- Tukey and McLaughlin standard error. Use , where is the sample variance of the Winsorized sample. Yuen's trimmed test uses it for two samples with unequal variances.
- Asymmetric trimming. Cut values at the bottom and at the top. It estimates a different parameter when is skewed.
- Interquartile mean. The case .
- Adaptive trimming. Choose from the data, for example from a measure of tail weight.
- Streaming. Over a sliding window, keep the window in an order-statistic tree; see the sliding window median for the same structure.
When to use it
Use a trimmed mean when the data are roughly symmetric but may have a few gross errors or heavy tails, and you want an estimate that is easy to explain. Sports judging, price indices and many lab protocols use it. Use the median if up to half of the data can be bad. Use the Huber M-estimator if you want a smoother weighting and a better efficiency at the same robustness. Use the plain mean if the data are clean and light-tailed.
Pitfalls
- for small samples. With and , , and the trimmed mean is the mean, with breakdown point .
- Rounding of . In floating point, , so gives 28 and not 29. Compute in exact arithmetic, or take as the input.
- Skewed data. For a skewed , the trimmed mean estimates neither the mean nor the median of . It estimates its own functional.
- Standard error. Do not use with the variance of the kept values. It is too small. Use the Winsorized variance.
- Ties at the cut. With ties at , the kept multiset is still well defined. A three-way partition keeps the time linear when many values are equal.
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/trimmed-mean/. The authors are listed in prov/4F0CN9.jsonl.
import math
import random
from fractions import Fraction
def trim_count(n: int, alpha) -> int:
"""Return g = floor(alpha * n), computed exactly.
A float alpha is read through its decimal repr, so 0.29 * 100 gives 29 and
not 28 (the float product is 28.999999999999996).
"""
a = Fraction(repr(alpha)) if isinstance(alpha, float) else Fraction(alpha)
if not 0 <= a < Fraction(1, 2):
raise ValueError("alpha must be in [0, 1/2)")
return math.floor(a * n)
def select(a: list, lo: int, hi: int, k: int, rng: random.Random) -> None:
"""Rearrange a[lo..hi] in place so that a[k] is the value of rank k - lo.
Afterwards a[lo..k-1] <= a[k] <= a[k+1..hi]. Quickselect with a random pivot
and a three-way partition, so equal keys cost no extra time.
Expected O(hi - lo + 1) comparisons.
"""
while lo < hi:
p = a[rng.randint(lo, hi)]
lt, i, gt = lo, lo, hi # a[lo..lt-1] < p, a[lt..i-1] == p, a[gt+1..hi] > p
while i <= gt:
if a[i] < p:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > p:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return
def trimmed_mean(xs, alpha=0.1, *, g=None, seed: int = 0):
"""Return the mean of x_(g+1), ..., x_(n-g), with g = floor(alpha * n).
Pass g to set the number of points cut from each end directly. The input is
not changed. Exact for int and Fraction data (the result is a Fraction).
Expected Theta(n) time, Theta(n) extra space for the copy.
"""
a = list(xs)
n = len(a) # @line L1
if g is None:
g = trim_count(n, alpha) # @line L1
if g < 0 or n - 2 * g < 1: # @line L2
raise ValueError("need n - 2 g >= 1")
rng = random.Random(seed)
select(a, 0, n - 1, g, rng) # @line L3
select(a, g, n - 1, n - g - 1, rng) # @line L4
s = sum(a[g:n - g], Fraction(0)) if all(isinstance(v, (int, Fraction)) for v in a) else math.fsum(a[g:n - g]) # @line L5
return s / (n - 2 * g) # @line L6
def winsorized_variance(xs, g: int):
"""Sample variance of the g-Winsorized sample (divide by n - 1).
The Tukey-McLaughlin standard error of the trimmed mean is
sqrt(winsorized_variance) / ((1 - 2 g / n) sqrt(n)).
"""
s = sorted(xs)
n = len(s)
w = [s[g]] * g + s[g:n - g] + [s[n - g - 1]] * g
m = sum(w) / n
return sum((v - m) ** 2 for v in w) / (n - 1)
test_trimmed_mean.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trimmed-mean/. The authors are listed in prov/4F0CN9.jsonl.
import random
from fractions import Fraction
import pytest
from trimmed_mean import select, trim_count, trimmed_mean, winsorized_variance
def by_sorting(xs, g):
"""Oracle: sort, cut g values from each end, average exactly."""
s = sorted(xs)
kept = s[g:len(s) - g]
return sum(kept, Fraction(0)) / len(kept)
def test_small_samples_by_hand() -> None:
# sorted: 1 1 2 3 3 4 5 5 6 9; g = 2 keeps 2 3 3 4 5 5, sum 22.
xs = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
assert trimmed_mean(xs, Fraction(1, 5)) == Fraction(22, 6)
# g = 0 is the mean, 39 / 10.
assert trimmed_mean(xs, 0) == Fraction(39, 10)
# g = 4 keeps 3 and 4.
assert trimmed_mean(xs, g=4) == Fraction(7, 2)
# (2, 4, 4, 5, 7, 9, 30) with g = 1 keeps 4 4 5 7 9.
assert trimmed_mean([2, 4, 4, 5, 7, 9, 30], g=1) == Fraction(29, 5)
# the example of the page
# sorted: 1 3 4 5 6 7 8 10 12 95; g = 2 keeps 4 5 6 7 8 10, sum 40.
assert trimmed_mean([12, 7, 3, 95, 5, 8, 6, 1, 10, 4], Fraction(1, 5)) == Fraction(20, 3)
def test_trim_count_is_exact() -> None:
assert trim_count(100, 0.29) == 29
assert trim_count(10, 0.1) == 1
assert trim_count(7, 0.1) == 0
assert trim_count(20, Fraction(1, 4)) == 5
with pytest.raises(ValueError):
trim_count(10, 0.5)
def test_against_sorting_random() -> None:
rng = random.Random(1)
for _ in range(400):
n = rng.randint(1, 40)
xs = [rng.randint(-5, 5) for _ in range(n)] # many ties
g = rng.randint(0, (n - 1) // 2)
assert trimmed_mean(xs, g=g, seed=rng.randint(0, 10**6)) == by_sorting(xs, g)
def test_select_postcondition() -> None:
rng = random.Random(2)
for _ in range(300):
n = rng.randint(1, 30)
a = [rng.randint(0, 6) for _ in range(n)]
lo = rng.randint(0, n - 1)
hi = rng.randint(lo, n - 1)
k = rng.randint(lo, hi)
before = list(a)
select(a, lo, hi, k, rng)
assert a[:lo] == before[:lo] and a[hi + 1:] == before[hi + 1:]
assert sorted(a[lo:hi + 1]) == sorted(before[lo:hi + 1])
assert all(v <= a[k] for v in a[lo:k]) and all(v >= a[k] for v in a[k + 1:hi + 1])
def test_input_not_changed_and_float_data() -> None:
xs = [0.5, 2.25, -1.0, 7.5, 3.0]
copy = list(xs)
assert trimmed_mean(xs, g=1) == pytest.approx((0.5 + 2.25 + 3.0) / 3)
assert xs == copy
def test_empirical_breakdown() -> None:
# Move k points to a huge value t. The trimmed mean stays in the range of the
# clean points for k <= g, and grows without bound for k = g + 1.
rng = random.Random(3)
n, g = 20, 4
clean = [rng.randint(0, 100) for _ in range(n)]
for t in (10**6, 10**12, 10**30):
for k in range(0, g + 2):
ys = clean[:n - k] + [t] * k
v = trimmed_mean(ys, g=g)
lo, hi = min(clean[:n - k]), max(clean[:n - k])
if k <= g:
assert lo <= v <= hi
else:
assert v >= Fraction(t, n - 2 * g)
# The mean (g = 0) breaks with one point.
assert trimmed_mean(clean[:-1] + [10**30], g=0) > 10**28
def test_winsorized_variance_small() -> None:
# g = 1 on (1, 2, 3, 4, 100): Winsorized sample (2, 2, 3, 4, 4), mean 3, variance 4 / 4.
assert winsorized_variance([1, 2, 3, 4, 100], 1) == 1
def test_errors() -> None:
with pytest.raises(ValueError):
trimmed_mean([1, 2], g=1)
with pytest.raises(ValueError):
trimmed_mean([], 0)
History
Tukey and McLaughlin (1963) studied trimmed means for small samples and gave a -like statistic with a Winsorized variance. Bickel studied their large-sample behaviour in 1965. Stigler (1973) found the limit law for every distribution and showed that it can fail to be normal when a cut quantile is not unique. Yuen (1974) gave the two-sample trimmed test.
References
- John W. Tukey and Donald H. McLaughlin, Less vulnerable confidence and significance procedures for location based on a single sample, trimming/Winsorization 1, Sankhyā A 25(3), 1963, pp. 331 to 352 (the trimmed mean and its Winsorized standard error)
- Stephen M. Stigler, The asymptotic distribution of the trimmed mean, The Annals of Statistics 1(3), 1973, pp. 472 to 477 (the limit law of the trimmed mean for any distribution)
- Karen K. Yuen, The two-sample trimmed t for unequal population variances, Biometrika 61(1), 1974, pp. 165 to 170 (the trimmed t statistic with the Winsorized variance)
- Ricardo A. Maronna, R. Douglas Martin, Victor J. Yohai and Matías Salibián-Barrera, Robust Statistics, Theory and Methods (with R), second edition, Wiley, 2019, Chapter 2 (trimmed means, their variance and their efficiency at the normal)
- Peter J. Huber and Elvezio M. Ronchetti, Robust Statistics, second edition, Wiley, 2009, Chapter 3 (L-estimators, the trimmed mean and its influence function)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, fourth edition, Section 9.2 (selection in expected linear time) and Section 9.3 (selection in worst-case linear time)
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 4F0CN9 Edit this page History Report an error Markdown