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 are independent and identically distributed from an unknown distribution . 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 , such as a mean, a quantile or a correlation, and the estimate is the plug-in value , where is the empirical distribution function.
- The statistic is a smooth function of . Then the bootstrap distribution of approaches the true distribution of (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 , the resampling plan (here: draw from ) and the number of replicates .
BOOTSTRAP(x_1, ..., x_n, s, b)- 1
for j ← 1 to b do - 2
x* ← n independent draws from x_1 .. x_n, each with probability 1/n - 3
θ*_j ← s(x*) - 4
se ← sqrt( Σ_j (θ*_j - θ̄*)² / (b - 1) ) ▷ θ̄* is the mean of the θ*_j - 5
bias ← θ̄* - s(x_1, ..., x_n) - 6
return θ*_1, ..., θ*_b, se, bias
The plug-in principle. The true distribution of depends on , which is unknown. The bootstrap replaces by and by , and uses the distribution of when are drawn from . 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 by , which does not shrink with , and the Monte Carlo error, which shrinks like .
The ideal bootstrap is a finite distribution. There are ordered resamples, each with probability . Only the multiset of drawn indices matters for a symmetric statistic, and there are multisets. A multiset in which index appears times has the multinomial probability . For there are 1716 multisets instead of 823543 ordered resamples, so the ideal bootstrap can be computed exactly for small . The code does this, and the tests check it against all resamples for .
The mean, exactly. Each is drawn from , which has mean and variance . The draws are independent, so
So the ideal bootstrap standard error of the mean is times the usual . It is slightly too small for small , because has less spread than on average.
How many replicates. For a standard error, 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 . 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 . The exact bootstrap variance of the mean is , so the ideal bootstrap standard error is . With random.Random(1) and , lines L1 to L4 gave .
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 . With random.Random(1) the Monte Carlo standard error was 36.33 at , 37.53 at and 38.49 at . 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; is the bias-corrected estimate. The jackknife gives a cheaper estimate of the same bias.
- Regression. Resample the pairs , 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 instead of .
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 , which removes the discreteness. It helps for quantiles in small samples.
- Bayesian bootstrap. Rubin (1981) weights the observations by a Dirichlet 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 , without or with replacement. They are consistent in many cases where the ordinary bootstrap fails; see subsampling.
- Balanced and antithetic resampling. Arrange the resamples so that each observation appears exactly times in total. This removes part of the Monte Carlo error at no extra cost (Davison and Hinkley, Chapter 9).
- Exact enumeration. For small , enumerate the 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 , which is for and tends to . So the bootstrap distribution of the maximum has an atom of about 63% at the observed maximum, while the true distribution of for a uniform 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 the resamples come from only 5 values, and the ideal bootstrap standard error of the mean is still times the usual one.
- Too few replicates. can give a usable standard error but not a usable 2.5% quantile. Report 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.
# 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
- Show that the number of distinct bootstrap multisets of a sample of distinct values is , and evaluate it for and .
- Prove that , and deduce that the ideal bootstrap standard error of the mean is .
- Show that when the values are distinct, and that the expected number of distinct original values in a resample is .
- For the plug-in variance , show that . Find the bias-corrected estimate and compare it with .
- The Monte Carlo estimate of the ideal bootstrap probability is the fraction of the replicates at most . Show that its Monte Carlo standard error is at most , and find the that makes it at most .
References
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag V0JBK5 Edit this page History Report an error Markdown