Algorithm Search⌘K

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
Properties
deterministicnot exact in exact arithmeticnot in placeofflinenot randomized
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 ε\varepsilon 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 λ\lambda and its eigenvector vv. If λ\lambda 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 vv. For a Gaussian with identity covariance, Diakonikolas et al. (2019) prove an error of O(εlog⁡(1/ε))O(\varepsilon\sqrt{\log(1/\varepsilon)}), with no factor that grows with the dimension dd. In the contamination model the sample mean can be moved arbitrarily far, and the coordinatewise median has an error that grows like εd\varepsilon\sqrt d.

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 NN points x1,…,xN∈Rdx_1, \ldots, x_N \in \mathbb R^d and the fraction ε<1/2\varepsilon < 1/2. In the strong contamination model an adversary draws NN points from N(μ,Id)N(\mu, I_d), sees them, and replaces any εN\varepsilon N of them. The goal is an estimate μ^\hat\mu with a small ∥μ^−μ∥\|\hat\mu - \mu\|. Write GG for the indices of the clean points and BB for the replaced ones. The algorithm does not know GG and BB.

For weights wi≥0w_i \ge 0 with W=∑iwi>0W = \sum_i w_i > 0, put μw=1W∑iwixi\mu_w = \frac1W\sum_i w_i x_i and Σw=1W∑iwi(xi−μw)(xi−μw)T\Sigma_w = \frac1W\sum_i w_i(x_i - \mu_w)(x_i - \mu_w)^{\mathsf T}. The threshold is θ=1+Cεlog⁡(1/ε)\theta = 1 + C\varepsilon\log(1/\varepsilon). The implementation uses C=3C = 3.

The algorithm

  1. FILTER(x_1..x_N, ε, θ)
  2. 1w_i ← 1/N for every i
  3. 2repeat
  4. 3μ ← Σ w_i x_i / Σ w_i
  5. 4(λ, v) ← the top eigenvalue and a unit eigenvector of Σ_w, by power iteration
  6. 5if λ ≤ θ then return μ
  7. 6τ_i ← (vᵀ(x_i − μ))² for every i
  8. 7τ_max ← max{τ_i : w_i > 0}; if τ_i = τ_max for every i with w_i > 0 then return μ
  9. 8w_i ← w_i (1 − τ_i / τ_max) for every i

Line L8 is the soft version of the filter. The point that lies farthest along vv gets weight 0, and every other point loses a part of its weight in proportion to τi\tau_i. Line L7 handles the case where all remaining points lie at the same distance along vv.

Example

Take N=10N = 10 points in the plane with ε=0.2\varepsilon = 0.2: the eight clean points (±1,0)(\pm1, 0), (0,±1)(0, \pm1), (1,1)(1, 1), (−1,−1)(-1, -1), (1,−1)(1, -1), (−1,1)(-1, 1), which have mean (0,0)(0, 0), and two planted points at (4,4)(4, 4). The threshold is θ=1+3⋅0.2log⁡5=1.966\theta = 1 + 3 \cdot 0.2\log 5 = 1.966.

Round 0. All weights are 0.10.1. The mean is (0.8,0.8)(0.8, 0.8), and

Σw=(3.162.562.563.16),λ=5.72,v=(1,1)/2.\Sigma_w = \begin{pmatrix} 3.16 & 2.56 \\ 2.56 & 3.16 \end{pmatrix}, \qquad \lambda = 5.72, \qquad v = (1, 1)/\sqrt2.

Since λ>θ\lambda > \theta, the filter acts. τi=(xi,1+xi,2−1.6)2/2\tau_i = (x_{i,1} + x_{i,2} - 1.6)^2/2:

point (1,0) (−1,0) (0,1) (0,−1) (1,1) (−1,−1) (1,−1) (−1,1) (4,4) (4,4)
τi\tau_i 0.18 3.38 0.18 3.38 0.08 6.48 1.28 1.28 20.48 20.48
new wiw_i 0.0991 0.0835 0.0991 0.0835 0.0996 0.0684 0.0938 0.0938 0 0

The weighted mean of τ\tau is 57.2/10=5.72=λ57.2/10 = 5.72 = \lambda. The two planted points carry 40.9640.96 of the weighted sum 57.257.2, more than half. They lose their whole weight 0.20.2, and the clean points lose 16.24/204.8=0.079316.24/204.8 = 0.0793 together.

Round 1. The total weight is 0.72070.7207. The weighted mean is (8/123,8/123)≈(0.065,0.065)(8/123, 8/123) \approx (0.065, 0.065), and λ=0.774≤θ\lambda = 0.774 \le \theta, so the filter returns it. For comparison, the sample mean is (0.8,0.8)(0.8, 0.8) and the coordinatewise median is (0.5,0.5)(0.5, 0.5). The output is not exactly (0,0)(0, 0), because the clean points that lay far along vv 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.

  • λ\lambda is the weighted mean of τ\tau. ∑iwiτi/W=vTΣwv=λ\sum_i w_i\tau_i/W = v^{\mathsf T}\Sigma_w v = \lambda.
  • Termination. In a round that updates the weights, the points with τi=τmax⁡\tau_i = \tau_{\max} 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 NN rounds with W>0W > 0.
  • Removal lemma. Point ii loses wiτi/τmax⁡w_i\tau_i/\tau_{\max}. So the good points lose ∑Gwiτi/τmax⁡\sum_G w_i\tau_i/\tau_{\max} and the bad points lose ∑Bwiτi/τmax⁡\sum_B w_i\tau_i/\tau_{\max}. If the bad points carry at least half of the weighted τ\tau, 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 ε\varepsilon, so they keep a weight of at least 1−2ε1 - 2\varepsilon.
  • The error bound (cited). For an ε\varepsilon-corrupted sample of N(μ,Id)N(\mu, I_d) of size of order d/ε2d/\varepsilon^2 up to logarithmic factors, with high probability the condition of the removal lemma holds while λ\lambda is above a threshold of the form 1+Cεlog⁡(1/ε)1 + C\varepsilon\log(1/\varepsilon), and a weighted mean with λ\lambda below it and good weight at least 1−2ε1 - 2\varepsilon is within O(εlog⁡(1/ε))O(\varepsilon\sqrt{\log(1/\varepsilon)}) of μ\mu (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 O(εlog⁡(1/ε))O(\varepsilon\sqrt{\log(1/\varepsilon)}) 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 x1,…,xN∈Rdx_1, \ldots, x_N \in \mathbb R^d, and the weights are wi≥0w_i \ge 0 with W=∑iwi>0W = \sum_i w_i > 0. Put μw=1W∑iwixi\mu_w = \frac1W\sum_i w_i x_i and Σw=1W∑iwi(xi−μw)(xi−μw)T\Sigma_w = \frac1W\sum_i w_i(x_i - \mu_w)(x_i - \mu_w)^{\mathsf T}. In a round, vv is a unit vector and λ=vTΣwv\lambda = v^{\mathsf T}\Sigma_w v; power iteration returns such a pair, with λ\lambda the Rayleigh quotient of vv. Put τi=(vT(xi−μw))2\tau_i = (v^{\mathsf T}(x_i - \mu_w))^2, and let τmax⁡\tau_{\max} be the largest τi\tau_i over the indices with wi>0w_i > 0. Let θ≥0\theta \ge 0 be the threshold.

Lemma 1 (the weighted mean of τ\tau is λ\lambda). 1W∑iwiτi=λ\frac1W\sum_i w_i\tau_i = \lambda.

Proof. τi=vT(xi−μw)(xi−μw)Tv\tau_i = v^{\mathsf T}(x_i - \mu_w)(x_i - \mu_w)^{\mathsf T}v. Sum with weights wi/Ww_i/W and use the definition of Σw\Sigma_w. □\square

Lemma 2 (the update). In a round that reaches line L8, every new weight wi′=wi(1−τi/τmax⁡)w_i' = w_i(1 - \tau_i/\tau_{\max}) satisfies 0≤wi′≤wi0 \le w_i' \le w_i. At least one index with wi>0w_i > 0 gets wi′=0w_i' = 0, and at least one keeps wi′>0w_i' > 0.

Proof. Line L7 did not return, so the indices with wi>0w_i > 0 do not all have τi=τmax⁡\tau_i = \tau_{\max}. So τmax⁡>0\tau_{\max} > 0, because τmax⁡\tau_{\max} is at least every such τi≥0\tau_i \ge 0 and one of them is smaller. For wi>0w_i > 0, 0≤τi≤τmax⁡0 \le \tau_i \le \tau_{\max}, so 0≤1−τi/τmax⁡≤10 \le 1 - \tau_i/\tau_{\max} \le 1. For wi=0w_i = 0, wi′=0w_i' = 0. An index with wi>0w_i > 0 and τi=τmax⁡\tau_i = \tau_{\max} gets wi′=0w_i' = 0. An index with wi>0w_i > 0 and τi<τmax⁡\tau_i < \tau_{\max} keeps wi′>0w_i' > 0. □\square

Theorem 1 (termination). The loop returns after at most NN rounds, and W>0W > 0 in every round, so μw\mu_w and Σw\Sigma_w are always defined.

Proof. At the start every weight is 1/N>01/N > 0. By Lemma 2, each round that does not return keeps a positive weight, so W>0W > 0 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 NN and stays at least 1, so at most N−1N - 1 rounds can update the weights. The next round returns at line L5 or L7. □\square

Lemma 3 (removal). Let the indices be split into good ones GG and bad ones BB. In a round that reaches line L8, the weight removed from GG is 1τmax⁡∑i∈Gwiτi\frac{1}{\tau_{\max}}\sum_{i \in G} w_i\tau_i, and the weight removed from BB is 1τmax⁡∑i∈Bwiτi\frac{1}{\tau_{\max}}\sum_{i \in B} w_i\tau_i. So if

∑i∈Gwiτi≤∑i∈Bwiτi,\sum_{i \in G} w_i\tau_i \le \sum_{i \in B} w_i\tau_i,

then the round removes at most as much weight from GG as from BB.

Proof. For wi>0w_i > 0, wi−wi′=wiτi/τmax⁡w_i - w_i' = w_i\tau_i/\tau_{\max}, and for wi=0w_i = 0 both sides are 0. Sum over GG and over BB. □\square

By Lemma 1, the condition of Lemma 3 says that the bad points carry at least half of the weighted mean λ\lambda of τ\tau.

Corollary 1 (the good weight is kept). Suppose ∣B∣≤εN|B| \le \varepsilon N and the condition of Lemma 3 holds in every round that updates the weights. Then at the end

∑i∈G(1N−wi)≤∑i∈B(1N−wi)≤ε,so∑i∈Gwi≥1−2ε.\sum_{i \in G}\Bigl(\frac1N - w_i\Bigr) \le \sum_{i \in B}\Bigl(\frac1N - w_i\Bigr) \le \varepsilon, \qquad\text{so}\qquad \sum_{i \in G} w_i \ge 1 - 2\varepsilon.

Proof. Add the inequality of Lemma 3 over the rounds. The total weight removed from BB is at most the initial weight ∣B∣/N≤ε|B|/N \le \varepsilon of BB. The good points start with weight ∣G∣/N≥1−ε|G|/N \ge 1 - \varepsilon. □\square

What is cited. For an ε\varepsilon-corrupted sample of N(μ,Id)N(\mu, I_d) with NN of order d/ε2d/\varepsilon^2 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 λ\lambda is above a threshold of the form 1+Cεlog⁡(1/ε)1 + C\varepsilon\log(1/\varepsilon), the bad points carry most of the weighted τ\tau, so Lemma 3 applies. Second, when λ\lambda is below the threshold and the good weight is at least 1−2ε1 - 2\varepsilon, the weighted mean satisfies ∥μw−μ∥=O(εlog⁡(1/ε))\|\mu_w - \mu\| = O(\varepsilon\sqrt{\log(1/\varepsilon)}). With Corollary 1 these give the error bound. The constant CC, 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 O(nd)O(nd) and the weighted covariance matrix O(nd2)O(nd^2). Power iteration with kk steps costs O(kd2)O(kd^2). The projections cost O(nd)O(nd). So a round costs O(nd2+kd2)O(nd^2 + kd^2). Without forming Σw\Sigma_w, each power iteration step can multiply by Σw\Sigma_w in O(nd)O(nd), for O(knd)O(knd) in a round.
  • Rounds. At most nn rounds, by the termination proof, so the worst case is O(n(nd2+kd2))O(n(nd^2 + kd^2)). In the tests 1 to 4 rounds were enough, because a cluster of planted points loses most of its weight in one round.
  • Space. O(n+d2)O(n + d^2) for the weights and the covariance matrix.

Properties

Proved on this page: termination, the identity for λ\lambda, 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 dd (cited). O(εlog⁡(1/ε))O(\varepsilon\sqrt{\log(1/\varepsilon)}) for N(μ,Id)N(\mu, I_d), compared with Ω(ε)\Omega(\varepsilon) for any estimator, Θ(εd)\Theta(\varepsilon\sqrt d) in the worst case for the coordinatewise median, and no bound for the sample mean.
  • Measured against the sample mean. 1000 points in d=10d = 10 with 10% planted points from N(s u,I)N(s\,u, I), u=(1,…,1)/du = (1, \ldots, 1)/\sqrt d. The table shows ∥μ^−μ∥\|\hat\mu - \mu\| for two seeds. The last column is the mean of the clean points only, which no estimator can know.
shift ss 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 d=5,10,20d = 5, 10, 20 were 0.063,0.124,0.1280.063, 0.124, 0.128, close to the mean of the clean points (0.045,0.116,0.1320.045, 0.116, 0.132). The coordinatewise median errors grew: 0.309,0.465,0.5840.309, 0.465, 0.584. 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 τ\tau in rounds 0 and 1, but not in round 2. Over the whole run the good points lost 0.03860.0386 of weight and the bad points 0.09480.0948.
  • Clean data. On uncorrupted data with λ≤θ\lambda \le \theta 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 vv 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 O(ε)O(\sqrt\varepsilon).
  • 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 O(ε)O(\varepsilon) but is hard to compute in high dimension. The geometric median is efficient but has an error that grows like εd\varepsilon\sqrt d.

When to use it

Use the filter for the mean of high-dimensional data, with dd 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 λ≤1+Cεlog⁡(1/ε)\lambda \le 1 + C\varepsilon\log(1/\varepsilon) assumes a clean covariance close to II. Rescale the data first, or use a version for an unknown covariance.
  • Finite samples. The top eigenvalue of the clean sample covariance is about (1+d/N)2(1 + \sqrt{d/N})^2. If NN is not large compared with dd, 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 λ\lambda stops changing, or use a full symmetric eigensolver.
  • ε\varepsilon must be known. The threshold depends on ε\varepsilon. A too small ε\varepsilon stops the filter early.
  • Large ε\varepsilon. The analysis needs ε\varepsilon below a small constant, well under the breakdown point 1/21/2 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.

robust_mean_estimation_filter.pyI0RawGitHub
# 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 ε\varepsilon, 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 O(εlog⁡(1/ε))O(\varepsilon\sqrt{\log(1/\varepsilon)}) for Gaussians. Lai, Rao and Vempala gave a spectral method whose error has an extra factor that grows with log⁡d\log d. The journal version of the first paper appeared in 2019. Diakonikolas and Kane (2023) give a textbook account of this area.

References

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • 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