Algorithmcore
Bootstrap percentile interval
Also called percentile bootstrap.
A confidence interval whose endpoints are the alpha/2 and 1 - alpha/2 quantiles of the bootstrap replicates of the statistic. Simple and transformation respecting, but only first-order accurate.
- Time
- Θ(b n + b log b) worstΘ(b n) best
- Space
- Θ(b + n) extra
- Where
- b = the number of bootstrap replicates; n = the sample size
- Model
- Real RAM
- Properties
- randomizednot exactofflinerandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bradley Efron, 1979
The bootstrap percentile interval is the simplest bootstrap confidence interval. Draw bootstrap samples, compute the statistic on each, and take the and quantiles of the values as the endpoints. The interval needs no standard error formula, it follows the skewness of the bootstrap distribution, and it respects monotone transformations: the interval for is the log of the interval for . Its coverage error for each endpoint is of order , so it is first-order accurate, and its coverage is a measured property, not a proved one.
In plain words
You computed an average from ten numbers and want a range of plausible values for the true average. Make two thousand bootstrap samples by drawing ten numbers from your data with replacement, and compute the average of each. Sort the two thousand averages. Cut off the lowest 2.5% and the highest 2.5%. The smallest and the largest of the averages that are left are the ends of a 95% interval.
If the bootstrap averages have a long tail to the right, the interval is longer on the right too, which a "plus or minus" interval cannot do. The method is easy, but with small samples it often covers the true value less often than it claims.
The problem
Input. A sample , independent and identically distributed from an unknown ; a statistic with , which estimates ; a level ; and a number of replicates .
Output. An interval that should contain with probability close to .
Definition. Let be the bootstrap distribution function of , the law of when is a sample of size from . With the generalized inverse , the ideal percentile interval is
The algorithm replaces by the empirical distribution of Monte Carlo replicates.
The algorithm
PERCENTILE-INTERVAL(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
sort θ*_1, ..., θ*_b into θ*_(1) ≤ ... ≤ θ*_(b) - 5
L ← θ*_(k), k = max(1, ⌈b α/2⌉) - 6
U ← θ*_(k'), k' = ⌈b (1 - α/2)⌉ - 7
return [L, U]
Lines L5 and L6 compute exactly: the empirical distribution of values reaches for the first time at the -th smallest value. The code converts to a fraction before the ceiling, so that is not rounded to a value just above an integer. Two quick selections, as in quickselect, can replace the sort of line L4.
Example
Take the right-skewed sample of values
with mean , and . Let be the mean, and , with random.Random(1). Lines L5 and L6 use and . The 50th smallest replicate is 1.80 and the 1950th is 6.31, so the interval is
It reaches above and below, which follows the right skew of the data. On the same data, the t interval is , the normal interval with the bootstrap standard error is , the bootstrap-t interval is , and the BCa interval is , all with the same seed.
Transformation. Running the same code with the statistic and the same seed gives the interval exactly, because the logarithm does not change the order of the replicates. The tests check this, and also that the statistic gives when and , where the two order statistics and are mirror images. For a decreasing transformation, other choices of can move an endpoint by one order statistic.
Measured coverage. For samples from the exponential law with mean 1, 1000 data sets of each size with (seeds 101 and 102) gave these coverages for the true mean at the nominal level 0.95:
| method | ||
|---|---|---|
| percentile | 0.869 | 0.911 |
| t interval | 0.911 | 0.924 |
| bootstrap-t | 0.943 | 0.950 |
| BCa | 0.884 | 0.916 |
The percentile interval misses mostly on one side: at its upper end was below the true mean in of the data sets and its lower end above it in . The Monte Carlo standard error of each coverage is about .
Correctness
The proof is in proofs/correctness.md. What is proved:
- Lines L5 and L6 return and , and as they converge to the ideal endpoints and wherever is strictly increasing at these quantiles.
- The interval respects transformations: for a strictly increasing , the interval computed for is .
- If there is an increasing transformation such that has a continuous distribution that is symmetric about 0 and does not depend on , and the bootstrap reproduces it, so that also has law , then the ideal percentile interval has coverage exactly . The method does not need to know .
What is not proved: the coverage for a real . The normalizing transformation exists only approximately, and the coverage error of each endpoint is of order (Hall 1988). The table above is a measurement.
Proof: The percentile interval computes the bootstrap quantiles and respects monotone transformationsfull
We use the pseudocode of the page. The data are fixed. is the bootstrap distribution function, where is the law of a resample of size from . is the empirical distribution function of the replicates. For any distribution function , .
This file proves what the algorithm computes and when the ideal interval has exact coverage. It does not prove a coverage level for a general . That coverage is measured on the page.
Claim 1 (lines L5 and L6 compute the empirical quantiles). For , with .
Proof. Since , . At at least replicates are , so . For at most replicates are , so , because by the definition of the ceiling. So the infimum is . With and this is lines L5 and L6. The max(1, ...) in line L5 changes nothing for ; it only keeps the index valid.
Claim 2 (the Monte Carlo endpoints converge to the ideal ones). Let be a number that does not take as a value. Then, with probability 1 over the resampling, for all large .
Proof. is a step function with finitely many jumps, at the values that takes on the resamples, and every replicate is one of these values. Let . Then , and since is not a value of , . If , then by the definition of the infimum. By the strong law of large numbers, and almost surely. So for all large , and for every , because is constant between consecutive values. So . If , no replicate is below , and the same argument applies with only the first inequality.
The values of are multiples of , so the condition excludes only finitely many . The tests compute exactly over all resamples for and check that the ideal interval of the implementation, which weights the multisets of indices, returns and .
Claim 3 (transformation respecting). Let be strictly increasing on a set that contains every value of . Run the algorithm twice with the same random numbers, once with the statistic and once with . If the first run returns , the second returns .
Proof. Line L2 draws the resample indices without looking at the statistic, so both runs use the same resamples, and the -th replicate of the second run is . A strictly increasing keeps the order, so the -th smallest of the is . Lines L5 and L6 use the same and in both runs.
For a strictly decreasing the same argument gives , up to the index of the order statistic: the -th smallest of is . With an integer, , so the two endpoints are adjacent order statistics, not equal ones. The tests use and , where and , and there the result is exact.
Claim 4 (exact coverage under a normalizing transformation). Suppose there is a continuous, strictly increasing and a continuous, strictly increasing distribution function , symmetric about 0, such that
Then the ideal interval contains with probability exactly .
Proof. Write , so by symmetry. By the second assumption , so . Because is increasing,
where the last step uses . By the first assumption this event has probability .
The algorithm does not need to know ; this is the reason for the method. The symmetry of is necessary: without it the correct interval uses and in the reverse order, which is the basic interval of the page. The BCa interval relaxes both assumptions of Claim 4 by allowing a bias and a standard deviation that changes with .
What is not proved. For a real the bootstrap distribution is discrete and no exact exists. Under smoothness conditions, Edgeworth expansions show that each one-sided endpoint has coverage error of order (Hall 1988; Hall 1992, Chapter 3). The coverages on the page come from a simulation with a stated seed. They are measurements with a Monte Carlo standard error of about , not theorems.
Cost. The loop of lines L1 to L3 runs times. Each pass draws indices and evaluates once. Line L4 sorts numbers in comparisons, and lines L5 and L6 take constant time. So the time is , where is the cost of , and the extra space is .
Complexity
Each of the replicates draws indices and evaluates the statistic, which for the mean costs . The sort of line L4 costs . So the time is , and with two linear-time selections instead of the sort. The replicates take space and one resample . For a statistic that costs , replace by in the first term.
Properties
- Transformation respecting. The interval for is applied to the interval for , for every strictly increasing . The t interval and the normal interval do not have this property.
- Range preserving. The endpoints are values that the statistic takes, so an interval for a correlation stays in and one for a variance stays positive.
- First-order accurate. The coverage error of each one-sided endpoint is . In an equal-tailed two-sided interval the leading errors of the two ends partly cancel, but the interval can still be badly unbalanced, as the table shows.
- Too narrow in small samples. For the mean, the bootstrap distribution has variance and uses normal-like quantiles instead of quantiles, so the interval is short by a factor of about , which is for .
- Monte Carlo error. The endpoints are extreme order statistics of the replicates, so they need more replicates than a standard error: use , and better or more.
Variants and improvements
- Basic (reverse percentile) interval. . It assumes that and have the same law, so it reflects the skewness the other way. It is not transformation respecting.
- BCa interval. Moves the two levels and to correct for bias and skewness, keeps the transformation-respecting property, and is second-order accurate; see the BCa interval.
- Bootstrap-t interval. Studentizes each replicate; second-order accurate when a good standard error is available; see the bootstrap-t interval.
- Ideal percentile interval. For small the bootstrap distribution can be enumerated over the multisets of indices, which removes the Monte Carlo error. The tests compare the code with the enumeration of all resamples for .
- Phylogenetics. The phylogenetic bootstrap reports the fraction of replicates that contain a clade, which is a percentile-type support value rather than an interval.
- Subsampling intervals. When the bootstrap is not consistent, quantiles of a subsampling distribution give valid intervals; see subsampling.
When to use it
Use it for a quick interval when the bootstrap distribution looks roughly symmetric after some monotone transformation, when the parameter has a restricted range, and when is moderate or large. For a mean or another statistic with a good standard error formula, the bootstrap-t interval covers better in skewed small samples. For a general smooth statistic, the BCa interval is the usual improvement at little extra cost.
Pitfalls
- Small samples. At from an exponential law, the nominal 95% interval covered the mean in only of the data sets.
- Statistics for which the bootstrap fails. For the sample maximum of a uniform sample the upper endpoint is always the observed maximum, and the interval cannot contain larger values; the method inherits every failure of the bootstrap.
- Biased statistics. If is biased, the bootstrap distribution is centred near plus the bias, and the percentile interval moves the wrong way. The BCa correction handles this.
- Interpolating quantiles. Library quantile functions often interpolate between order statistics. That gives slightly different endpoints and loses the exact transformation-respecting property. Use the order statistic, as lines L5 and L6 do.
- Too few replicates. With the 2.5% quantile is the 5th smallest value, and its Monte Carlo error is large.
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/bootstrap-percentile-interval/. The authors are listed in prov/3JWEPT.jsonl.
import itertools
import math
import random
from fractions import Fraction
from typing import Callable, Sequence
def empirical_quantile(sorted_values: Sequence, p) -> object:
"""G^{-1}(p) = inf{t : G(t) >= p} for the empirical law of the sorted values.
This is the ceil(b p)-th smallest value (1-based) for 0 < p <= 1, and the
smallest value for p = 0. p may be a float or a Fraction.
"""
b = len(sorted_values)
if b == 0:
raise ValueError("no values")
if not 0 <= p <= 1:
raise ValueError("p must be in [0, 1]")
k = max(1, math.ceil(Fraction(p) * b))
return sorted_values[k - 1]
def percentile_interval(
x: Sequence[float],
statistic: Callable[[Sequence[float]], float],
alpha: float,
b: int,
rng: random.Random,
) -> tuple:
"""The 1 - alpha bootstrap percentile interval [G^{-1}(alpha/2), G^{-1}(1 - alpha/2)].
G is the empirical distribution of b bootstrap replicates of the statistic.
"""
if not 0 < alpha < 1:
raise ValueError("alpha must be in (0, 1)")
n = len(x)
if n == 0 or b < 1:
raise ValueError("need data and b >= 1")
reps = []
for _ in range(b): # @line L1
xs = [x[rng.randrange(n)] for _ in range(n)] # @line L2
reps.append(statistic(xs)) # @line L3
reps.sort() # @line L4
lo = empirical_quantile(reps, alpha / 2) # @line L5
hi = empirical_quantile(reps, 1 - alpha / 2) # @line L6
return lo, hi # @line L7
def ideal_bootstrap_cdf(x: Sequence, statistic: Callable) -> list:
"""The ideal bootstrap law of the statistic as a sorted list of (value, probability).
It lists the C(2n - 1, n) multisets of indices with multinomial weights.
"""
n = len(x)
fact_n = math.factorial(n)
dist: dict = {}
for idx in itertools.combinations_with_replacement(range(n), n):
w = fact_n
for _, g in itertools.groupby(idx):
w //= math.factorial(len(list(g)))
v = statistic([x[i] for i in idx])
dist[v] = dist.get(v, 0) + w
return sorted((v, Fraction(w, n**n)) for v, w in dist.items())
def ideal_percentile_interval(x: Sequence, statistic: Callable, alpha) -> tuple:
"""The percentile interval of the ideal bootstrap (b = infinity), for small n."""
law = ideal_bootstrap_cdf(x, statistic)
def quantile(p):
acc = Fraction(0)
for v, w in law:
acc += w
if acc >= p:
return v
return law[-1][0]
a = Fraction(alpha)
return quantile(a / 2), quantile(1 - a / 2)
test_bootstrap_percentile_interval.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bootstrap-percentile-interval/. The authors are listed in prov/3JWEPT.jsonl.
import itertools
import math
import random
import statistics
from fractions import Fraction
import pytest
from bootstrap_percentile_interval import (
empirical_quantile,
ideal_percentile_interval,
percentile_interval,
)
SKEWED = [0.4, 0.9, 1.3, 1.6, 2.2, 2.8, 3.5, 4.9, 7.6, 13.1]
def exact_mean(xs):
return Fraction(sum(Fraction(v) for v in xs), len(xs))
def brute_quantile(values, p):
"""inf{t : #{v <= t} / b >= p}, searched over the values themselves."""
b = len(values)
return min(t for t in values if Fraction(sum(1 for v in values if v <= t), b) >= p)
def test_quantile_rule_matches_definition():
rng = random.Random(1)
for b in range(1, 30):
values = sorted(rng.randint(0, 9) for _ in range(b))
for num in range(1, 41):
p = Fraction(num, 40)
assert empirical_quantile(values, p) == brute_quantile(values, p)
def test_ideal_interval_matches_all_resamples():
rng = random.Random(2)
for n in range(1, 6):
x = [Fraction(rng.randint(0, 20), 2) for _ in range(n)]
for alpha in (Fraction(1, 10), Fraction(1, 5)):
law = {}
for idx in itertools.product(range(n), repeat=n):
v = exact_mean([x[i] for i in idx])
law[v] = law.get(v, 0) + Fraction(1, n**n)
vals = sorted(law)
def q(p):
acc = Fraction(0)
for v in vals:
acc += law[v]
if acc >= p:
return v
assert ideal_percentile_interval(x, exact_mean, alpha) == (q(alpha / 2), q(1 - alpha / 2))
def test_transformation_respecting():
lo, hi = percentile_interval(SKEWED, statistics.fmean, 0.1, 999, random.Random(5))
llo, lhi = percentile_interval(SKEWED, lambda xs: math.log(statistics.fmean(xs)), 0.1, 999, random.Random(5))
assert llo == math.log(lo) and lhi == math.log(hi)
nlo, nhi = percentile_interval(SKEWED, lambda xs: -statistics.fmean(xs), 0.1, 999, random.Random(5))
assert (nlo, nhi) == (-hi, -lo)
def test_example_on_the_page():
lo, hi = percentile_interval(SKEWED, statistics.fmean, 0.05, 2000, random.Random(1))
assert lo < statistics.fmean(SKEWED) < hi
assert hi - statistics.fmean(SKEWED) > statistics.fmean(SKEWED) - lo # skewed to the right
def test_coverage_is_measured_not_proved():
"""Coverage for the mean of N(0, 1) samples of size 20 is near 0.95, up to O(1/n) and noise."""
rng = random.Random(8)
r, b, alpha = 400, 400, 0.05
hits = 0
for _ in range(r):
x = [rng.gauss(0.0, 1.0) for _ in range(20)]
lo, hi = percentile_interval(x, statistics.fmean, alpha, b, rng)
hits += lo <= 0.0 <= hi
cov = hits / r
assert abs(cov - (1 - alpha)) <= 4 * math.sqrt(alpha * (1 - alpha) / r) + 0.03
def test_errors():
with pytest.raises(ValueError):
percentile_interval([1.0, 2.0], statistics.fmean, 0.0, 10, random.Random(1))
with pytest.raises(ValueError):
percentile_interval([], statistics.fmean, 0.1, 10, random.Random(1))
with pytest.raises(ValueError):
empirical_quantile([], 0.5)
History
Bradley Efron introduced the bootstrap in 1979 and, in his 1981 and 1982 work, the percentile interval and its justification by a normalizing transformation. The weakness of the method in small and skewed samples led him to the bias-corrected interval and in 1987 to the BCa interval. Peter Hall (1988) compared the methods by Edgeworth expansions and showed that the percentile interval is first-order accurate and the studentized and BCa intervals second-order accurate. Hall also pointed out that the basic interval, which some authors call the percentile interval, reflects the bootstrap distribution, and that the two methods differ when the distribution is skewed.
References
- Bradley Efron and Robert J. Tibshirani, An Introduction to the Bootstrap, Chapman and Hall, 1993, Chapter 13 (confidence intervals based on bootstrap percentiles, and the transformation-respecting property) and Chapter 22 (further topics in bootstrap confidence intervals, the orders of accuracy)
- A. C. Davison and D. V. Hinkley, Bootstrap Methods and their Application, Cambridge University Press, 1997, Chapter 5 (confidence intervals, the basic and the percentile methods, and their coverage)
- Peter Hall, Theoretical comparison of bootstrap confidence intervals, The Annals of Statistics 16(3), 1988, pp. 927 to 953 (the percentile interval is first-order accurate, and the studentized and BCa intervals are second-order accurate)
- Peter Hall, The Bootstrap and Edgeworth Expansion, Springer, 1992, Chapter 3 (an Edgeworth view of the bootstrap, the coverage error of percentile intervals)
- Bradley Efron, Bootstrap methods, another look at the jackknife, The Annals of Statistics 7(1), 1979, pp. 1 to 26 (the bootstrap distribution of a statistic)
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 3JWEPT Edit this page History Report an error Markdown