Algorithm Search⌘K

Techniqueintro

Bootstrap

Also called Efron's bootstrap, bootstrap resampling.

Estimate the sampling distribution of a statistic by recomputing it on many samples drawn with replacement from the data. It gives standard errors, bias and intervals.

The bootstrap estimates the sampling distribution of a statistic from one sample. It treats the sample as if it were the population: it draws many new samples of the same size with replacement from the data, computes the statistic on each, and uses the spread of these values as an estimate of the spread of the statistic over repeated real samples. Bradley Efron introduced it in 1979. It gives standard errors, bias estimates and confidence intervals for statistics that have no simple formula, such as a median, a ratio or a correlation.

In plain words

You measured seven mice and computed their median survival time. How much would that median change if you could repeat the study with seven new mice? You cannot repeat the study, so you use the seven numbers you have as a stand-in for all mice.

Put the seven numbers in a hat. Draw one, write it down, and put it back. Do this seven times. Some numbers come out twice and some not at all. That is one "bootstrap sample". Compute its median. Repeat a few thousand times. The medians that you get scatter around, and their spread tells you how much the real median would scatter from study to study. The only work is computing, and the same recipe works for almost any statistic.

When it applies

  • The data X1,…,XnX_1, \ldots, X_n are independent and identically distributed from an unknown distribution FF. The basic bootstrap does not apply to time series, clustered data or other dependent data; see the block bootstrap for stationary series.
  • The quantity of interest is a functional θ=t(F)\theta = t(F), such as a mean, a quantile or a correlation, and the estimate is the plug-in value θ^=t(F^n)\hat\theta = t(\hat F_n), where F^n\hat F_n is the empirical distribution function.
  • The statistic is a smooth function of F^n\hat F_n. Then the bootstrap distribution of n(θ^∗−θ^)\sqrt{n}(\hat\theta^* - \hat\theta) approaches the true distribution of n(θ^−θ)\sqrt{n}(\hat\theta - \theta) (Bickel and Freedman 1981). The mean with finite variance, smooth functions of means, and quantiles of a distribution with a positive density all qualify.
  • It does not apply as is to extremes (the sample maximum), to the mean when the variance is infinite, to parameters on the boundary of the parameter space, or to very small samples. See the pitfalls below.

The template

The holes are the statistic ss, the resampling plan (here: draw from F^n\hat F_n) and the number of replicates bb.

  1. BOOTSTRAP(x_1, ..., x_n, s, b)
  2. 1for j ← 1 to b do
  3. 2x* ← n independent draws from x_1 .. x_n, each with probability 1/n
  4. 3θ*_j ← s(x*)
  5. 4se ← sqrt( Σ_j (θ*_j - θ̄*)² / (b - 1) ) ▷ θ̄* is the mean of the θ*_j
  6. 5bias ← θ̄* - s(x_1, ..., x_n)
  7. 6return θ*_1, ..., θ*_b, se, bias

The plug-in principle. The true distribution of θ^−θ\hat\theta - \theta depends on FF, which is unknown. The bootstrap replaces FF by F^n\hat F_n and θ\theta by θ^=t(F^n)\hat\theta = t(\hat F_n), and uses the distribution of θ^∗−θ^\hat\theta^* - \hat\theta when X1∗,…,Xn∗X_1^*, \ldots, X_n^* are drawn from F^n\hat F_n. This ideal bootstrap distribution is a fixed function of the data. Lines L1 to L3 approximate it by Monte Carlo integration. So there are two errors: the statistical error of replacing FF by F^n\hat F_n, which does not shrink with bb, and the Monte Carlo error, which shrinks like 1/b1/\sqrt{b}.

The ideal bootstrap is a finite distribution. There are nnn^n ordered resamples, each with probability n−nn^{-n}. Only the multiset of drawn indices matters for a symmetric statistic, and there are (2n−1n)\binom{2n - 1}{n} multisets. A multiset in which index ii appears cic_i times has the multinomial probability n!c1!⋯cn!n−n\frac{n!}{c_1! \cdots c_n!} n^{-n}. For n=7n = 7 there are 1716 multisets instead of 823543 ordered resamples, so the ideal bootstrap can be computed exactly for small nn. The code does this, and the tests check it against all nnn^n resamples for n≤5n \le 5.

The mean, exactly. Each Xi∗X_i^* is drawn from F^n\hat F_n, which has mean xˉ\bar x and variance σ^2=1n∑i(xi−xˉ)2\hat\sigma^2 = \frac{1}{n} \sum_i (x_i - \bar x)^2. The draws are independent, so

E∗[Xˉ∗]=xˉ,Var⁡∗(Xˉ∗)=σ^2n=1n2∑i=1n(xi−xˉ)2=n−1n⋅S2n.E^*[\bar X^*] = \bar x, \qquad \operatorname{Var}^*(\bar X^*) = \frac{\hat\sigma^2}{n} = \frac{1}{n^2} \sum_{i=1}^n (x_i - \bar x)^2 = \frac{n - 1}{n} \cdot \frac{S^2}{n}.

So the ideal bootstrap standard error of the mean is (n−1)/n\sqrt{(n - 1)/n} times the usual S/nS/\sqrt{n}. It is slightly too small for small nn, because F^n\hat F_n has less spread than FF on average.

How many replicates. For a standard error, bb between 200 and 1000 is usually enough, since the Monte Carlo error is then small against the statistical error. For the tails of a distribution, as in a percentile interval, use b≥2000b \ge 2000. Efron and Tibshirani (Chapter 6) discuss the rule.

Worked example. The 7 treated mice of Efron and Tibshirani (Table 2.1) lived 94, 197, 16, 38, 99, 141 and 23 days. The mean is 86.86 and S/7=25.24S/\sqrt{7} = 25.24. The exact bootstrap variance of the mean is 187228/343187228/343, so the ideal bootstrap standard error is 23.36=6/7⋅25.2423.36 = \sqrt{6/7} \cdot 25.24. With random.Random(1) and b=2000b = 2000, lines L1 to L4 gave 23.5023.50.

The median is 94, and it has no simple standard error formula. The ideal bootstrap distribution of the median puts probability 0.306 on 94, 0.239 on each of 38 and 99, 0.098 on each of 23 and 141, and 0.010 on each of 16 and 197. Its standard deviation is 37.83, and its mean is 79.73, so the ideal bootstrap bias estimate is −14.27-14.27. With random.Random(1) the Monte Carlo standard error was 36.33 at b=25b = 25, 37.53 at b=200b = 200 and 38.49 at b=4000b = 4000. Here the median has a standard error about 1.6 times that of the mean, because the values next to the median, 38 and 99, are far from it.

Classic examples

  • The standard error of a median, a trimmed mean or a ratio, as in the worked example. For the trimmed mean and the Hodges-Lehmann estimator the formulas are asymptotic and hard to use, but the bootstrap is direct.
  • Confidence intervals. The percentile interval, the bootstrap-t interval and the BCa interval all start from the replicates of line L3.
  • Bias correction. Line L5 estimates the bias; θ^−bias^=2θ^−θˉ∗\hat\theta - \widehat{\text{bias}} = 2\hat\theta - \bar\theta^* is the bias-corrected estimate. The jackknife gives a cheaper estimate of the same bias.
  • Regression. Resample the pairs (xi,yi)(x_i, y_i), which allows any form of heteroscedasticity, or fit once and resample the residuals, which assumes that the errors are exchangeable.
  • Bagging. Bagging and random forests average a predictor over bootstrap samples to reduce its variance. The goal there is a better predictor, not an error estimate.
  • Phylogenetics. The phylogenetic bootstrap resamples alignment columns and reports how often each clade of the tree appears.
  • Parametric models. The parametric bootstrap draws from a fitted model Fθ^F_{\hat\theta} instead of F^n\hat F_n.

Variations

  • Parametric bootstrap. Draw the resamples from a fitted parametric model. It is more accurate when the model is right, and wrong when it is not.
  • Smoothed bootstrap. Draw from a kernel density estimate instead of F^n\hat F_n, which removes the discreteness. It helps for quantiles in small samples.
  • Bayesian bootstrap. Rubin (1981) weights the observations by a Dirichlet(1,…,1)(1, \ldots, 1) vector instead of multinomial counts. The result is a posterior distribution under a noninformative model on the support of the data.
  • Wild bootstrap. For regression with heteroscedastic errors, multiply each residual by an independent random sign or another weight with mean 0 and variance 1, and keep each residual on its own design point.
  • Block bootstrap. Resample blocks of consecutive values to keep the dependence of a time series; see the block bootstrap.
  • Subsampling and the m-out-of-n bootstrap. Draw samples of size m≪nm \ll n, without or with replacement. They are consistent in many cases where the ordinary bootstrap fails; see subsampling.
  • Balanced and antithetic resampling. Arrange the bb resamples so that each observation appears exactly bb times in total. This removes part of the Monte Carlo error at no extra cost (Davison and Hinkley, Chapter 9).
  • Exact enumeration. For small nn, enumerate the (2n−1n)\binom{2n - 1}{n} multisets as the code does, and get the ideal bootstrap without Monte Carlo error.

Pitfalls

  • The maximum. A resample contains the largest observation with probability 1−(1−1/n)n1 - (1 - 1/n)^n, which is 0.6720.672 for n=5n = 5 and tends to 1−1/e=0.6321 - 1/e = 0.632. So the bootstrap distribution of the maximum has an atom of about 63% at the observed maximum, while the true distribution of n(θ−X(n))n(\theta - X_{(n)}) for a uniform [0,θ][0, \theta] sample is continuous (exponential in the limit). The bootstrap is not consistent here (Bickel and Freedman 1981). Use subsampling or a parametric model.
  • Infinite variance. For the mean of a heavy-tailed distribution with infinite variance, the bootstrap distribution has a random limit and does not estimate the sampling distribution (Athreya 1987).
  • Dependent data. Resampling single values of a time series destroys the dependence. For an AR(1) series with coefficient 0.5 the bootstrap variance of the mean is too small by a factor of about 3; see the block bootstrap.
  • The wrong unit. With clustered data (pupils in schools, repeated measures on patients), resample whole clusters.
  • Small samples. The bootstrap cannot add information. With n=5n = 5 the resamples come from only 5 values, and the ideal bootstrap standard error of the mean is still 4/5=0.89\sqrt{4/5} = 0.89 times the usual one.
  • Too few replicates. b=25b = 25 can give a usable standard error but not a usable 2.5% quantile. Report bb and the seed.
  • Not the same as particle resampling. Resampling in particle filters draws from a weighted set of particles to reduce weight degeneracy. It uses the same multinomial draw but has a different purpose.

Code

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.

bootstrap_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bootstrap-method/. The authors are listed in prov/V0JBK5.jsonl.

import itertools
import math
import random
import statistics
from fractions import Fraction
from typing import Callable, Sequence

Statistic = Callable[[Sequence], object]


def resample(x: Sequence, rng: random.Random) -> list:
    """One bootstrap sample: n draws with replacement from x, each index equally likely."""
    n = len(x)
    return [x[rng.randrange(n)] for _ in range(n)]


def bootstrap_replicates(x: Sequence, statistic: Statistic, b: int, rng: random.Random) -> list:
    """The b bootstrap replicates statistic(x*_1), ..., statistic(x*_b)."""
    if len(x) == 0:
        raise ValueError("empty sample")
    if b < 1:
        raise ValueError("b must be at least 1")
    reps = []
    for _ in range(b):  # @line L1
        xs = resample(x, rng)  # @line L2
        reps.append(statistic(xs))  # @line L3
    return reps  # @line L6


def bootstrap_se(reps: Sequence[float]) -> float:
    """The standard deviation of the replicates, with divisor b - 1."""
    return statistics.stdev(reps)  # @line L4


def bootstrap_bias(reps: Sequence[float], theta_hat: float) -> float:
    """The mean of the replicates minus the estimate on the original sample."""
    return statistics.fmean(reps) - theta_hat  # @line L5


def exact_bootstrap_distribution(x: Sequence, statistic: Statistic) -> dict:
    """The ideal bootstrap distribution (b = infinity) as {value: probability}.

    It lists the C(2n - 1, n) multisets of indices instead of the n^n ordered
    resamples. A multiset with counts c_1, ..., c_n has probability
    n! / (c_1! ... c_n!) / n^n. Feasible for n up to about 9.
    """
    n = len(x)
    if n == 0:
        raise ValueError("empty sample")
    total = n**n
    fact_n = math.factorial(n)
    dist: dict = {}
    for idx in itertools.combinations_with_replacement(range(n), n):
        weight = fact_n
        for _, group in itertools.groupby(idx):
            weight //= math.factorial(len(list(group)))
        value = statistic([x[i] for i in idx])
        dist[value] = dist.get(value, 0) + weight
    return {v: Fraction(w, total) for v, w in dist.items()}


def exact_bootstrap_moments(x: Sequence, statistic: Statistic) -> tuple:
    """Mean and variance of the ideal bootstrap distribution. Exact for int or Fraction values."""
    dist = exact_bootstrap_distribution(x, statistic)
    mean = sum(p * v for v, p in dist.items())
    var = sum(p * (v - mean) ** 2 for v, p in dist.items())
    return mean, var


def exact_mean(xs: Sequence) -> Fraction:
    """The sample mean as an exact Fraction, for use as a statistic."""
    return Fraction(sum(Fraction(v) for v in xs), len(xs))
test_bootstrap_method.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bootstrap-method/. The authors are listed in prov/V0JBK5.jsonl.

import itertools
import math
import random
import statistics
from fractions import Fraction

import pytest

from bootstrap_method import (
    bootstrap_bias,
    bootstrap_replicates,
    bootstrap_se,
    exact_bootstrap_distribution,
    exact_bootstrap_moments,
    exact_mean,
    resample,
)

# Survival times in days of the 7 treated mice, Efron and Tibshirani (1993), Table 2.1.
TREATMENT = [94, 197, 16, 38, 99, 141, 23]


def plugin_variance(xs):
    m = exact_mean(xs)
    return sum((Fraction(v) - m) ** 2 for v in xs) / len(xs)


def all_ordered_resamples(x, statistic):
    """Brute force: list all n^n ordered resamples, each with probability n^-n."""
    n = len(x)
    dist = {}
    for idx in itertools.product(range(n), repeat=n):
        v = statistic([x[i] for i in idx])
        dist[v] = dist.get(v, 0) + 1
    return {v: Fraction(c, n**n) for v, c in dist.items()}


@pytest.mark.parametrize("statistic", [exact_mean, statistics.median_low, max, plugin_variance])
def test_multisets_match_all_resamples(statistic):
    rng = random.Random(2)
    for n in range(1, 6):
        x = [rng.randint(0, 6) for _ in range(n)]  # ties are allowed on purpose
        assert exact_bootstrap_distribution(x, statistic) == all_ordered_resamples(x, statistic)


def test_number_of_multisets():
    x = list(range(5))
    count = sum(1 for _ in itertools.combinations_with_replacement(range(5), 5))
    assert count == math.comb(9, 5) == 126
    assert sum(exact_bootstrap_distribution(x, exact_mean).values()) == 1


def test_variance_of_the_mean_is_exact():
    rng = random.Random(4)
    for n in range(1, 7):
        x = [Fraction(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(n)]
        mean, var = exact_bootstrap_moments(x, exact_mean)
        xbar = exact_mean(x)
        assert mean == xbar
        assert var == sum((v - xbar) ** 2 for v in x) / n**2
    mean, var = exact_bootstrap_moments(TREATMENT, exact_mean)
    s2 = statistics.variance(TREATMENT)
    assert math.isclose(float(var), (len(TREATMENT) - 1) / len(TREATMENT) * s2 / len(TREATMENT))


def test_bias_of_the_plugin_variance():
    x = [Fraction(v) for v in (3, 1, 4, 1, 5)]
    mean, _ = exact_bootstrap_moments(x, plugin_variance)
    n = len(x)
    assert mean == Fraction(n - 1, n) * plugin_variance(x)


def test_maximum_has_an_atom():
    for n in range(1, 6):
        x = list(range(10, 10 + n))
        dist = exact_bootstrap_distribution(x, max)
        assert dist[max(x)] == 1 - Fraction(n - 1, n) ** n


def test_monte_carlo_matches_ideal_bootstrap():
    _, var = exact_bootstrap_moments(TREATMENT, statistics.median)
    exact_se = math.sqrt(var)
    reps = bootstrap_replicates(TREATMENT, statistics.median, 4000, random.Random(1))
    assert len(reps) == 4000
    assert abs(bootstrap_se(reps) - exact_se) < 0.06 * exact_se
    mean, _ = exact_bootstrap_moments(TREATMENT, statistics.median)
    bias = bootstrap_bias(reps, statistics.median(TREATMENT))
    assert abs(bias - (mean - 94)) < 4 * exact_se / math.sqrt(4000)


def test_reproducible_and_resample_shape():
    a = bootstrap_replicates(TREATMENT, statistics.fmean, 50, random.Random(7))
    b = bootstrap_replicates(TREATMENT, statistics.fmean, 50, random.Random(7))
    assert a == b
    xs = resample(TREATMENT, random.Random(3))
    assert len(xs) == len(TREATMENT) and set(xs) <= set(TREATMENT)


def test_errors():
    with pytest.raises(ValueError):
        bootstrap_replicates([], statistics.fmean, 10, random.Random(1))
    with pytest.raises(ValueError):
        bootstrap_replicates([1.0], statistics.fmean, 0, random.Random(1))

Exercises

  1. Show that the number of distinct bootstrap multisets of a sample of nn distinct values is (2n−1n)\binom{2n - 1}{n}, and evaluate it for n=10n = 10 and n=20n = 20.
  2. Prove that Var⁡∗(Xˉ∗)=1n2∑i(xi−xˉ)2\operatorname{Var}^*(\bar X^*) = \frac{1}{n^2} \sum_i (x_i - \bar x)^2, and deduce that the ideal bootstrap standard error of the mean is (n−1)/n S/n\sqrt{(n - 1)/n} \, S/\sqrt{n}.
  3. Show that P∗(X(n)∗=x(n))=1−(1−1/n)nP^*(X^*_{(n)} = x_{(n)}) = 1 - (1 - 1/n)^n when the values are distinct, and that the expected number of distinct original values in a resample is n(1−(1−1/n)n)n(1 - (1 - 1/n)^n).
  4. For the plug-in variance σ^2\hat\sigma^2, show that E∗[σ^2∗]=n−1nσ^2E^*[\hat\sigma^{2*}] = \frac{n - 1}{n} \hat\sigma^2. Find the bias-corrected estimate 2σ^2−E∗[σ^2∗]2\hat\sigma^2 - E^*[\hat\sigma^{2*}] and compare it with S2S^2.
  5. The Monte Carlo estimate of the ideal bootstrap probability P∗(θ^∗≤c)P^*(\hat\theta^* \le c) is the fraction of the bb replicates at most cc. Show that its Monte Carlo standard error is at most 1/(2b)1/(2\sqrt{b}), and find the bb that makes it at most 0.0050.005.

References

  1. Bradley Efron, Bootstrap methods, another look at the jackknife, The Annals of Statistics 7(1), 1979, pp. 1 to 26 (the bootstrap, the exact computation for the mean, and the comparison with the jackknife)
  2. Bradley Efron and Robert J. Tibshirani, An Introduction to the Bootstrap, Chapman and Hall, 1993, Chapter 6 (the bootstrap estimate of standard error, Algorithm 6.1 and the choice of B) and Chapter 10 (bootstrap estimates of bias)
  3. A. C. Davison and D. V. Hinkley, Bootstrap Methods and their Application, Cambridge University Press, 1997, Chapter 2 (the basic bootstraps, the plug-in principle and the number of simulations) and Chapter 3 (further ideas, including the smoothed and the parametric bootstrap)
  4. Peter J. Bickel and David A. Freedman, Some asymptotic theory for the bootstrap, The Annals of Statistics 9(6), 1981, pp. 1196 to 1217 (consistency for the mean and for von Mises functionals, and the failure for the sample maximum)
  5. K. B. Athreya, Bootstrap of the mean in the infinite variance case, The Annals of Statistics 15(2), 1987, pp. 724 to 731 (the bootstrap of the mean has a random limit when the variance is infinite)
  6. Larry Wasserman, All of Statistics, Springer, 2004, Chapter 8 (the bootstrap, bootstrap variance estimation and intervals)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises