Algorithm Search⌘K

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
Properties
randomizednot exactofflinerandomizediterative
Origin
Bradley Efron, 1979

The bootstrap percentile interval is the simplest bootstrap confidence interval. Draw bb bootstrap samples, compute the statistic θ^∗\hat\theta^* on each, and take the α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles of the bb 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 log⁡θ\log\theta is the log of the interval for θ\theta. Its coverage error for each endpoint is of order n−1/2n^{-1/2}, 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 x1,…,xnx_1, \ldots, x_n, independent and identically distributed from an unknown FF; a statistic ss with θ^=s(x)\hat\theta = s(x), which estimates θ=t(F)\theta = t(F); a level α∈(0,1)\alpha \in (0, 1); and a number of replicates bb.

Output. An interval [L,U][L, U] that should contain θ\theta with probability close to 1−α1 - \alpha.

Definition. Let GG be the bootstrap distribution function of θ^∗\hat\theta^*, the law of s(X∗)s(X^*) when X∗X^* is a sample of size nn from F^n\hat F_n. With the generalized inverse G−1(p)=inf⁡{t:G(t)≥p}G^{-1}(p) = \inf\{t : G(t) \ge p\}, the ideal percentile interval is

[ G−1(α/2), G−1(1−α/2) ].[\,G^{-1}(\alpha/2),\ G^{-1}(1 - \alpha/2)\,].

The algorithm replaces GG by the empirical distribution G^b\hat G_b of bb Monte Carlo replicates.

The algorithm

  1. PERCENTILE-INTERVAL(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. 4sort θ*_1, ..., θ*_b into θ*_(1) ≤ ... ≤ θ*_(b)
  6. 5L ← θ*_(k), k = max(1, ⌈b α/2⌉)
  7. 6U ← θ*_(k'), k' = ⌈b (1 - α/2)⌉
  8. 7return [L, U]

Lines L5 and L6 compute G^b−1(p)\hat G_b^{-1}(p) exactly: the empirical distribution of bb values reaches pp for the first time at the ⌈bp⌉\lceil b p \rceil-th smallest value. The code converts pp to a fraction before the ceiling, so that bpb p 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 n=10n = 10 values

0.4, 0.9, 1.3, 1.6, 2.2, 2.8, 3.5, 4.9, 7.6, 13.1,0.4,\ 0.9,\ 1.3,\ 1.6,\ 2.2,\ 2.8,\ 3.5,\ 4.9,\ 7.6,\ 13.1,

with mean xˉ=3.83\bar x = 3.83, S=3.90S = 3.90 and S/10=1.233S/\sqrt{10} = 1.233. Let ss be the mean, α=0.05\alpha = 0.05 and b=2000b = 2000, with random.Random(1). Lines L5 and L6 use k=⌈2000⋅0.025⌉=50k = \lceil 2000 \cdot 0.025 \rceil = 50 and k′=⌈2000⋅0.975⌉=1950k' = \lceil 2000 \cdot 0.975 \rceil = 1950. The 50th smallest replicate is 1.80 and the 1950th is 6.31, so the interval is

[1.80, 6.31].[1.80,\ 6.31].

It reaches 2.482.48 above xˉ\bar x and 2.032.03 below, which follows the right skew of the data. On the same data, the t interval is [1.04,6.62][1.04, 6.62], the normal interval xˉ±1.96⋅se^boot\bar x \pm 1.96 \cdot \widehat{se}_{boot} with the bootstrap standard error 1.1721.172 is [1.53,6.13][1.53, 6.13], the bootstrap-t interval is [1.82,10.27][1.82, 10.27], and the BCa interval is [2.18,6.97][2.18, 6.97], all with the same seed.

Transformation. Running the same code with the statistic log⁡xˉ\log \bar x and the same seed gives the interval [log⁡1.80,log⁡6.31][\log 1.80, \log 6.31] exactly, because the logarithm does not change the order of the replicates. The tests check this, and also that the statistic −xˉ-\bar x gives [−U,−L][-U, -L] when b=999b = 999 and α=0.1\alpha = 0.1, where the two order statistics k=50k = 50 and k′=950k' = 950 are mirror images. For a decreasing transformation, other choices of bb 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 b=1000b = 1000 (seeds 101 and 102) gave these coverages for the true mean at the nominal level 0.95:

method n=10n = 10 n=20n = 20
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 n=10n = 10 its upper end was below the true mean in 10.9%10.9\% of the data sets and its lower end above it in 2.2%2.2\%. The Monte Carlo standard error of each coverage is about 0.0070.007.

Correctness

The proof is in proofs/correctness.md. What is proved:

  • Lines L5 and L6 return G^b−1(α/2)\hat G_b^{-1}(\alpha/2) and G^b−1(1−α/2)\hat G_b^{-1}(1 - \alpha/2), and as b→∞b \to \infty they converge to the ideal endpoints G−1(α/2)G^{-1}(\alpha/2) and G−1(1−α/2)G^{-1}(1 - \alpha/2) wherever GG is strictly increasing at these quantiles.
  • The interval respects transformations: for a strictly increasing gg, the interval computed for g(θ^)g(\hat\theta) is [g(L),g(U)][g(L), g(U)].
  • If there is an increasing transformation ϕ\phi such that ϕ(θ^)−ϕ(θ)\phi(\hat\theta) - \phi(\theta) has a continuous distribution HH that is symmetric about 0 and does not depend on FF, and the bootstrap reproduces it, so that ϕ(θ^∗)−ϕ(θ^)\phi(\hat\theta^*) - \phi(\hat\theta) also has law HH, then the ideal percentile interval has coverage exactly 1−α1 - \alpha. The method does not need to know ϕ\phi.

What is not proved: the coverage for a real FF. The normalizing transformation exists only approximately, and the coverage error of each endpoint is of order n−1/2n^{-1/2} (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 x1,…,xnx_1, \ldots, x_n are fixed. G(t)=P∗(θ^∗≤t)G(t) = P^*(\hat\theta^* \le t) is the bootstrap distribution function, where P∗P^* is the law of a resample of size nn from F^n\hat F_n. G^b(t)=1b#{j:θj∗≤t}\hat G_b(t) = \frac{1}{b} \#\{j : \theta^*_j \le t\} is the empirical distribution function of the bb replicates. For any distribution function KK, K−1(p)=inf⁡{t:K(t)≥p}K^{-1}(p) = \inf\{t : K(t) \ge p\}.

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 FF. That coverage is measured on the page.

Claim 1 (lines L5 and L6 compute the empirical quantiles). For 0<p<10 < p < 1, G^b−1(p)=θ(k)∗\hat G_b^{-1}(p) = \theta^*_{(k)} with k=⌈bp⌉k = \lceil b p \rceil.

Proof. Since 0<p<10 < p < 1, 1≤k≤b1 \le k \le b. At t=θ(k)∗t = \theta^*_{(k)} at least kk replicates are ≤t\le t, so G^b(t)≥k/b≥p\hat G_b(t) \ge k/b \ge p. For t<θ(k)∗t < \theta^*_{(k)} at most k−1k - 1 replicates are ≤t\le t, so G^b(t)≤(k−1)/b<p\hat G_b(t) \le (k-1)/b < p, because k−1<bpk - 1 < b p by the definition of the ceiling. So the infimum is θ(k)∗\theta^*_{(k)}. With p=α/2p = \alpha/2 and p=1−α/2p = 1 - \alpha/2 this is lines L5 and L6. The max(1, ...) in line L5 changes nothing for p>0p > 0; it only keeps the index valid. □\square

Claim 2 (the Monte Carlo endpoints converge to the ideal ones). Let 0<p<10 < p < 1 be a number that GG does not take as a value. Then, with probability 1 over the resampling, G^b−1(p)=G−1(p)\hat G_b^{-1}(p) = G^{-1}(p) for all large bb.

Proof. GG is a step function with finitely many jumps, at the values t1<⋯<trt_1 < \cdots < t_r that ss takes on the nnn^n resamples, and every replicate is one of these values. Let ti=G−1(p)t_i = G^{-1}(p). Then G(ti)≥pG(t_i) \ge p, and since pp is not a value of GG, G(ti)>pG(t_i) > p. If i>1i > 1, then G(ti−1)<pG(t_{i-1}) < p by the definition of the infimum. By the strong law of large numbers, G^b(ti)→G(ti)\hat G_b(t_i) \to G(t_i) and G^b(ti−1)→G(ti−1)\hat G_b(t_{i-1}) \to G(t_{i-1}) almost surely. So for all large bb, G^b(ti)>p\hat G_b(t_i) > p and G^b(t)≤G^b(ti−1)<p\hat G_b(t) \le \hat G_b(t_{i-1}) < p for every t<tit < t_i, because G^b\hat G_b is constant between consecutive tt values. So G^b−1(p)=ti\hat G_b^{-1}(p) = t_i. If i=1i = 1, no replicate is below t1t_1, and the same argument applies with only the first inequality. □\square

The values of GG are multiples of n−nn^{-n}, so the condition excludes only finitely many pp. The tests compute GG exactly over all nnn^n resamples for n≤5n \le 5 and check that the ideal interval of the implementation, which weights the (2n−1n)\binom{2n-1}{n} multisets of indices, returns G−1(α/2)G^{-1}(\alpha/2) and G−1(1−α/2)G^{-1}(1 - \alpha/2).

Claim 3 (transformation respecting). Let gg be strictly increasing on a set that contains every value of ss. Run the algorithm twice with the same random numbers, once with the statistic ss and once with g∘sg \circ s. If the first run returns [L,U][L, U], the second returns [g(L),g(U)][g(L), g(U)].

Proof. Line L2 draws the resample indices without looking at the statistic, so both runs use the same resamples, and the jj-th replicate of the second run is g(θj∗)g(\theta^*_j). A strictly increasing gg keeps the order, so the kk-th smallest of the g(θj∗)g(\theta^*_j) is g(θ(k)∗)g(\theta^*_{(k)}). Lines L5 and L6 use the same kk and k′k' in both runs. □\square

For a strictly decreasing gg the same argument gives [g(U),g(L)][g(U), g(L)], up to the index of the order statistic: the kk-th smallest of g(θj∗)g(\theta^*_j) is g(θ(b+1−k)∗)g(\theta^*_{(b + 1 - k)}). With bα/2b \alpha / 2 an integer, b+1−⌈bα/2⌉=⌈b(1−α/2)⌉+1b + 1 - \lceil b \alpha/2 \rceil = \lceil b(1 - \alpha/2) \rceil + 1, so the two endpoints are adjacent order statistics, not equal ones. The tests use b=999b = 999 and α=0.1\alpha = 0.1, where k=50k = 50 and k′=950=b+1−kk' = 950 = b + 1 - k, and there the result is exact.

Claim 4 (exact coverage under a normalizing transformation). Suppose there is a continuous, strictly increasing ϕ\phi and a continuous, strictly increasing distribution function HH, symmetric about 0, such that

ϕ(θ^)−ϕ(θ)∼Hunder F,ϕ(θ^∗)−ϕ(θ^)∼Hunder P∗.\phi(\hat\theta) - \phi(\theta) \sim H \quad \text{under } F, \qquad \phi(\hat\theta^*) - \phi(\hat\theta) \sim H \quad \text{under } P^*.

Then the ideal interval [G−1(α/2),G−1(1−α/2)][G^{-1}(\alpha/2), G^{-1}(1 - \alpha/2)] contains θ\theta with probability exactly 1−α1 - \alpha.

Proof. Write hp=H−1(p)h_p = H^{-1}(p), so hα/2=−h1−α/2h_{\alpha/2} = -h_{1 - \alpha/2} by symmetry. By the second assumption G(t)=P∗(ϕ(θ^∗)≤ϕ(t))=H(ϕ(t)−ϕ(θ^))G(t) = P^*(\phi(\hat\theta^*) \le \phi(t)) = H(\phi(t) - \phi(\hat\theta)), so G−1(p)=ϕ−1(ϕ(θ^)+hp)G^{-1}(p) = \phi^{-1}(\phi(\hat\theta) + h_p). Because ϕ\phi is increasing,

G−1(α/2)≤θ≤G−1(1−α/2)  ⟺  hα/2≤ϕ(θ)−ϕ(θ^)≤h1−α/2  ⟺  hα/2≤ϕ(θ^)−ϕ(θ)≤h1−α/2,G^{-1}(\alpha/2) \le \theta \le G^{-1}(1 - \alpha/2) \iff h_{\alpha/2} \le \phi(\theta) - \phi(\hat\theta) \le h_{1 - \alpha/2} \iff h_{\alpha/2} \le \phi(\hat\theta) - \phi(\theta) \le h_{1-\alpha/2},

where the last step uses −h1−α/2=hα/2-h_{1-\alpha/2} = h_{\alpha/2}. By the first assumption this event has probability H(h1−α/2)−H(hα/2)=1−αH(h_{1-\alpha/2}) - H(h_{\alpha/2}) = 1 - \alpha. □\square

The algorithm does not need to know ϕ\phi; this is the reason for the method. The symmetry of HH is necessary: without it the correct interval uses hα/2h_{\alpha/2} and h1−α/2h_{1-\alpha/2} 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 z0z_0 and a standard deviation that changes with θ\theta.

What is not proved. For a real FF the bootstrap distribution is discrete and no exact ϕ\phi exists. Under smoothness conditions, Edgeworth expansions show that each one-sided endpoint has coverage error of order n−1/2n^{-1/2} (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 0.0070.007, not theorems.

Cost. The loop of lines L1 to L3 runs bb times. Each pass draws nn indices and evaluates ss once. Line L4 sorts bb numbers in Θ(blog⁡b)\Theta(b \log b) comparisons, and lines L5 and L6 take constant time. So the time is Θ(b⋅(n+Cs(n))+blog⁡b)\Theta(b \cdot (n + C_s(n)) + b \log b), where Cs(n)C_s(n) is the cost of ss, and the extra space is Θ(b+n)\Theta(b + n).

Complexity

Each of the bb replicates draws nn indices and evaluates the statistic, which for the mean costs Θ(n)\Theta(n). The sort of line L4 costs Θ(blog⁡b)\Theta(b \log b). So the time is Θ(bn+blog⁡b)\Theta(b n + b \log b), and Θ(bn)\Theta(b n) with two linear-time selections instead of the sort. The replicates take Θ(b)\Theta(b) space and one resample Θ(n)\Theta(n). For a statistic that costs Cs(n)C_s(n), replace nn by Cs(n)C_s(n) in the first term.

Properties

  • Transformation respecting. The interval for g(θ)g(\theta) is gg applied to the interval for θ\theta, for every strictly increasing gg. 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 [−1,1][-1, 1] and one for a variance stays positive.
  • First-order accurate. The coverage error of each one-sided endpoint is O(n−1/2)O(n^{-1/2}). 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 n−1nS2/n\frac{n-1}{n} S^2/n and uses normal-like quantiles instead of tt quantiles, so the interval is short by a factor of about (n−1)/n⋅z0.975/tn−1,0.975\sqrt{(n-1)/n} \cdot z_{0.975}/t_{n-1, 0.975}, which is 0.820.82 for n=10n = 10.
  • Monte Carlo error. The endpoints are extreme order statistics of the replicates, so they need more replicates than a standard error: use b≥1000b \ge 1000, and better 20002000 or more.

Variants and improvements

  • Basic (reverse percentile) interval. [2θ^−G−1(1−α/2), 2θ^−G−1(α/2)][2\hat\theta - G^{-1}(1 - \alpha/2),\ 2\hat\theta - G^{-1}(\alpha/2)]. It assumes that θ^−θ\hat\theta - \theta and θ^∗−θ^\hat\theta^* - \hat\theta have the same law, so it reflects the skewness the other way. It is not transformation respecting.
  • BCa interval. Moves the two levels α/2\alpha/2 and 1−α/21 - \alpha/2 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 nn the bootstrap distribution can be enumerated over the (2n−1n)\binom{2n - 1}{n} multisets of indices, which removes the Monte Carlo error. The tests compare the code with the enumeration of all nnn^n resamples for n≤5n \le 5.
  • 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 nn 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 n=10n = 10 from an exponential law, the nominal 95% interval covered the mean in only 86.9%86.9\% 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 θ^\hat\theta is biased, the bootstrap distribution is centred near θ^\hat\theta plus the bias, and the percentile interval moves the wrong way. The BCa correction z0z_0 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 b=200b = 200 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.

bootstrap_percentile_interval.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. Peter Hall, The Bootstrap and Edgeworth Expansion, Springer, 1992, Chapter 3 (an Edgeworth view of the bootstrap, the coverage error of percentile intervals)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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