Algorithmresearch
Filter algorithm for robust mean estimation
Also called spectral filtering for robust estimation.
Estimates a high-dimensional mean under epsilon contamination by repeatedly removing points far along the top eigenvector of the covariance. Its error does not grow with the dimension.
- Time
- O(n (n d² + k d²)) worstO(r (n d² + k d²)) averageO(n d² + k d²) best
- Space
- O(n + d²) extra
- Where
- d = the dimension; k = the number of power iteration steps in a round; n = the number of points; r = the number of rounds
- Model
- Real RAM
- Properties
- deterministicnot exact in exact arithmeticnot in placeofflinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ilias Diakonikolas, Gautam Kamath, Daniel M. Kane, Jerry Li, Ankur Moitra, Alistair Stewart, 2016
The filter estimates the mean of a high-dimensional distribution when an fraction of the sample is replaced by arbitrary points. It keeps a weight for every point. In each round it computes the weighted mean and the weighted covariance matrix and finds the top eigenvalue and its eigenvector . If is close to the variance of the clean data, the outliers cannot have moved the mean much, so it returns the weighted mean. Otherwise it lowers the weight of each point in proportion to its squared projection on . For a Gaussian with identity covariance, Diakonikolas et al. (2019) prove an error of , with no factor that grows with the dimension . In the contamination model the sample mean can be moved arbitrarily far, and the coordinatewise median has an error that grows like .
In plain words
Suppose most of the points come from a round cloud and a few were planted by an adversary. If the planted points pull the average away, they must stretch the cloud in the direction of the pull. So the algorithm looks for the direction in which the cloud is most stretched. If that stretch is about as large as for clean data, it stops and returns the average. If not, the points that lie far out along that direction are suspicious. It lowers their weights, more for points that lie farther out, and repeats. Because the planted points cause the stretch, they lose more weight than the clean points.
The problem
The input is points and the fraction . In the strong contamination model an adversary draws points from , sees them, and replaces any of them. The goal is an estimate with a small . Write for the indices of the clean points and for the replaced ones. The algorithm does not know and .
For weights with , put and . The threshold is . The implementation uses .
The algorithm
FILTER(x_1..x_N, ε, θ)- 1
w_i ← 1/N for every i - 2
repeat - 3
μ ← Σ w_i x_i / Σ w_i - 4
(λ, v) ← the top eigenvalue and a unit eigenvector of Σ_w, by power iteration - 5
if λ ≤ θ then return μ - 6
τ_i ← (vᵀ(x_i − μ))² for every i - 7
τ_max ← max{τ_i : w_i > 0}; if τ_i = τ_max for every i with w_i > 0 then return μ - 8
w_i ← w_i (1 − τ_i / τ_max) for every i
Line L8 is the soft version of the filter. The point that lies farthest along gets weight 0, and every other point loses a part of its weight in proportion to . Line L7 handles the case where all remaining points lie at the same distance along .
Example
Take points in the plane with : the eight clean points , , , , , , which have mean , and two planted points at . The threshold is .
Round 0. All weights are . The mean is , and
Since , the filter acts. :
| point | (1,0) | (−1,0) | (0,1) | (0,−1) | (1,1) | (−1,−1) | (1,−1) | (−1,1) | (4,4) | (4,4) |
|---|---|---|---|---|---|---|---|---|---|---|
| 0.18 | 3.38 | 0.18 | 3.38 | 0.08 | 6.48 | 1.28 | 1.28 | 20.48 | 20.48 | |
| new | 0.0991 | 0.0835 | 0.0991 | 0.0835 | 0.0996 | 0.0684 | 0.0938 | 0.0938 | 0 | 0 |
The weighted mean of is . The two planted points carry of the weighted sum , more than half. They lose their whole weight , and the clean points lose together.
Round 1. The total weight is . The weighted mean is , and , so the filter returns it. For comparison, the sample mean is and the coordinatewise median is . The output is not exactly , because the clean points that lay far along lost some weight too.
Correctness
The page proves that the loop stops and that each round with a large bad share removes more bad weight than good weight. The error bound is cited, not proved. proofs/correctness.md has the proofs.
- is the weighted mean of . .
- Termination. In a round that updates the weights, the points with get weight 0, and, because line L7 did not return, some point keeps a positive weight. So the number of positive weights drops by at least 1 in each such round, and the loop returns within rounds with .
- Removal lemma. Point loses . So the good points lose and the bad points lose . If the bad points carry at least half of the weighted , the good points lose at most as much as the bad ones.
- Good weight is kept. If the condition of the removal lemma holds in every round, the good points lose at most the initial bad weight , so they keep a weight of at least .
- The error bound (cited). For an -corrupted sample of of size of order up to logarithmic factors, with high probability the condition of the removal lemma holds while is above a threshold of the form , and a weighted mean with below it and good weight at least is within of (Diakonikolas et al. 2019; Diakonikolas and Kane 2023).
Proof: The filter stops, and a round with large bad mass removes more bad weight than good weightfull
This proof covers the deterministic part of the filter: the stopping of the loop and the removal lemma. The error bound for Gaussian data is a theorem of Diakonikolas, Kamath, Kane, Li, Moitra and Stewart (2019). It is cited on the main page and is not proved here.
Notation. The points are , and the weights are with . Put and . In a round, is a unit vector and ; power iteration returns such a pair, with the Rayleigh quotient of . Put , and let be the largest over the indices with . Let be the threshold.
Lemma 1 (the weighted mean of is ). .
Proof. . Sum with weights and use the definition of .
Lemma 2 (the update). In a round that reaches line L8, every new weight satisfies . At least one index with gets , and at least one keeps .
Proof. Line L7 did not return, so the indices with do not all have . So , because is at least every such and one of them is smaller. For , , so . For , . An index with and gets . An index with and keeps .
Theorem 1 (termination). The loop returns after at most rounds, and in every round, so and are always defined.
Proof. At the start every weight is . By Lemma 2, each round that does not return keeps a positive weight, so holds again, and it lowers the number of positive weights by at least 1. Weights that are 0 stay 0. The number of positive weights starts at and stays at least 1, so at most rounds can update the weights. The next round returns at line L5 or L7.
Lemma 3 (removal). Let the indices be split into good ones and bad ones . In a round that reaches line L8, the weight removed from is , and the weight removed from is . So if
then the round removes at most as much weight from as from .
Proof. For , , and for both sides are 0. Sum over and over .
By Lemma 1, the condition of Lemma 3 says that the bad points carry at least half of the weighted mean of .
Corollary 1 (the good weight is kept). Suppose and the condition of Lemma 3 holds in every round that updates the weights. Then at the end
Proof. Add the inequality of Lemma 3 over the rounds. The total weight removed from is at most the initial weight of . The good points start with weight .
What is cited. For an -corrupted sample of with of order up to logarithmic factors, the good points satisfy, with high probability, a deterministic stability condition. Under it, two facts hold (Diakonikolas et al. 2019; Diakonikolas and Kane 2023). First, while is above a threshold of the form , the bad points carry most of the weighted , so Lemma 3 applies. Second, when is below the threshold and the good weight is at least , the weighted mean satisfies . With Corollary 1 these give the error bound. The constant , and whether the condition of Lemma 3 holds in a given finite run, are not proved here. The tests measure them.
Complexity
- One round. The weighted mean costs and the weighted covariance matrix . Power iteration with steps costs . The projections cost . So a round costs . Without forming , each power iteration step can multiply by in , for in a round.
- Rounds. At most rounds, by the termination proof, so the worst case is . In the tests 1 to 4 rounds were enough, because a cluster of planted points loses most of its weight in one round.
- Space. for the weights and the covariance matrix.
Properties
Proved on this page: termination, the identity for , the removal lemma, and the kept good weight under the condition of the lemma. Cited: the error bound and the sample size. Measured: everything in the tests below.
- Error independent of (cited). for , compared with for any estimator, in the worst case for the coordinatewise median, and no bound for the sample mean.
- Measured against the sample mean. 1000 points in with 10% planted points from , . The table shows for two seeds. The last column is the mean of the clean points only, which no estimator can know.
| shift | seed | filter | sample mean | coordinatewise median | mean of clean points |
|---|---|---|---|---|---|
| 4 | 0 | 0.170 | 0.404 | 0.369 | 0.087 |
| 4 | 1 | 0.231 | 0.421 | 0.359 | 0.119 |
| 8 | 0 | 0.104 | 0.801 | 0.487 | 0.087 |
| 8 | 1 | 0.168 | 0.815 | 0.452 | 0.119 |
- Measured against the dimension. With shift 20 and 1000 points, the filter errors for were , close to the mean of the clean points (). The coordinatewise median errors grew: . The sample mean errors were about 2.0.
- Measured removal condition. In the run with shift 8, seed 0, the bad points carried more than half of the weighted in rounds 0 and 1, but not in round 2. Over the whole run the good points lost of weight and the bad points .
- Clean data. On uncorrupted data with at the start, the filter returns the sample mean.
- Moderate shifts are the hard case. Planted points at shift 4 are harder to separate from the clean points than at shift 8, and the measured error was larger.
Variants and improvements
- Hard filter. Remove the points whose projection on is larger than a threshold from a Gaussian tail bound (Diakonikolas et al. 2019). It has the same guarantee.
- Unknown covariance. Filters for the covariance matrix use the fourth moments, and the mean can then be estimated after whitening.
- Heavy tails. For distributions with bounded covariance, the same filter with threshold of order 1 gives error .
- Faster versions. Near-linear time algorithms replace the repeated eigenvector computation by matrix multiplicative weights.
- Convex programming. The ellipsoid-based separation method of the same paper, and sum-of-squares methods for other distributions. See semidefinite programming.
- Related robust estimators. The Tukey median has error but is hard to compute in high dimension. The geometric median is efficient but has an error that grows like .
When to use it
Use the filter for the mean of high-dimensional data, with in the tens or more, when a fraction of the points may be corrupted in arbitrary ways and the clean distribution has a known or bounded covariance. In low dimension, the minimum covariance determinant and depth-based estimators such as the Tukey median are simpler and well studied. For one coordinate at a time, use the median or a trimmed mean.
Pitfalls
- The threshold needs the covariance. The rule assumes a clean covariance close to . Rescale the data first, or use a version for an unknown covariance.
- Finite samples. The top eigenvalue of the clean sample covariance is about . If is not large compared with , this exceeds the threshold, and the filter keeps removing clean weight.
- Power iteration from below. The Rayleigh quotient of an unconverged vector is below the top eigenvalue, so an early stop can pass line L5 too soon. Iterate until stops changing, or use a full symmetric eigensolver.
- must be known. The threshold depends on . A too small stops the filter early.
- Large . The analysis needs below a small constant, well under the breakdown point of the median.
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/robust-mean-estimation-filter/. The authors are listed in prov/VJ455W.jsonl.
import math
import random
def weighted_mean(xs, w):
total = sum(w)
d = len(xs[0])
return [sum(wi * x[j] for wi, x in zip(w, xs)) / total for j in range(d)]
def weighted_cov(xs, w, mu):
"""sum_i w_i (x_i - mu)(x_i - mu)^T / sum_i w_i, as a list of rows."""
total = sum(w)
d = len(mu)
c = [[0.0] * d for _ in range(d)]
for wi, x in zip(w, xs):
if wi == 0:
continue
z = [a - b for a, b in zip(x, mu)]
for a in range(d):
za = wi * z[a]
row = c[a]
for b in range(a, d):
row[b] += za * z[b]
for a in range(d):
for b in range(a, d):
c[a][b] /= total
c[b][a] = c[a][b]
return c
def top_eigen(c, iters=2000, tol=1e-12, seed=0):
"""The largest eigenvalue and a unit eigenvector of a symmetric PSD matrix, by power iteration.
The Rayleigh quotient of the returned vector is the returned value, so it is a
lower bound on the largest eigenvalue; the loop runs until it stops changing.
"""
d = len(c)
rng = random.Random(seed)
v = [rng.gauss(0.0, 1.0) for _ in range(d)]
norm = math.sqrt(sum(t * t for t in v))
v = [t / norm for t in v]
lam = 0.0
for _ in range(iters):
u = [sum(c[a][b] * v[b] for b in range(d)) for a in range(d)]
norm = math.sqrt(sum(t * t for t in u))
if norm == 0.0:
return 0.0, v
u = [t / norm for t in u]
new = sum(u[a] * sum(c[a][b] * u[b] for b in range(d)) for a in range(d))
v = u
if abs(new - lam) <= tol * max(1.0, new):
lam = new
break
lam = new
return lam, v
def default_threshold(eps, c=3.0):
"""1 + c eps log(1/eps), the stopping level for the top eigenvalue."""
return 1.0 + c * eps * math.log(1.0 / eps)
def filter_mean(xs, eps, threshold=None, max_rounds=None, trace=None):
"""Robust mean of points whose clean part is close to N(mu, I), with an eps fraction corrupted.
The weighted soft filter: while the top eigenvalue of the weighted covariance
exceeds the threshold, every weight w_i is multiplied by 1 - tau_i / tau_max,
where tau_i is the squared projection of x_i - mu_w on the top eigenvector.
If trace is a list, one dict per round is appended to it.
"""
n = len(xs)
if threshold is None:
threshold = default_threshold(eps)
if max_rounds is None:
max_rounds = n
w = [1.0 / n] * n # @line L1
for r in range(max_rounds + 1): # @line L2
mu = weighted_mean(xs, w) # @line L3
lam, v = top_eigen(weighted_cov(xs, w, mu), seed=r) # @line L4
if trace is not None:
trace.append({"round": r, "lambda": lam, "mean": mu, "weights": list(w)})
if lam <= threshold: # @line L5
return mu
tau = [(sum(a * (b - m) for a, b, m in zip(v, x, mu))) ** 2 for x in xs] # @line L6
tau_max = max(t for t, wi in zip(tau, w) if wi > 0) # @line L7
if all(t == tau_max for t, wi in zip(tau, w) if wi > 0):
return mu # @line L7
w = [wi * (1.0 - t / tau_max) if wi > 0 else 0.0 for wi, t in zip(w, tau)] # @line L8
return weighted_mean(xs, w)
def sample_mean(xs):
return weighted_mean(xs, [1.0] * len(xs))
def coordinatewise_median(xs):
d = len(xs[0])
out = []
for j in range(d):
col = sorted(x[j] for x in xs)
m = len(col)
out.append(col[m // 2] if m % 2 else (col[m // 2 - 1] + col[m // 2]) / 2)
return out
def contaminated_gaussian(n, d, eps, shift, seed=0):
"""n points: (1 - eps) n from N(0, I_d) and eps n from N(shift * u, I_d), u = (1, ..., 1)/sqrt(d).
The corrupted points have the same spread as the clean ones, so their norms do
not give them away. Returns (points, is_corrupted).
"""
rng = random.Random(seed)
k = int(round(eps * n))
s = shift / math.sqrt(d)
xs, bad = [], []
for i in range(n):
corrupt = i < k
xs.append([rng.gauss(s if corrupt else 0.0, 1.0) for _ in range(d)])
bad.append(corrupt)
return xs, bad
def norm(v):
return math.sqrt(sum(t * t for t in v))
test_robust_mean_estimation_filter.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-mean-estimation-filter/. The authors are listed in prov/VJ455W.jsonl.
import math
import random
import pytest
from robust_mean_estimation_filter import (
contaminated_gaussian,
coordinatewise_median,
default_threshold,
filter_mean,
norm,
sample_mean,
top_eigen,
weighted_cov,
)
EXAMPLE = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1), (4, 4), (4, 4)]
def taus(xs, mu, v):
return [sum(a * (b - m) for a, b, m in zip(v, x, mu)) ** 2 for x in xs]
def test_example():
trace = []
mu = filter_mean(EXAMPLE, 0.2, trace=trace)
assert default_threshold(0.2) == pytest.approx(1.9657, abs=1e-4)
assert len(trace) == 2
assert trace[0]["mean"] == pytest.approx([0.8, 0.8])
assert trace[0]["lambda"] == pytest.approx(5.72)
# tau_i * 100 = 18, 338, 18, 338, 8, 648, 128, 128, 2048, 2048; the new weights are (1 - tau_i / 20.48) / 10.
want = [2030, 1710, 2030, 1710, 2040, 1400, 1920, 1920, 0, 0]
assert trace[1]["weights"] == pytest.approx([v / 20480 for v in want], abs=1e-7)
assert trace[1]["lambda"] == pytest.approx(0.7737, abs=1e-4)
assert mu == pytest.approx([8 / 123, 8 / 123], abs=1e-6)
assert sample_mean(EXAMPLE) == pytest.approx([0.8, 0.8])
assert coordinatewise_median(EXAMPLE) == [0.5, 0.5]
def test_power_iteration_on_a_known_matrix():
lam, v = top_eigen([[3.16, 2.56], [2.56, 3.16]])
assert lam == pytest.approx(5.72, abs=1e-10)
assert abs(v[0]) == pytest.approx(math.sqrt(0.5), abs=1e-6)
assert v[0] * v[1] > 0
def test_weighted_average_of_tau_is_lambda():
xs, _ = contaminated_gaussian(400, 6, 0.1, 8.0, seed=11)
trace = []
filter_mean(xs, 0.1, trace=trace)
assert len(trace) >= 2
for t in trace:
w, mu = t["weights"], t["mean"]
lam, v = top_eigen(weighted_cov(xs, w, mu), seed=t["round"])
tau = taus(xs, mu, v)
assert sum(wi * ti for wi, ti in zip(w, tau)) / sum(w) == pytest.approx(lam, rel=1e-9)
def test_terminates_even_with_a_zero_threshold():
rng = random.Random(4)
xs = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(25)]
trace = []
mu = filter_mean(xs, 0.1, threshold=0.0, trace=trace)
alive = [sum(1 for w in t["weights"] if w > 0) for t in trace]
assert all(b < a for a, b in zip(alive, alive[1:]))
assert len(trace) <= len(xs)
assert alive[-1] >= 1
assert all(math.isfinite(v) for v in mu)
# All remaining points tie at tau_max: line L7 returns the weighted mean.
assert filter_mean([(-1.0, 0.0), (1.0, 0.0)], 0.1, threshold=0.0) == pytest.approx([0.0, 0.0])
def test_removal_lemma_in_every_round():
"""When the bad points carry at least half of the weighted tau, they lose at least as much weight."""
xs, bad = contaminated_gaussian(1000, 10, 0.1, 8.0, seed=0)
trace = []
filter_mean(xs, 0.1, trace=trace)
held = 0
for t, nxt in zip(trace, trace[1:]):
w, mu = t["weights"], t["mean"]
_, v = top_eigen(weighted_cov(xs, w, mu), seed=t["round"])
tau = taus(xs, mu, v)
good_mass = sum(wi * ti for wi, ti, b in zip(w, tau, bad) if not b)
bad_mass = sum(wi * ti for wi, ti, b in zip(w, tau, bad) if b)
lost_good = sum(a - b2 for a, b2, b in zip(w, nxt["weights"], bad) if not b)
lost_bad = sum(a - b2 for a, b2, b in zip(w, nxt["weights"], bad) if b)
tau_max = max(ti for ti, wi in zip(tau, w) if wi > 0)
assert lost_good == pytest.approx(good_mass / tau_max, rel=1e-6)
assert lost_bad == pytest.approx(bad_mass / tau_max, rel=1e-6)
if good_mass <= bad_mass:
held += 1
assert lost_good <= lost_bad + 1e-12
# Measured: the condition held in rounds 0 and 1 and failed in round 2 of 3.
assert len(trace) == 4 and held == 2
final = trace[-1]["weights"]
lost_good = 0.9 - sum(wi for wi, b in zip(final, bad) if not b)
lost_bad = 0.1 - sum(wi for wi, b in zip(final, bad) if b)
assert lost_good == pytest.approx(0.0386, abs=1e-4)
assert lost_bad == pytest.approx(0.0948, abs=1e-4)
@pytest.mark.parametrize("shift, seed", [(4.0, 0), (4.0, 1), (8.0, 0), (8.0, 1)])
def test_filter_against_the_sample_mean(shift, seed):
"""Measured on 1000 points in 10 dimensions with 10% shifted points; the true mean is 0."""
xs, bad = contaminated_gaussian(1000, 10, 0.1, shift, seed)
err_filter = norm(filter_mean(xs, 0.1))
err_mean = norm(sample_mean(xs))
err_oracle = norm(sample_mean([x for x, b in zip(xs, bad) if not b]))
assert err_mean > 0.09 * shift
assert err_filter < 0.25
assert err_filter < err_mean / 1.7
assert err_filter < err_oracle + 0.15
def test_error_does_not_grow_with_the_dimension():
"""Measured with a shift of 20: the coordinatewise median error grows with d, the filter error does not."""
errs = {}
for d in (5, 10, 20):
xs, bad = contaminated_gaussian(1000, d, 0.1, 20.0, seed=3)
oracle = norm(sample_mean([x for x, b in zip(xs, bad) if not b]))
errs[d] = (norm(filter_mean(xs, 0.1)), norm(coordinatewise_median(xs)), norm(sample_mean(xs)), oracle)
for d, (f, med, mean, oracle) in errs.items():
assert f < oracle + 0.05
assert mean > 1.9
assert errs[5][1] < errs[10][1] < errs[20][1]
assert errs[20][1] > 4 * errs[20][0]
def test_clean_data_gives_the_sample_mean():
xs, _ = contaminated_gaussian(1000, 10, 0.0, 0.0, seed=7)
trace = []
mu = filter_mean(xs, 0.1, trace=trace)
assert len(trace) == 1
assert mu == pytest.approx(sample_mean(xs))
History
Huber (1964) introduced the contamination model. In one dimension the median is optimal in it. In high dimension the Tukey median and related estimators have an error of order , but no efficient algorithm was known to compute them. In 2016, two papers at the same conference gave efficient estimators with nearly dimension-free errors. Diakonikolas, Kamath, Kane, Li, Moitra and Stewart introduced the filter and a convex programming method, with error for Gaussians. Lai, Rao and Vempala gave a spectral method whose error has an extra factor that grows with . The journal version of the first paper appeared in 2019. Diakonikolas and Kane (2023) give a textbook account of this area.
References
- Ilias Diakonikolas, Gautam Kamath, Daniel M. Kane, Jerry Li, Ankur Moitra and Alistair Stewart, Robust estimators in high-dimensions without the computational intractability, SIAM Journal on Computing 48(2), 2019, pp. 742 to 864, Section 5 (the filter for the mean of an identity-covariance Gaussian and its error bound)
- Ilias Diakonikolas, Gautam Kamath, Daniel M. Kane, Jerry Li, Ankur Moitra and Alistair Stewart, Robust estimators in high dimensions without the computational intractability, FOCS 2016, pp. 655 to 664 (the conference version)
- Kevin A. Lai, Anup B. Rao and Santosh Vempala, Agnostic estimation of mean and covariance, FOCS 2016, pp. 665 to 674 (a spectral method with an error that depends on log d)
- Ilias Diakonikolas and Daniel M. Kane, Algorithmic High-Dimensional Robust Statistics, Cambridge University Press, 2023, the chapters on robust mean estimation (stability, the filter and its weighted version)
- Peter J. Huber, Robust estimation of a location parameter, The Annals of Mathematical Statistics 35(1), 1964, pp. 73 to 101 (the contamination model)
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 VJ455W Edit this page History Report an error Markdown