Module contents
Lesson 16 of 27Core 105 min

The bootstrap and the jackknife

Use bootstrap and jackknife resampling to estimate uncertainty, bias, and confidence intervals, and recognize their limitations.

After this lesson you can

  • Explain the plug-in principle and construct bootstrap samples.
  • Estimate standard error, bias and confidence intervals, and compare parametric and nonparametric bootstrap.
  • Derive jackknife estimates and diagnose failure for nonsmooth statistics.
  • Choose the number and independent unit of resamples for machine-learning metrics.

Before you start

Motivation: a standard error without a formula

A service measures 200 request latencies and wants the 99th percentile, important to the unluckiest user. The sample percentile takes one line of code. But how precise is it? A number without uncertainty is an anecdote, and the 99th percentile of a long-tailed distribution has no simple standard-error formula without strong assumptions. The same applies to classifier F1F_1, AUC, a ratio of means, Gini coefficient or largest graph component size. In asymptotic theory you learned delta-method standard errors for smooth functions of means. Here there may be no means, the function may not be smooth, or derivation may be inconvenient.

The alternative is brutally simple: if we cannot repeat the experiment with the real population, repeat it with the sample we have. The next cell deliberately cheats so we can judge the trick. It generates lognormal latencies (known truth), calculates the “real” 99th-percentile standard error by repeating the experiment five thousand times, and compares it with what an analyst with one resampled dataset obtains.

[ ]Standard error of a 99th percentile without a formulaBrowser
import numpy as np

rng = np.random.default_rng(16)
n, mu, sig = 200, 3.0, 0.6                     # latencias en ms, lognormales
p99 = lambda a: np.percentile(a, 99, axis=-1)

# la verdad: repetir el experimento con la población real (imposible en la práctica)
verdad = p99(rng.lognormal(mu, sig, (5000, n))).std(ddof=1)

# lo que se tiene: una sola muestra, remuestreada con reemplazo B veces
x = rng.lognormal(mu, sig, n)
B = 2000
rep = p99(x[rng.integers(0, n, (B, n))])
print(f"percentil 99 de esta muestra     : {p99(x):.1f} ms   (el de la población es {np.exp(mu + sig * 2.3263479):.1f})")
print(f"error estándar verdadero         : {verdad:.2f} ms")
print(f"error estándar bootstrap (1 muestra): {rep.std(ddof=1):.2f} ms")

# ¿es una casualidad de esta muestra? repetimos con 200 muestras distintas (B = 200)
ee = np.array([p99(y[rng.integers(0, n, (200, n))]).std(ddof=1) for y in rng.lognormal(mu, sig, (200, n))])
print(f"\nbootstrap en 200 muestras distintas: media {ee.mean():.2f} ms, entre {np.quantile(ee, .1):.2f} y {np.quantile(ee, .9):.2f} (percentiles 10 y 90)")

For this particular sample bootstrap gives 6.3 ms, half the true 11.3 ms: not a method failure but a sample with few extreme latencies by chance, where the 99th percentile of 200 observations depends on only two. Across 200 samples the average approaches truth (12.4 ms versus 11.3), but the central 80 % of estimates spans 5.3 to 22 ms. Bootstrap is not exact: it is an estimate with its own error, and this lesson quantifies it and when to trust it. Five questions:

  1. Why does it work? The plug-in principle: replace the unknown population with the empirical distribution, including for the sampling distribution.
  2. What exactly is a resample? A multinomial count vector with surprising consequences (63.2 %, maximum).
  3. What can be estimated? Standard error, bias and intervals (percentile and basic), and when parametric bootstrap helps.
  4. What about jackknife? Its deterministic predecessor, its formulas and why it fails for the median.
  5. How many replicates, and what unit should be resampled? Monte Carlo errors and bootstrap for machine-learning metrics.

We use empirical distribution, sampling distribution, standard error, bias and mean squared error, confidence intervals and simulation studies, along with the central limit theorem and weak and strong laws of large numbers.

The plug-in principle

Almost everything estimated in statistics is a function of the data-generating distribution. Making that explicit is step one.

Sample means, “1/n1/n” variances, medians and empirical percentiles are plug-in estimates. The principle does not give the best estimator: plug-in variance 1n∑(xi−xˉ)2\frac1n\sum(x_i - \bar x)^2 is biased by factor (n−1)/n(n-1)/n, as in estimators. It gives the obvious estimator, valid under mild conditions.

Proof

By Glivenko–Cantelli, ∥F^n−F∥∞→0\norm{\hat F_n - F}_\infty \to 0 almost surely. Continuity of TT at FF turns uniform convergence into T(F^n)→T(F)T(\hat F_n) \to T(F).

∎

The assumption is stronger than it looks: the mean is not continuous in sup norm (move mass ε\varepsilon arbitrarily far to change the mean arbitrarily without letting sup⁡x∣G−F∣\sup_x\abs{G - F} exceed ε\varepsilon), yet Xˉ→μ\bar X \to \mu almost surely by the strong law. Sup-norm continuity is sufficient but not necessary: handle the mean via the strong law and each functional with an appropriate topology. For asymptotic normality of T(F^n)T(\hat F_n) and bootstrap validity, the standard condition is different and stronger: Hadamard differentiability (van der Vaart, 1998, chapters 20 and 23), covering quantiles where density is positive and generalizing the lesson 8 delta method. The idea suffices here.

The plug-in principle estimates more than parameters. The sampling distribution of θ^\hat\theta is itself a functional of FF:

GF(t)=PF(θ^(X1,…,Xn)≤t),Xi∼iidF.G_F(t) = \Pr_F\big(\hat\theta(X_1, \dots, X_n) \le t\big), \qquad X_i \iid F.

It depends on FF (shape, tails, skew) and nn. If FF is unknown, estimate it plug-in using F^n\hat F_n. That is bootstrap.

Nonparametric bootstrap

G^n\hat G_n is rarely closed-form, but can be simulated as much as needed:

  1. For b=1,…,Bb = 1, \dots, B: choose nn uniform indices from {1,…,n}\{1, \dots, n\} with replacement, form x∗b\vb{x}^{\ast b}, calculate θ^∗b\hat\theta^{\ast b}.
  2. Summarize replicates θ^∗1,…,θ^∗B\hat\theta^{\ast 1}, \dots, \hat\theta^{\ast B}: SE^B=sd(θ^∗b)\widehat{\mathrm{SE}}_B = \mathrm{sd}(\hat\theta^{\ast b}), sesgo^B=θ^∗‾−θ^\widehat{\mathrm{sesgo}}_B = \overline{\hat\theta^\ast} - \hat\theta, interval quantiles.

Two worlds

Understand in parallel. In the real world, population FF produces sample x\vb{x}, yielding θ^=T(F^n)\hat\theta = T(\hat F_n); repeated experiments give the sampling distribution. In the bootstrap world, F^n\hat F_n serves as population, produces resample x∗\vb{x}^\ast, yielding θ^∗\hat\theta^\ast.

Real worldBootstrap world
PopulationFF (unknown)F^n\hat F_n (known)
Datax∼F\vb{x} \sim Fx∗∼F^n\vb{x}^\ast \sim \hat F_n
Parameterθ=T(F)\theta = T(F)θ^=T(F^n)\hat\theta = T(\hat F_n)
Estimateθ^\hat\thetaθ^∗\hat\theta^\ast
Estimation errorR=θ^−θR = \hat\theta - \thetaR∗=θ^∗−θ^R^\ast = \hat\theta^\ast - \hat\theta

Bootstrap does not assume θ^∗\hat\theta^\ast resembles θ^\hat\theta or θ^\hat\theta resembles θ\theta. It assumes bootstrap-world error R∗R^\ast behaves like real-world error RR. The figure shows this.

InteractiveTwo worlds: real and bootstrap
Real world: samples of size n=20n = 20 drawn from the population
θ
Bootstrap world: resamples from the single observed sample
θ̂θ
Both centered distributions: R=θ^−θR = \hat\theta - \theta (real) versus R∗=θ^∗−θ^R^\ast = \hat\theta^\ast - \hat\theta (bootstrap)
  • real world, sampling distribution
  • bootstrap world
  • parameter θ
  • estimate θ̂
Population
Statistic
20
Parameter θ\theta | estimate θ^\hat\theta1.325 | 1.213
Standard error: real | bootstrap0.247 | 0.253
Bias: real mean −θ-\theta | bootstrap mean −θ^-\hat\theta−0.001 | −0.002
Kolmogorov distance between RR and R∗R^\ast0.031
Replicates shown in each world1500 of 1500
The bootstrap standard error is 0.253, compared with the true 0.247 (ratio 1.03). The centers differ by θ^−θ=−0.112\hat\theta - \theta = −0.112, as expected: the shape and width are copied, not the location. Press “Another observed sample” to see the ratio change: bootstrap inherits the randomness of the sample it receives.
Left: fifteen hundred real-population samples and their statistic, the true sampling distribution. Right: fifteen hundred resamples of one observed sample. Panels share an axis: centers differ (θ versus θ̂), but width and shape resemble each other. Below: both distributions centered on their parameter, R=θ^−θR = \hat\theta - \theta versus R∗=θ^∗−θ^R^\ast = \hat\theta^\ast - \hat\theta, and their Kolmogorov distance. Press 'Replay animation'. Request several observed samples: how much does bootstrap standard error vary? Switch to median with n=10n = 10 in a bimodal population, where resemblance is worse, then increase nn to 80.

Three readings:

  • Center belongs to the sample, not population. Bootstrap distribution is centered at θ^\hat\theta (more precisely around it), not θ\theta. Bootstrap thus measures dispersion (standard error, interval width), not recentering.
  • Bootstrap inherits sample randomness. Two samples from the same population give slightly different bootstrap distributions. Width is an estimate with its own relative O(n−1/2)\bigO(n^{-1/2}) error.
  • It improves with nn, not BB. At n=10n = 10 bootstrap shape is a poor approximation, especially for median; at n=80n = 80 it resembles truth. More replicates only smooth the right histogram.

Two sources of error

The approximation has two steps, each with error:

GF⏟distribucioˊn muestral real  →error estadıˊstico  F → F^n    G^n⏟bootstrap ideal (B=∞)  →error de Monte Carlo  B<∞    G^n,B.\underbrace{G_F}_{\text{distribución muestral real}} \;\xrightarrow[\text{error estadístico}]{\;F \,\to\, \hat F_n\;}\; \underbrace{\hat G_n}_{\text{bootstrap ideal}\ (B = \infty)} \;\xrightarrow[\text{error de Monte Carlo}]{\;B < \infty\;}\; \hat G_{n,B}.

Statistical error comes from F^n≠F\hat F_n \ne F and shrinks only with more data. Monte Carlo error comes from simulating rather than calculating G^n\hat G_n exactly, and shrinks with more replicates BB (free compared with collecting data). Confusing them is the most frequent conceptual error: increasing BB cannot fix a small sample.

Why it works: the mean

The simplest rigorous justification concerns the mean, due to Bickel and Freedman (1981) and Singh (1981).

Proof

Conditional on x\vb{x}, Xj∗X_j^\ast are iid with mean xˉ\bar x and variance σ^n2=1n∑i(xi−xˉ)2\hat\sigma_n^2 = \frac1n\sum_i (x_i - \bar x)^2, converging almost surely to σ2\sigma^2 (strong law). To apply Lindeberg–Feller to the triangular array, verify Lindeberg’s condition for each ε>0\varepsilon > 0:

1σ^n2 1n∑i=1n(xi−xˉ)2 1[∣xi−xˉ∣>εn σ^n]→n→∞0casi seguro.\frac{1}{\hat\sigma_n^2}\,\frac1n\sum_{i=1}^n (x_i - \bar x)^2\,\ind\big[\abs{x_i - \bar x} > \varepsilon\sqrt n\,\hat\sigma_n\big] \xrightarrow[n\to\infty]{} 0 \quad\text{casi seguro.}

Indeed, for fixed M>0M > 0 and large nn, εn σ^n>M\varepsilon\sqrt n\,\hat\sigma_n > M, so the term is at most σ^n−2 1n∑i(xi−xˉ)21[∣xi−xˉ∣>M]\hat\sigma_n^{-2}\,\frac1n\sum_i (x_i - \bar x)^2\ind[\abs{x_i - \bar x} > M], which by the strong law tends to σ−2 E[(X−μ)21[∣X−μ∣>M]]\sigma^{-2}\,\E\big[(X - \mu)^2\ind[\abs{X - \mu} > M]\big], tending to 0 as M→∞M \to \infty by dominated convergence. Thus almost surely n(Xˉ∗−xˉ)/σ^n⇒N(0,1)\sqrt n(\bar X^\ast - \bar x)/\hat\sigma_n \Rightarrow \Normal(0,1) conditionally; continuity of the limit makes convergence uniform (Pólya). The CLT also gives n(Xˉ−μ)/σ⇒N(0,1)\sqrt n(\bar X - \mu)/\sigma \Rightarrow \Normal(0, 1) and σ^n→σ\hat\sigma_n \to \sigma. The triangle inequality finishes.

∎

The bootstrap mean distribution inherits asymptotic normality from the real one. Nothing magical: the CLT is applied twice, once to data and once to conditional resamples. For the mean ideal bootstrap has closed form:

Var∗(Xˉ∗)=σ^n2n=1n2∑i=1n(xi−xˉ)2,es decirSE∞=n−1n  sn,\mathrm{Var}^\ast(\bar X^\ast) = \frac{\hat\sigma_n^2}{n} = \frac{1}{n^2}\sum_{i=1}^n (x_i - \bar x)^2, \qquad \text{es decir}\qquad \mathrm{SE}_\infty = \sqrt{\tfrac{n-1}{n}}\;\frac{s}{\sqrt n},

almost the classical s/ns/\sqrt n standard error, with factor (n−1)/n\sqrt{(n-1)/n} from plug-in variance. This is a good implementation smoke test:

[ ]Ideal bootstrap of the mean has a closed formBrowser
import numpy as np

rng = np.random.default_rng(1)
n = 25
x = rng.exponential(1.0, n)

ee_ideal = np.sqrt(x.var(ddof=0) / n)          # sqrt(sigma_hat^2 / n): B = infinito
ee_clasico = x.std(ddof=1) / np.sqrt(n)        # s / sqrt(n)

B = 100_000
rep = x[rng.integers(0, n, (B, n))].mean(axis=1)
print(f"error estándar bootstrap con B = {B:,}: {rep.std(ddof=1):.5f}")
print(f"fórmula cerrada del bootstrap ideal     : {ee_ideal:.5f}")
print(f"error estándar clásico s/sqrt(n)        : {ee_clasico:.5f}   (cociente {ee_ideal / ee_clasico:.4f} = sqrt((n-1)/n) = {np.sqrt((n - 1) / n):.4f})")

What is a resample?

A size-nn resample is determined by how often each observation was selected, and those counts have an explicit distribution.

Proof

Each of nn draws independently selects xix_i with probability 1/n1/n: the multinomial definition, with binomial marginal NiN_i. Observation xix_i is absent if no draw selects it, probability (1−1/n)n(1 - 1/n)^n, tending to e−1e^{-1} (classic limit (1+a/n)n→ea(1 + a/n)^n \to e^a). A size-nn multiset over nn elements solves N1+⋯+Nn=nN_1 + \dots + N_n = n in nonnegative integers, counted by stars and bars as (n+n−1n)\binom{n + n - 1}{n}. This count depends on nn. For (3), assume ordered untied data. Observed maximum x(n)x_{(n)} appears unless no draw selects it; when present it is the resample maximum: probability 1−(1−1/n)n1 - (1-1/n)^n, decreasing toward 1−e−11 - e^{-1} from above (for n=2n = 2 it is 0.750.75).

∎

For n=3n = 3 distinct values there are (53)=10\binom{5}{3} = 10 multiset resamples, not equally likely: three “triples” (3,0,0)(3,0,0) each occur with probability 1/271/27, six “doubles” (2,1,0)(2,1,0) with 3/273/27, and the “balanced” (1,1,1)(1,1,1) with 6/276/27 (sum 3/27+18/27+6/27=13/27 + 18/27 + 6/27 = 1). Ideal bootstrap is enumerable for small nn, but with n=20n = 20 already has 6.9×10106.9 \times 10^{10} multisets: simulation is practical.

InteractiveWhat is a resample?
Last resample: times each observation was selected (sorted smallest to largest; violet is the maximum)
How often an observation appears across all resamples
ausente: 36.5 %
  • simulated
  • binomial B(n, 1/n)
  • Poisson(1) (rings)
Which observation is the resample maximum
  • simulated
  • observed maximum
  • theory
20
Accumulated resamples300
Distinct observations in the last resample13 of 20
Fraction present: simulated | 1−(1−1/n)n1-(1-1/n)^n63.5 % | 64.2 %
Observed maximum is resample maximum: simulated | theory64.0 % | 64.2 %
Distinct resamples (multisets) (2n−1n)\binom{2n-1}{n}6.9 × 10¹⁰
With n=20n = 20 each resample contains on average 64.2 % distinct observations and misses 35.8 %, already close to limits 1−e−1≈63.2 %1 - e^{-1} \approx 63.2\ \% and e−1≈36.8 %e^{-1} \approx 36.8\ \%. By the same calculation, a resample maximum equals the observed maximum 64 % of the time, so the bootstrap maximum distribution has a giant atom.
Top: latest resample; tall bars are repeatedly chosen observations, red marks absent ones. Bottom left: count distribution across accumulated resamples versus binomial B(n,1/n)B(n, 1/n) (dots) and Poisson(1) (rings); right: which observation becomes resample maximum. Accumulate thousands of resamples. At n=5n = 5, can binomial and Poisson be distinguished? At n=100n = 100, what is 63.2 %? Inspect the right purple bar: what fraction repeats the observed maximum?

The theorem’s three facts have practical consequences.

Each resample sees only 63 % of data. The remaining 37 % is “out of bag”. This underlies out-of-bag error in random forests: each tree trains on a resample and is evaluated on unseen data.

A resample reweights. F^n∗=∑i(Ni/n) δxi\hat F_n^\ast = \sum_i (N_i/n)\,\delta_{x_i}: bootstrap invents no data, it changes weights from 1/n1/n to Ni/nN_i/n with Ni∼Bin(n,1/n)N_i \sim \mathrm{Bin}(n,1/n). This connects bootstrap to jackknife (weight 0 for one observation, 1/(n−1)1/(n-1) for others) and modern variants (weighted, Bayesian bootstrap).

The maximum resists bootstrap. Bootstrap sample-maximum distribution has an atom of mass ≥0.632\ge 0.632 at the observed maximum, while its true distribution is continuous. This classic naive-bootstrap inconsistency arises because nonsmoothness breaks the two-world analogy. Advanced bootstrap studies failures and remedies. Keep the warning: bootstrap works for reasonably smooth statistics (means, central quantiles, differentiable functions) and fails at extremes.

[ ]Resample facts checkedBrowser
import numpy as np
from itertools import combinations_with_replacement
from math import comb

rng = np.random.default_rng(3)
print("   n   datos distintos (sim)   1-(1-1/n)^n   P(máx* = máx observado) (sim)")
for n in (3, 5, 20, 100, 1000):
    N = rng.multinomial(n, np.ones(n) / n, size=3000)      # recuentos de 3000 remuestras
    distintos = (N > 0).mean()                              # fracción media de datos presentes
    prob_max = (N[:, -1] > 0).mean()                        # el dato mayor está presente
    print(f"{n:5d}   {distintos:20.4f}   {1 - (1 - 1 / n) ** n:11.4f}   {prob_max:26.4f}")

print("\nlímite 1 - 1/e =", round(1 - np.exp(-1), 4))
print("multiconjuntos con n = 3  :", len(list(combinations_with_replacement(range(3), 3))), "= C(5,3) =", comb(5, 3))
print("multiconjuntos con n = 20 :", f"{comb(39, 20):,}")

Standard error and bias

Given replicates, two basic estimates follow. Bootstrap standard error is replicate standard deviation SE^B=[1B−1∑b(θ^∗b−θ^∗‾)2]1/2\widehat{\mathrm{SE}}_B = \big[\frac{1}{B-1}\sum_b (\hat\theta^{\ast b} - \overline{\hat\theta^\ast})^2\big]^{1/2}. This answers the motivating question for any computable statistic.

Bootstrap bias applies the two-world analogy to bias E[θ^]−θ\E[\hat\theta] - \theta: in the bootstrap world, E∗[θ^∗]−θ^≈θ^∗‾−θ^\E^\ast[\hat\theta^\ast] - \hat\theta \approx \overline{\hat\theta^\ast} - \hat\theta. For plug-in variance σ^2\hat\sigma^2 from a sample with σ2=1\sigma^2 = 1 and n=15n = 15, true bias is −1/15=−0.067-1/15 = -0.067, and bootstrap estimates near that.

A tempting consequence: subtract known bias. The corrected estimator is

θ^corr=θ^−sesgo^boot=2θ^−θ^∗‾.\hat\theta_{\mathrm{corr}} = \hat\theta - \widehat{\mathrm{sesgo}}_{\mathrm{boot}} = 2\hat\theta - \overline{\hat\theta^\ast}.

Almost always a bad idea. Bias estimates are noisy (statistical and Monte Carlo error), and subtracting them adds noise to an estimator whose bias, if small relative to standard error, contributed little to MSE. Efron and Tibshirani’s rule is not to correct unless ∣sesgo∣/SE\abs{\mathrm{sesgo}}/\mathrm{SE} exceeds about 0.250.25. The cell checks three estimators, repeating the entire procedure (sample, bootstrap, correction) hundreds of times to measure actual MSE.

[ ]Is bootstrap bias correction worthwhile?Browser
import numpy as np

rng = np.random.default_rng(12)
R, B = 1000, 150

exp1, norm1 = (lambda n: rng.exponential(1, n)), (lambda n: rng.normal(0, 1, n))
casos = [   # nombre, generador, estimador (reduce sobre el último eje), valor verdadero, n
    ("mediana, n = 15",          exp1,  lambda a: np.median(a, axis=-1), np.log(2), 15),
    ("varianza plug-in, n = 15", norm1, lambda a: a.var(axis=-1),        1.0,       15),
    ("1/media, n = 15",          exp1,  lambda a: 1 / a.mean(axis=-1),   1.0,       15),
    ("1/media, n = 8",           exp1,  lambda a: 1 / a.mean(axis=-1),   1.0,       8),
]
print(f"{'estimador':26s} {'sesgo/EE':>9s} {'ECM sin corregir':>17s} {'ECM corregido':>14s}  cociente")
for nombre, gen, est, verdad, n in casos:
    sin, con = np.empty(R), np.empty(R)
    for r in range(R):
        x = gen(n)
        t = est(x)
        rep = est(x[rng.integers(0, n, (B, n))])
        sin[r], con[r] = t, 2 * t - rep.mean()              # theta - sesgo_boot
    ecm0, ecm1 = ((sin - verdad) ** 2).mean(), ((con - verdad) ** 2).mean()
    print(f"{nombre:26s} {(sin.mean() - verdad) / sin.std():9.2f} {ecm0:17.4f} {ecm1:14.4f}  {ecm1 / ecm0:8.2f}")

A lesson in caution. For the nonsmooth median, correction worsens MSE by 36 % despite modest bias (0.190.19 standard errors), because bootstrap bias estimation for nonsmooth statistics is especially noisy. For plug-in variance, with bias (−0.26-0.26) near threshold, correction also loses (8 % worse). Only for 1/xˉ1/\bar x, a smooth function of the mean with bias 0.280.28–0.320.32 standard errors, does correction help (16 % and 24 % lower MSE, more at smaller nn). A procedure that sometimes helps and sometimes hurts deserves skepticism: report estimated bias alongside the estimator, reserving correction for smooth statistics with bias large relative to standard error, as in very small samples and nonlinear functions.

Bootstrap confidence intervals

The bootstrap distribution of θ^∗\hat\theta^\ast yields several intervals. Three simple ones share an idea but treat skew differently.

Normal interval. If θ^\hat\theta is approximately normal, θ^±z1−α/2 SE^B\hat\theta \pm z_{1-\alpha/2}\,\widehat{\mathrm{SE}}_B. Bootstrap supplies only standard error.

Basic (pivotal) interval. Start with the two-world analogy. If rpr_p is the pp quantile of error R=θ^−θR = \hat\theta - \theta, then P(rα/2≤θ^−θ≤r1−α/2)=1−α\Pr(r_{\alpha/2} \le \hat\theta - \theta \le r_{1-\alpha/2}) = 1 - \alpha; solving for θ\theta,

θ∈[θ^−r1−α/2, θ^−rα/2].\theta \in \big[\hat\theta - r_{1-\alpha/2},\ \hat\theta - r_{\alpha/2}\big].

The rpr_p are unknown, but bootstrap error R∗=θ^∗−θ^R^\ast = \hat\theta^\ast - \hat\theta has quantiles rp∗=qp∗−θ^r_p^\ast = q_p^\ast - \hat\theta, where qp∗q_p^\ast is the pp quantile of replicates. Substitute:

 [ 2θ^−q1−α/2∗,  2θ^−qα/2∗ ] \boxed{\ \Big[\,2\hat\theta - q^\ast_{1-\alpha/2},\ \ 2\hat\theta - q^\ast_{\alpha/2}\,\Big]\ }

the percentile interval reflected about θ^\hat\theta.

Percentile interval. More directly, take replicate quantiles themselves.

The three agree when bootstrap distribution is symmetric and diverge otherwise. Comparing percentile and basic is instructive because they rest on different analogies and give different results:

Proof

(1) Substitute: if qα/2∗=2θ^−q1−α/2∗q^\ast_{\alpha/2} = 2\hat\theta - q^\ast_{1-\alpha/2}, basic endpoints are 2θ^−q1−α/2∗=qα/2∗2\hat\theta - q^\ast_{1-\alpha/2} = q^\ast_{\alpha/2} and 2θ^−qα/2∗=q1−α/2∗2\hat\theta - q^\ast_{\alpha/2} = q^\ast_{1-\alpha/2}. (2) Quantiles commute with increasing maps: qp(g(θ^∗))=g(qp(θ^∗))q_p(g(\hat\theta^\ast)) = g(q_p(\hat\theta^\ast)). But 2g(θ^)−g(q)≠g(2θ^−q)2g(\hat\theta) - g(q) \ne g(2\hat\theta - q) unless gg is affine. (3) Set ϕ=g(θ)\phi = g(\theta) and ϕ^=g(θ^)\hat\phi = g(\hat\theta). Real world gives ϕ^−ϕ∼H\hat\phi - \phi \sim H, and by hypothesis bootstrap reproduces ϕ^∗−ϕ^∼H\hat\phi^\ast - \hat\phi \sim H, so ϕ^∗\hat\phi^\ast has quantiles ϕ^+hp\hat\phi + h_p. The basic interval for ϕ\phi is [ϕ^−h1−α/2, ϕ^−hα/2][\hat\phi - h_{1-\alpha/2},\ \hat\phi - h_{\alpha/2}], which by symmetry hα/2=−h1−α/2h_{\alpha/2} = -h_{1-\alpha/2} equals [ϕ^+hα/2, ϕ^+h1−α/2][\hat\phi + h_{\alpha/2},\ \hat\phi + h_{1-\alpha/2}], the percentile interval for ϕ^∗\hat\phi^\ast; coverage is 1−α1 - \alpha because P(hα/2≤ϕ^−ϕ≤h1−α/2)=1−α\Pr(h_{\alpha/2} \le \hat\phi - \phi \le h_{1-\alpha/2}) = 1 - \alpha. By (2), transforming by g−1g^{-1} gives the percentile interval for θ\theta and preserves coverage.

∎

Condition (3) is a normalizing pivot: a scale where error is symmetric and parameter-independent. Fisher’s correlation zz transform is the classic example: percentile interval for rr works despite skew in rr, being equivalent to a symmetric interval in artanh⁡r\operatorname{artanh} r. Both intervals are first order: each tail’s coverage error is order n−1/2n^{-1/2}, no better than normal. Second-order corrections (BCa, bootstrap-tt) are the subject of the next lesson.

InteractiveNormal, percentile and basic intervals
Bootstrap distribution of the median (2000 replicates) and the three 95% intervals
θθ̂
  • bootstrap
  • normal
  • percentile
  • basic
  • θ (true value)
Actual coverage across 400 samples (95% nominal)
normalpercentilebasicpress “Measure coverage”
  • nominal level 95%
Statistic and population
20
Level
Parameter θ\theta | estimate θ^\hat\theta | bootstrap SE0.693 | 0.711 | 0.146
normal interval (contains θ)[0.425, 0.997]
percentile interval (contains θ)[0.573, 1.115]
basic interval (contains θ)[0.307, 0.849]
Press ‘Measure coverage’ to repeat the complete procedure (sample, bootstrap, three intervals) over 400 new samples and see what fraction actually contains the parameter.
One observed sample and its bootstrap distribution (blue histogram), with the three 95% or 90% intervals. Translucent bars are intervals that do not contain the parameter. Change scenario and request other samples: with the exponential distribution, percentile and basic intervals separate. On the right is actual coverage: repeat everything (sample, bootstrap, three intervals) over 400 new samples; after changing scenario or nn, press 'Measure coverage'. For which statistic is percentile clearly better? And basic? Does either reach nominal coverage at n=10n = 10? Increase nn and measure again.

The figure (and the following cell, which measures the same thing with more samples) teaches humility about simple bootstrap methods: there is no universal winner, actual coverage for small nn falls below nominal, and the worst case (standard deviation of an exponential distribution with n=20n = 20) is very far from 95%.

[ ]Coverage of the three intervals, measured by simulationBrowser
import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(5)
R, B, n, alpha = 600, 300, 20, 0.05
z = norm.ppf(1 - alpha / 2)

escenarios = {   # nombre: (generador, estadístico, valor verdadero)
    "media, lognormal(0, 0.75)":  (lambda: rng.lognormal(0, 0.75, n), lambda a: a.mean(axis=-1),          np.exp(0.75 ** 2 / 2)),
    "mediana, exponencial":       (lambda: rng.exponential(1, n),     lambda a: np.median(a, axis=-1),    np.log(2)),
    "desv. típica, exponencial":  (lambda: rng.exponential(1, n),     lambda a: a.std(axis=-1, ddof=1),   1.0),
    "media, normal":              (lambda: rng.normal(0, 1, n),       lambda a: a.mean(axis=-1),          0.0),
}
print(f"{'escenario':28s} {'normal':>8s} {'percentil':>10s} {'básico':>8s}      (nominal {1 - alpha:.0%}, n = {n})")
for nombre, (gen, est, verdad) in escenarios.items():
    cubre = np.zeros(3)
    for _ in range(R):
        x = gen()
        t = est(x)
        rep = est(x[rng.integers(0, n, (B, n))])
        lo, hi = np.quantile(rep, [alpha / 2, 1 - alpha / 2])
        ee = rep.std(ddof=1)
        for j, (a, b) in enumerate(((t - z * ee, t + z * ee), (lo, hi), (2 * t - hi, 2 * t - lo))):
            cubre[j] += a <= verdad <= b
    print(f"{nombre:28s} {cubre[0] / R:8.3f} {cubre[1] / R:10.3f} {cubre[2] / R:8.3f}")

With 600 samples, each coverage’s Monte Carlo error (one standard deviation) is slightly over one percentage point near 0.9 and almost two points near 0.75, so differences of one point do not count. What does count: with n=20n = 20 no interval reaches 95% (not even for the mean of normal data, which stays at 0.92, whereas the exact tt interval would give 0.95); percentile clearly wins for the median (0.92 versus 0.79), basic fares somewhat better for standard deviation (0.77 versus 0.72), and the exponential standard deviation is around 0.75, far from the requested level. The practical conclusion: for skewed statistics and moderate nn do not stop at percentile; look at the second-order intervals in the next lesson and validate the procedure with a simulation like this when it matters.

The parametric bootstrap

The nonparametric bootstrap estimates FF with F^n\hat F_n. If the data are known (or assumed) to come from a family {Fϑ:ϑ∈Θ}\{F_\vartheta : \vartheta \in \Theta\}, there is a much more refined estimate of FF: Fϑ^F_{\hat\vartheta}, with ϑ^\hat\vartheta estimated.

It is exactly a simulation study, but with the estimated parameter instead of the true one. It has clear advantages when the model is reasonable:

  • It uses structural information, so it is often more efficient: for the same nn, sampling-distribution approximation error is smaller than in the nonparametric case.
  • It works with small nn, where F^n\hat F_n is a poor approximation; it does not have the problem of resamples with little variety.
  • It applies to statistics where the nonparametric method fails (extremes) and to calibrating tests when Wilks’s asymptotic approximation from lesson 11 is unreliable: simulate the likelihood ratio under H0H_0 with the estimated parameter.

And it has an unavoidable cost: if the model is misspecified, it inherits the model’s error, and no large sample cures that. The following cell implements both bootstraps and tests them in both situations.

[ ]Parametric versus nonparametric bootstrapBrowser
import numpy as np

rng = np.random.default_rng(5)

def ee_boot(x, sim, est, B=300):
    """Error estándar bootstrap; `sim` genera una matriz (B, n) de muestras simuladas."""
    return est(sim(x, B)).std(ddof=1)

# Caso 1: el modelo es correcto. Datos exponenciales (media 1), n = 15, estimando el percentil 90 de la
# población con el estimador de máxima verosimilitud  q90 = media * ln 10.
n, R = 15, 300
est = lambda m: m.mean(axis=1) * np.log(10)
verdad = est(rng.exponential(1, (20000, n))).std()
sim_param = lambda x, B: rng.exponential(x.mean(), (B, len(x)))                 # F_theta_hat
sim_nopar = lambda x, B: x[rng.integers(0, len(x), (B, len(x)))]                # F_hat_n
datos = rng.exponential(1, (R, n))
p = np.array([ee_boot(x, sim_param, est) for x in datos])
q = np.array([ee_boot(x, sim_nopar, est) for x in datos])
print("Modelo correcto (exponencial), n = 15")
print(f"  error estándar verdadero      : {verdad:.3f}")
print(f"  bootstrap paramétrico  media {p.mean():.3f}  desv. típica {p.std():.3f}")
print(f"  bootstrap no paramétrico media {q.mean():.3f}  desv. típica {q.std():.3f}")

# Caso 2: el modelo es incorrecto. Datos lognormales (n = 30), estadístico = media, pero se ajusta un modelo exponencial.
n = 30
verdad = rng.lognormal(0, 1, (20000, n)).mean(axis=1).std()
datos = rng.lognormal(0, 1, (R, n))
p = np.array([ee_boot(x, sim_param, lambda m: m.mean(axis=1)) for x in datos])
q = np.array([ee_boot(x, sim_nopar, lambda m: m.mean(axis=1)) for x in datos])
print("\nModelo incorrecto (datos lognormales, se supone exponencial), n = 30")
print(f"  error estándar verdadero      : {verdad:.3f}")
print(f"  bootstrap paramétrico  media {p.mean():.3f}   (sesgo {100 * (p.mean() / verdad - 1):+.0f} %)")
print(f"  bootstrap no paramétrico media {q.mean():.3f}   (sesgo {100 * (q.mean() / verdad - 1):+.0f} %)")

The lesson is twofold. With the correct model, the parametric method is more stable (less dispersion across samples) and barely biased, while the nonparametric method somewhat underestimates error at n=15n = 15 (the analogy F^n≈F\hat F_n \approx F is poor). With the wrong model, the parametric method confidently answers the wrong question, and its standard error is 23% below the truth (the nonparametric method is also short, by 11%, because at n=30n = 30 a lognormal tail is poorly represented in the sample). The rule: the parametric bootstrap is only as good as the model. If in doubt, test the model (using the goodness-of-fit methods in lesson 15) or use the nonparametric method.

The jackknife

Before the bootstrap came the jackknife (a pocket knife: a crude tool that serves many purposes; Quenouille 1949 and Tukey 1958): instead of randomly resampling, recalculate the statistic nn times, leaving out one observation each time.

The second equality for v^J\hat v_J is algebra: θ~i−θ~ˉ=−(n−1)(θ^(−i)−θ^(⋅))\tilde\theta_i - \bar{\tilde\theta} = -(n-1)(\hat\theta_{(-i)} - \hat\theta_{(\cdot)}). For the sample mean, v^J=S2/n\hat v_J = S^2/n exactly (the proof exercise in this lesson), so the jackknife generalizes the classical standard error. Unlike the bootstrap, dispersion of the nn jackknife replicates does not directly estimate that of the statistic: the replicates are very close (each shares n−2n-2 observations with any other), and the factor (n−1)/n(n-1)/n together with the undivided sum of squares rescales that dispersion to the standard error.

Bias, from order 1/n1/n to order 1/n21/n^2

Proof

Each θ^(−i)\hat\theta_{(-i)} is the estimator with n−1n - 1 observations, so E[θ^(−i)]=θ+an−1+b(n−1)2+c(n−1)3+O(n−4)\E[\hat\theta_{(-i)}] = \theta + \frac{a}{n-1} + \frac{b}{(n-1)^2} + \frac{c}{(n-1)^3} + \bigO(n^{-4}), and the same holds for its mean θ^(⋅)\hat\theta_{(\cdot)}. Thus

E[θ^J]=nE[θ^n]−(n−1)E[θ^(⋅)]=θ+b(1n−1n−1)+c(1n2−1(n−1)2)+O(n−3),\E[\hat\theta_J] = n\E[\hat\theta_n] - (n-1)\E[\hat\theta_{(\cdot)}] = \theta + b\Big(\frac1n - \frac{1}{n-1}\Big) + c\Big(\frac1{n^2} - \frac{1}{(n-1)^2}\Big) + \bigO(n^{-3}),

because the aa term cancels (n⋅an−(n−1)⋅an−1=0n\cdot\frac an - (n-1)\cdot\frac{a}{n-1} = 0) and remainders n O(n−4)n\,\bigO(n^{-4}) are O(n−3)\bigO(n^{-3}). As 1n−1n−1=−1n(n−1)\frac1n - \frac1{n-1} = -\frac{1}{n(n-1)} and 1n2−1(n−1)2=O(n−3)\frac1{n^2} - \frac1{(n-1)^2} = \bigO(n^{-3}), the claim follows.

∎

The canonical example: plug-in variance has E[σ^2]=σ2(1−1/n)\E[\hat\sigma^2] = \sigma^2(1 - 1/n), i.e. a=−σ2a = -\sigma^2 and b=0b = 0, and the jackknife corrects it exactly to S2S^2 (the ‘Bootstrap and jackknife from scratch’ cell below checks this). For more complicated estimators, bias disappears only to the order stated by the theorem, and correction has the same problem as bootstrap correction: it can add more noise than it removes.

Jackknife and influence function

A linearization shows why jackknife variance works. If θ^=T(F^n)\hat\theta = T(\hat F_n) with smooth TT, the difference produced by removing one observation is small and linear in that observation:

θ^(−i)−θ^≈−1n−1 Li,Li=valor de influencia empıˊrico de xi,\hat\theta_{(-i)} - \hat\theta \approx -\frac{1}{n-1}\,L_i, \qquad L_i = \text{valor de influencia empírico de } x_i,

and so θ~i≈θ^+Li\tilde\theta_i \approx \hat\theta + L_i and v^J≈1n2∑iLi2\hat v_J \approx \frac{1}{n^2}\sum_i L_i^2: the variance estimate by linearization (the same sandwich variance as for the MM-estimators in lesson 8). In other words, the jackknife evaluates the influence function without differentiating. That is its strength (deterministic, nn evaluations, no randomness) and its limitation: it sees only the linear approximation. For a nonsmooth statistic, linearization does not describe its reaction to removing a point.

Failure for the median

The extreme case is the median. With n=2m+1n = 2m + 1 ordered observations x(1)<⋯<x(n)x_{(1)} < \dots < x_{(n)}, the median is x(m+1)x_{(m+1)}. Removing one leaves an even number of observations and the median is the mean of the two central remaining observations, so only three possibilities exist:

θ^(−i)={12(x(m+1)+x(m+2))si se quita uno de los m datos inferiores,12(x(m)+x(m+1))si se quita uno de los m superiores,12(x(m)+x(m+2))si se quita el propio dato central.\hat\theta_{(-i)} = \begin{cases} \tfrac12\big(x_{(m+1)} + x_{(m+2)}\big) & \text{si se quita uno de los } m \text{ datos inferiores,} \\[2pt] \tfrac12\big(x_{(m)} + x_{(m+1)}\big) & \text{si se quita uno de los } m \text{ superiores,} \\[2pt] \tfrac12\big(x_{(m)} + x_{(m+2)}\big) & \text{si se quita el propio dato central.} \end{cases}

The nn pseudo-values take three distinct values (two if nn is even). That is very little information: jackknife variance depends only on the two spacings s1=x(m+1)−x(m)s_1 = x_{(m+1)} - x_{(m)} and s2=x(m+2)−x(m+1)s_2 = x_{(m+2)} - x_{(m+1)} around the median, and those spacings are random and do not concentrate as nn grows.

Proof

Sketch. With vˉ=12(v1+v2)\bar v = \frac12(v_1 + v_2), where v1v_1 and v2v_2 are the first two values in the table (those occurring mm times each), the central value contributes O(n−2)\bigO(n^{-2}) and

v^J=n−1n[m (v1−vˉ)2+m (v2−vˉ)2+O(1)],v1−v2=12(s1+s2),\hat v_J = \frac{n-1}{n}\Big[m\,(v_1 - \bar v)^2 + m\,(v_2 - \bar v)^2 + \bigO(1)\Big], \qquad v_1 - v_2 = \tfrac12(s_1 + s_2),

so v^J≈n16(s1+s2)2\hat v_J \approx \frac{n}{16}(s_1 + s_2)^2. The spacings of order statistics around the median, multiplied by nf(μ1/2)n f(\mu_{1/2}), converge jointly to independent exponentials with mean 1 (a classical order-statistics result): sj≈Ej/(nf)s_j \approx E_j/(nf). Substituting, v^J≈(E1+E2)2/(16 nf2)\hat v_J \approx (E_1 + E_2)^2/(16\,n f^2) and division by 1/(4nf2)1/(4nf^2) yields (E1+E2)2/4(E_1 + E_2)^2/4. The mean is E[(E1+E2)2]/4=(2+4)/4=3/2\E[(E_1 + E_2)^2]/4 = (2 + 4)/4 = 3/2, because E1+E2∼Gamma(2,1)E_1 + E_2 \sim \mathrm{Gamma}(2, 1).

∎

The jackknife for the median errs by a random factor that does not vanish with nn: the ratio of jackknife to true standard error has, even for enormous nn, a 10% probability of falling below 0.270.27 and another 10% of exceeding 1.941.94. (Its mean is 1, but the mean jackknife variance is 50% larger than the true variance.) With even n=2mn = 2m, failure is worse: pseudo-values take only two values, θ^(−i)∈{x(m),x(m+1)}\hat\theta_{(-i)} \in \{x_{(m)}, x_{(m+1)}\}, jackknife variance depends on one spacing, and the same argument gives limit E12E_1^2, with mean 2 (also written (χ22/2)2(\chi^2_2/2)^2, since χ22/2∼Exp(1)\chi^2_2/2 \sim \mathrm{Exp}(1)). Bootstrap, by contrast, resamples with replacement and resample medians take many distinct values: their distribution converges to the correct one. This lesson is one of the few occasions when more data do not fix a variance estimator.

InteractiveThe jackknife and the median
Centered pseudovalues θ~i−θ^\tilde\theta_i - \hat\theta from a sample with n=81n = 81 (in units of n SE\sqrt n\,\mathrm{SE})
Estimated / true standard error ratio, in 60 samples for each nn
True SE
  • jackknife
  • bootstrap (B = 100)
Statistic
81
Distinct values among the nn leave-one-out estimates3 of 81
This sample: jackknife SE | bootstrap SE | true SE0.185 | 0.119 | 0.140
Estimated SE / true SE, 60 samples with n=81n = 81: jackknife0.88 (0.24 to 2.11)
Estimated SE / true SE: bootstrap1.03 (0.75 to 1.32)
With n=81n = 81, the 81 leave-one-out estimates take only 3 distinct values, and the jackknife standard error of this sample is 0.185 versus the true 0.140. Across samples, the jackknife-to-true ratio ranges from 0.24 to 2.11 (10th and 90th percentiles) and does not narrow as nn grows; the bootstrap ratio ranges from 0.75 to 1.32.
Left: pseudo-values of one sample (from a normal distribution), one for each omitted observation. For the mean they are the centered data; for the median, only a few distinct levels appear. Right: ratio of estimated to true standard error in 60 samples of each size nn. For the mean, jackknife (red) converges to 1 and is exact. For the median, the red cloud does not narrow as nn grows, whereas the blue one (bootstrap with 100 replicates) does. Try n=11n = 11 and n=641n = 641. How many distinct leave-one-out estimates are there among the 641?

A remedy exists: the delete-dd jackknife, which removes dd observations at a time and is consistent for the median if n/d→0\sqrt n/d \to 0 and n−d→∞n - d \to \infty (Shao and Wu, 1989). For suitable dd, however, it costs as much as a bootstrap, and bootstrap is what is used. The jackknife retains its unrivaled role: a cheap deterministic bias and variance estimator for smooth statistics, and the foundation for modern tools such as leave-one-out cross-validation and estimation of individual observation influence.

BootstrapJackknife
Statistic evaluationsBB (hundreds to thousands)nn
Randomnessyes (Monte Carlo error)none
Nonsmooth statistics (median, quantiles)yesfails
Intervalsyes (percentile, basic, …)not directly
Biasyesyes, to order n−2n^{-2}
IdeaF^n→\hat F_n \to random resampleslinearization, F^n→\hat F_n \to remove one observation

The following cell implements everything from scratch: vectorized bootstrap (the B×nB \times n index matrix is generated at once), standard error, bias, percentile and basic intervals, parametric bootstrap, and jackknife, and validates them on cases with known answers. This is the reference implementation you will use throughout the rest of the course.

[ ]Bootstrap and jackknife from scratchBrowser
import numpy as np

# ---------- bootstrap no paramétrico (todo vectorizado) ----------
def remuestras(x, B, rng):
    """Matriz (B, n) con B remuestras de x, con reemplazo."""
    x = np.asarray(x)
    return x[rng.integers(0, len(x), (B, len(x)))]

def bootstrap(x, estadistico, B=2000, seed=0):
    """Réplicas bootstrap. `estadistico(a, axis=-1)` debe aceptar una matriz y reducir sobre el último eje."""
    return estadistico(remuestras(x, B, np.random.default_rng(seed)), axis=-1)

def error_estandar(rep):
    return rep.std(ddof=1)

def sesgo(rep, theta_hat):
    return rep.mean() - theta_hat

def ic_percentil(rep, alpha=0.05):
    lo, hi = np.quantile(rep, [alpha / 2, 1 - alpha / 2])
    return lo, hi

def ic_basico(rep, theta_hat, alpha=0.05):
    lo, hi = np.quantile(rep, [alpha / 2, 1 - alpha / 2])
    return 2 * theta_hat - hi, 2 * theta_hat - lo

# ---------- bootstrap paramétrico ----------
def bootstrap_parametrico(x, ajustar, simular, estadistico, B=2000, seed=0):
    """ajustar(x) -> parámetros; simular(par, B, n, rng) -> matriz (B, n); se vuelve a ajustar en cada muestra."""
    rng = np.random.default_rng(seed)
    par = ajustar(x)
    return estadistico(simular(par, B, len(x), rng), axis=-1)

# ---------- jackknife ----------
def jackknife(x, estadistico):
    """Estimadores dejando uno fuera, sesgo y error estándar jackknife."""
    x = np.asarray(x)
    n = len(x)
    loo = estadistico(x[(np.arange(n)[:, None] + np.arange(1, n)) % n], axis=-1)    # fila i = todos menos x_i, (n,)
    th = estadistico(x)
    sesgo_j = (n - 1) * (loo.mean() - th)
    ee_j = np.sqrt((n - 1) / n * ((loo - loo.mean()) ** 2).sum())
    return loo, sesgo_j, ee_j

# ---------- validación con casos de respuesta conocida ----------
rng = np.random.default_rng(7)
x = rng.normal(10, 2, 40)
n = len(x)

rep = bootstrap(x, np.mean, B=20000)
print("1) media: bootstrap", round(error_estandar(rep), 4), "| fórmula del bootstrap ideal", round(np.sqrt(x.var() / n), 4))

_, _, ee_j = jackknife(x, np.mean)
print("2) media: jackknife", round(ee_j, 6), "| s/sqrt(n)", round(x.std(ddof=1) / np.sqrt(n), 6), "(idénticos)")

loo, sesgo_j, _ = jackknife(x, np.var)                      # varianza plug-in (ddof = 0)
print("3) varianza plug-in: corregida con jackknife", round(np.var(x) - sesgo_j, 6), "| S^2 =", round(x.var(ddof=1), 6), "(idénticas)")

rb = bootstrap(x, np.median, B=4000)
print("4) mediana: percentil", np.round(ic_percentil(rb), 3), "| básico", np.round(ic_basico(rb, np.median(x)), 3), "| sesgo boot", round(sesgo(rb, np.median(x)), 4))

# paramétrico: normal con media y desviación estimadas, estadístico = media
sim_norm = lambda par, B, n, rng: rng.normal(par[0], par[1], (B, n))
rp = bootstrap_parametrico(x, lambda a: (a.mean(), a.std(ddof=1)), sim_norm, np.mean, B=20000)
print("5) media: bootstrap paramétrico", round(error_estandar(rp), 4), "| s/sqrt(n)", round(x.std(ddof=1) / np.sqrt(n), 4))

The five checks show the code is correct: standard errors for the mean agree with the formulas, the jackknife reproduces S2/nS^2/n exactly and corrects plug-in variance to S2S^2, and the parametric method with a normal model converges to the same value. Now, jackknife failure for the median and the theorem’s limiting distribution:

[ ]The jackknife for the median, measuredBrowser
import numpy as np

rng = np.random.default_rng(11)

def jack_var(x, estadistico):
    n = len(x)
    loo = estadistico(x[(np.arange(n)[:, None] + np.arange(1, n)) % n], axis=-1)
    return (n - 1) / n * ((loo - loo.mean()) ** 2).sum(), len(np.unique(loo))

print("   n   valores distintos   var jackknife / var verdadera: media  p10  p50  p90")
for n in (21, 81, 321):
    var_verdadera = np.median(rng.normal(0, 1, (4000, n)), axis=1).var(ddof=1)
    r, k = zip(*[jack_var(rng.normal(0, 1, n), np.median) for _ in range(300)])
    r = np.array(r) / var_verdadera
    print(f"{n:4d}   {max(k):9d}            {r.mean():17.2f} {np.quantile(r, .1):7.2f}{np.quantile(r, .5):6.2f}{np.quantile(r, .9):6.2f}")

E = rng.exponential(1, (200000, 2))
L = ((E.sum(axis=1)) / 2) ** 2
print(f"\nlímite teórico ((E1+E2)/2)^2:        media {L.mean():5.2f}  p10 {np.quantile(L, .1):.2f}  p50 {np.quantile(L, .5):.2f}  p90 {np.quantile(L, .9):.2f}")

How many replicates?

One last ingredient: Monte Carlo error. Each quantity extracted from the BB replicates is itself an estimate, and its error depends on the use.

For standard error. The sample standard deviation of BB independent replicates with kurtosis κ\kappa has approximate relative variance (κ−1)/(4B)(\kappa - 1)/(4B) (delta method applied to sample variance, whose variance is σ4(κ−1)/B\sigma^4(\kappa - 1)/B). Its coefficient of variation is

CV(SE^B)≈κ−14B  =κ=3  12B.\mathrm{CV}\big(\widehat{\mathrm{SE}}_B\big) \approx \sqrt{\frac{\kappa - 1}{4B}} \;\stackrel{\kappa = 3}{=}\; \frac{1}{\sqrt{2B}}.

With B=200B = 200 it is 5%; with B=50B = 50, 10%. Since statistical error in the bootstrap is already of that order or greater, a few hundred replicates suffice.

For interval endpoints. A sample quantile at level pp from BB replicates has standard deviation p(1−p)/B / f(qp)\sqrt{p(1-p)/B}\,/\,f(q_p), where ff is the bootstrap density. For the 2.5% quantile of a normal distribution with standard deviation σ∗\sigma_\ast, f(q0.025)=φ(1.96)/σ∗=0.0584/σ∗f(q_{0.025}) = \varphi(1.96)/\sigma_\ast = 0.0584/\sigma_\ast and

sd(q^0.025)≈0.025×0.9750.0584B σ∗≈2.67B σ∗.\mathrm{sd}\big(\hat q_{0.025}\big) \approx \frac{\sqrt{0.025 \times 0.975}}{0.0584\sqrt B}\,\sigma_\ast \approx \frac{2.67}{\sqrt B}\,\sigma_\ast.

With B=1000B = 1000 it is 0.084 σ∗0.084\,\sigma_\ast, and with B=200B = 200, 0.19 σ∗0.19\,\sigma_\ast, almost four times as much relative noise as for standard error, because the extreme quantile relies on very few replicates (only 5 out of 200 are below 2.5%). Classical recommendations (Efron and Tibshirani, 1993) reflect this: a few hundred replicates for standard errors and at least a thousand for intervals. With current computational costs, B=10 000B = 10\,000 is a convenient choice for interval endpoints: Monte Carlo standard deviation falls to 0.027 σ∗0.027\,\sigma_\ast.

InteractiveHow many replicates?
Bootstrap standard error with BB replicates, divided by its ideal value (24 runs)
  • one run
  • 10th to 90th percentiles
  • theory: 1 ± 1.28·√((κ−1)/4B)
  • selected B
95% percentile interval from each run with B=100B = 100
ideal
  • interval from one run
  • ideal interval (B → ∞)
Statistic
100
Ideal standard error (B→∞B \to \infty)0.1423
Ideal 95% percentile interval[0.889, 1.444]
Standard error CV with B=100B = 100: simulated | theory5.2 % | 7.0 %
Lower endpoint SD, in standard errors: simulated | theory0.201 | 0.247
Upper endpoint SD, in standard errors: simulated | theory0.251 | 0.285
With B=100B = 100 the standard error varies 5 % across runs (its coefficient of variation), and interval endpoints vary more: their standard deviations across runs are 0.20 and 0.25 standard errors. Two analysts with the same data would obtain different intervals.
A fixed dataset (n = 30, lognormal) and 24 independent bootstrap runs. Left: standard error with the first BB replicates of each run, divided by its ideal value; the shaded band contains the central 80% of runs and the dashed orange lines are the theoretically predicted 80% band, 1±1.28(κ−1)/(4B)1 \pm 1.28\sqrt{(\kappa - 1)/(4B)}. Right: the 95% percentile interval each run would give with the chosen BB: what two analysts with the same data and different seeds would see. Move BB from 10 to 4000. At what BB does standard error stabilize? And the endpoints? Switch to median: it is more irregular and its endpoints noisier. Notice that the ideal interval at the end is not the true one, only the one from this sample.

The figure’s final takeaway: replicates reduce Monte Carlo error, not statistical error. With B=4000B = 4000 the 24 runs agree almost exactly, but their limiting interval still follows from this sample of 30 observations; another sample would give another interval. Only more data reduce that uncertainty. Two practical details: if the pp quantile is defined as ordered replicate number (B+1)p(B+1)p (the classical convention, not the default linear interpolation of np.quantile), choosing BB such that (B+1) α/2(B+1)\,\alpha/2 is an integer (with α=0.05\alpha = 0.05, B=999B = 999 or 99999999) makes endpoints actual replicates without interpolation; fixing the seed makes the analysis reproducible (but no less uncertain: change it to see Monte Carlo error).

[ ]Bootstrap Monte Carlo error, measuredBrowser
import numpy as np

rng = np.random.default_rng(2)
x = np.random.default_rng(7).lognormal(0, 0.8, 30)            # un conjunto de datos fijo, n = 30
n = len(x)
mediana = lambda m: np.median(m, axis=1)

ideal = mediana(x[rng.integers(0, n, (200_000, n))])           # ~ B infinito
ee0 = ideal.std(ddof=1)
print(f"B → ∞: error estándar {ee0:.4f}, intervalo percentil 95 % [{np.quantile(ideal, .025):.3f}, {np.quantile(ideal, .975):.3f}]")
print("\n   B    CV del EE (50 ejecuciones)   sd del extremo 2.5 % (en EE)   sd del extremo 97.5 % (en EE)")
for B in (25, 100, 400, 2000):
    ee, lo, hi = [], [], []
    for _ in range(50):
        r = mediana(x[rng.integers(0, n, (B, n))])
        ee.append(r.std(ddof=1))
        q = np.quantile(r, [.025, .975])
        lo.append(q[0]); hi.append(q[1])
    print(f"{B:5d}   {np.std(ee) / ee0:22.3f}   {np.std(lo) / ee0:27.3f}   {np.std(hi) / ee0:30.3f}")

Bootstrap for machine-learning metrics

A use case where bootstrap is almost mandatory: reporting uncertainty in a metric on a test set. A model with F1F_1 of 0.880.88 measured on 600 examples does not have F1F_1 of 0.880.88: it has an estimate with error. And the metric (AUC, F1F_1, the largest of several accuracies, accuracy on a class tail) generally lacks a simple standard-error formula. Three principles.

1. Resample test examples, do not retrain. Given the mm test (prediction, label) pairs, resample the indices and recalculate the metric. This quantifies uncertainty from the finite test-set size. It does not quantify training variability (seed, data split): that requires retraining, which is a different and much more expensive task.

2. Resample the independent unit. Data from one user, conversation, or document are not independent of each other. If the test has UU users with ss sessions each and we resample rows, bootstrap assumes UsUs independent observations and underestimates error. Resample users, with all their rows (cluster bootstrap). Standard-error inflation follows the design effect seen in cluster sampling, 1+(s−1)ρ1 + (s-1)\rho for variance, with ρ\rho the intraclass correlation.

3. Compare models using paired differences. When two models are evaluated on the same examples, their errors are correlated (difficult examples are difficult for both). Resampling the same indices for both models and calculating the difference of metrics gives a much narrower interval than bootstrapping each separately and subtracting. It is the same argument as for paired tests, and the same rule: the analysis unit is the pair.

[ ]Confidence intervals for classifier metricsBrowser
import numpy as np
from scipy.stats import rankdata
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=1800, n_features=12, n_informative=5, n_redundant=2, flip_y=0.06, class_sep=0.9, random_state=3)
Xtr, ytr, Xte, yte = X[:1200], y[:1200], X[1200:], y[1200:]
modelo_a = RandomForestClassifier(n_estimators=40, max_depth=6, random_state=0).fit(Xtr, ytr)
modelo_b = RandomForestClassifier(n_estimators=40, max_depth=8, random_state=0).fit(Xtr, ytr)
pa, pb = modelo_a.predict_proba(Xte)[:, 1], modelo_b.predict_proba(Xte)[:, 1]
m = len(yte)

# métricas vectorizadas: cada una acepta matrices (B, m) y reduce sobre el último eje
def exactitud(yt, p):
    return ((p > 0.5) == yt).mean(axis=-1)

def f1(yt, p):
    pred = p > 0.5
    tp, fp, fn = (pred & (yt == 1)).sum(-1), (pred & (yt == 0)).sum(-1), (~pred & (yt == 1)).sum(-1)
    return 2 * tp / (2 * tp + fp + fn)

def auc(yt, p):                                    # estadístico de Mann-Whitney con rangos
    r = rankdata(p, axis=-1)
    n1, n0 = (yt == 1).sum(-1), (yt == 0).sum(-1)
    return ((r * (yt == 1)).sum(-1) - n1 * (n1 + 1) / 2) / (n1 * n0)

rng = np.random.default_rng(0)
B = 2000
idx = rng.integers(0, m, (B, m))                   # los mismos índices para todas las métricas y modelos

print(f"conjunto de test: {m} ejemplos, B = {B}\n")
print("métrica      modelo   estimación   error estándar   IC percentil 95 %")
for nombre, metrica in (("exactitud", exactitud), ("F1", f1), ("AUC", auc)):
    for etiqueta, p in (("A", pa), ("B", pb)):
        rep = metrica(yte[idx], p[idx])
        lo, hi = np.quantile(rep, [.025, .975])
        print(f"{nombre:10s}      {etiqueta}      {metrica(yte, p):.4f}       {rep.std(ddof=1):.4f}        [{lo:.4f}, {hi:.4f}]")

The intervals for A and B overlap on some metrics. Does that mean they cannot be distinguished? No: overlap of two intervals is not a test. What is needed is the interval for the difference, and pairing makes the difference there.

[ ]Paired difference between two models, and bootstrap by userBrowser
import numpy as np
from scipy.stats import rankdata
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=1800, n_features=12, n_informative=5, n_redundant=2, flip_y=0.06, class_sep=0.9, random_state=3)
Xtr, ytr, Xte, yte = X[:1200], y[:1200], X[1200:], y[1200:]
pa = RandomForestClassifier(n_estimators=40, max_depth=6, random_state=0).fit(Xtr, ytr).predict_proba(Xte)[:, 1]
pb = RandomForestClassifier(n_estimators=40, max_depth=8, random_state=0).fit(Xtr, ytr).predict_proba(Xte)[:, 1]
m = len(yte)
exactitud = lambda yt, p: ((p > 0.5) == yt).mean(axis=-1)

rng = np.random.default_rng(0)
B = 2000
idx, idx2 = rng.integers(0, m, (B, m)), rng.integers(0, m, (B, m))

d_pareada = exactitud(yte[idx], pb[idx]) - exactitud(yte[idx], pa[idx])        # mismos índices
d_ingenua = exactitud(yte[idx2], pb[idx2]) - exactitud(yte[idx], pa[idx])      # un bootstrap por modelo
obs = exactitud(yte, pb) - exactitud(yte, pa)
print(f"diferencia de exactitud B - A: {obs:+.4f}")
print(f"  bootstrap pareado   : error estándar {d_pareada.std(ddof=1):.4f}, IC 95 % [{np.quantile(d_pareada, .025):+.4f}, {np.quantile(d_pareada, .975):+.4f}]")
print(f"  bootstrap ingenuo   : error estándar {d_ingenua.std(ddof=1):.4f}, IC 95 % [{np.quantile(d_ingenua, .025):+.4f}, {np.quantile(d_ingenua, .975):+.4f}]")

# --- ahora, la unidad independiente: 150 usuarios con 8 sesiones, y tasas de error distintas por usuario ---
U, s = 150, 8
tasa = rng.beta(2, 6, U)                                         # error propio de cada usuario
err = rng.random((U, s)) < tasa[:, None]                         # True = el modelo falla en esa sesión
filas = err.ravel()
rep_filas = 1 - filas[rng.integers(0, filas.size, (B, filas.size))].mean(axis=1)    # remuestra filas
rep_users = 1 - err[rng.integers(0, U, (B, U))].mean(axis=(1, 2))                   # remuestra usuarios
print(f"\nexactitud global {1 - filas.mean():.4f} con {filas.size} sesiones de {U} usuarios")
print(f"  bootstrap por filas    : error estándar {rep_filas.std(ddof=1):.4f}")
print(f"  bootstrap por usuarios : error estándar {rep_users.std(ddof=1):.4f}   (cociente {rep_users.std(ddof=1) / rep_filas.std(ddof=1):.2f}, efecto de diseño {(rep_users.std(ddof=1) / rep_filas.std(ddof=1)) ** 2:.2f})")

The two results are bootstrap’s practical lesson for machine learning. First, the models’ accuracy difference is 2 points, and its paired interval excludes 0, while naive bootstrap (which ignores that both models fail on the same examples) includes it: a real improvement would be missed. Second, with sessions grouped by user, the correct standard error is substantially greater than that of row bootstrap, which would give a false sense of precision. This is recommended practice for reporting benchmark results (the hierarchical bootstrap in the research module), and bootstrap ensembles in the reliability module are a classical way to estimate epistemic uncertainty (there one does retrain on each resample).

With libraries: scipy.stats.bootstrap

SciPy implements bootstrap with percentile, basic and BCa intervals (the second-order interval of the next lesson), resampling one or more arguments and a paired mode. The implementation above and SciPy’s should agree apart from Monte Carlo error:

[ ]Own implementation versus scipy.stats.bootstrapBrowser
import numpy as np
from scipy.stats import bootstrap

rng = np.random.default_rng(4)
x = rng.exponential(2.0, 40)
n = len(x)

# propia
rep = np.median(x[rng.integers(0, n, (9999, n))], axis=1)
lo, hi = np.quantile(rep, [.025, .975])
print(f"propia, percentil     : [{lo:.4f}, {hi:.4f}]   error estándar {rep.std(ddof=1):.4f}")

# scipy: percentil, básico y BCa, con la misma estimación
for metodo in ("percentile", "basic", "BCa"):
    res = bootstrap((x,), np.median, confidence_level=0.95, n_resamples=9999, method=metodo, random_state=rng)
    print(f"scipy, {metodo:10s}     : [{res.confidence_interval.low:.4f}, {res.confidence_interval.high:.4f}]   error estándar {res.standard_error:.4f}")

# datos pareados: dos modelos evaluados sobre los mismos 40 ejemplos (puntuaciones por ejemplo)
a = rng.normal(0.70, 0.15, n)
b = a + rng.normal(0.03, 0.05, n)                         # el segundo modelo mejora 0.03 de media, con ruido pequeño
dif = lambda u, v, axis: np.mean(v - u, axis=axis)
res = bootstrap((a, b), dif, paired=True, vectorized=True, method="percentile", n_resamples=5000, random_state=rng)
print(f"\ndiferencia pareada de medias, IC 95 %: [{res.confidence_interval.low:.4f}, {res.confidence_interval.high:.4f}]  (media observada {np.mean(b - a):.4f})")

Three usage details. The statistic must accept axis for vectorized mode (which makes it orders of magnitude faster; otherwise SciPy loops). Data go inside a tuple ((x,)), because the function accepts multiple samples. And the default method is 'BCa', which corrects bias and skew and is often better than the two above; until you understand it, always inspect more than one method and be skeptical if they disagree.

Common mistakes

Exercises

NumericAn observation absent from the resample
A sample of n=100n = 100 distinct observations is resampled with replacement. What is the probability that a particular observation does not appear in the resample?
ProofThe jackknife of the mean is exact
Prove: For the estimator θ^=xˉ\hat\theta = \bar x of the mean, jackknife variance is exactly v^J=S2/n\hat v_J = S^2/n, with S2=1n−1∑i(xi−xˉ)2S^2 = \frac{1}{n-1}\sum_i (x_i - \bar x)^2.
0
Let θ^(−i)\hat\theta_{(-i)} be the mean of the n−1n - 1 observations left after removing xix_i, and θ^(⋅)=1n∑iθ^(−i)\hat\theta_{(\cdot)} = \frac1n\sum_i \hat\theta_{(-i)}. Recall v^J=n−1n∑i(θ^(−i)−θ^(⋅))2\hat v_J = \frac{n-1}{n}\sum_i (\hat\theta_{(-i)} - \hat\theta_{(\cdot)})^2.

Step 1 of 4. What are θ^(−i)\hat\theta_{(-i)} and θ^(⋅)\hat\theta_{(\cdot)}?

NumericHow many distinct resamples?
A sample has n=3n = 3 distinct observations. Counting resamples as multisets (order does not matter), how many different bootstrap resamples exist?
CodeThe basic bootstrap interval
Complete ic_basico(x, estadistico, B, alpha, seed): generate B resamples of x with replacement (index matrix of shape (B, n) using np.random.default_rng(seed)), compute the statistic on each with estadistico(remuestras, axis=1) and return the tuple (inf, sup) for the level-1 - alpha basic bootstrap interval: (2 * theta - q_alto, 2 * theta - q_bajo), where theta = estadistico(x) and q_bajo, q_alto are the alpha/2 and 1 - alpha/2 quantiles of the replicates. Do not loop over resamples.
import numpy as np

def ic_basico(x, estadistico, B=2000, alpha=0.05, seed=0):
  """Intervalo bootstrap básico de nivel 1 - alpha para estadistico(x)."""
  x = np.asarray(x, dtype=float)
  n = len(x)
  rng = np.random.default_rng(seed)
  # tu código: theta, réplicas bootstrap, cuantiles y reflexión
  return (0.0, 0.0)
Shift+Enter to run
QuizWhich error is not reduced by more replicates?
An analyst calculates a percentile bootstrap interval with B=1000B = 1000 and finds it too wide to publish. What should they propose?
NumericReplicates for an interval endpoint
A statistic's bootstrap distribution is approximately normal with standard deviation σ∗\sigma_\ast. You want the endpoint of a 95% percentile interval (the 2.5 %2.5\,\% quantile of the replicates) to have Monte Carlo standard deviation at most 0.05 σ∗0.05\,\sigma_\ast. How many BB replicates are needed? Use sd(q^p)≈p(1−p)/B / f(qp)\mathrm{sd}(\hat q_p) \approx \sqrt{p(1-p)/B}\,/\,f(q_p).
QuizWhat to resample
You evaluate a recommendation model on 20,000 interactions from 500 users (about 40 per user). You want a bootstrap interval for recall@10. What do you do?

Summary

Key idea
Bootstrap applies the plug-in principle to the sampling distribution: replace the unknown population with the empirical distribution and simulate, giving any statistic a standard error, bias and interval without formulas. It works for smooth statistics, inherits sample randomness, and its replicates reduce only Monte Carlo error, never statistical error.
  • Plug-in. A parameter is a functional θ=T(F)\theta = T(F), estimated by T(F^n)T(\hat F_n). The sampling distribution of θ^\hat\theta is also a functional of FF, and estimating it by plug-in is bootstrap.
  • Nonparametric bootstrap. Resample nn observations with replacement, recompute, and repeat BB times. It bets that error R∗=θ^∗−θ^R^\ast = \hat\theta^\ast - \hat\theta resembles R=θ^−θR = \hat\theta - \theta. It is consistent for the mean (Bickel, Freedman and Singh) and inherits normality from the central limit theorem.
  • The resample. Multinomial counts: each observation is absent with probability (1−1/n)n→e−1(1-1/n)^n \to e^{-1} (a resample contains 63.2% distinct observations), there are (2n−1n)\binom{2n-1}{n} multisets, and the maximum repeats with probability ≥0.632\ge 0.632 (bootstrap fails for extremes).
  • Standard error, bias and intervals. SE^B\widehat{\mathrm{SE}}_B is the replicates’ standard deviation; bootstrap bias is rarely worth subtracting (rule ∣sesgo∣/SE>0.25\abs{\mathrm{sesgo}}/\mathrm{SE} > 0.25). Percentile [qα/2∗,q1−α/2∗][q^\ast_{\alpha/2}, q^\ast_{1-\alpha/2}] and basic [2θ^−q1−α/2∗,2θ^−qα/2∗][2\hat\theta - q^\ast_{1-\alpha/2}, 2\hat\theta - q^\ast_{\alpha/2}] coincide for symmetric bootstrap; percentile is invariant under increasing transformations. Both are first-order and their coverage with small nn falls below nominal.
  • Parametric bootstrap. Simulate from Fϑ^F_{\hat\vartheta} instead of F^n\hat F_n: more efficient if the model is correct, false if not.
  • Jackknife. v^J=n−1n∑(θ^(−i)−θ^(⋅))2\hat v_J = \frac{n-1}{n}\sum(\hat\theta_{(-i)} - \hat\theta_{(\cdot)})^2, exact for the mean (S2/nS^2/n), reduces bias from order 1/n1/n to 1/n21/n^2 and linearizes the influence function. For the median it sees only three distinct values and its standard error converges to (E1+E2)/2(E_1 + E_2)/2, not the truth: it is inconsistent.
  • Replicates. CV(SE^B)≈(κ−1)/(4B)\mathrm{CV}(\widehat{\mathrm{SE}}_B) \approx \sqrt{(\kappa-1)/(4B)}: hundreds for standard error. Interval endpoints require thousands (standard deviation of a 2.5% quantile is ≈2.67 σ∗/B\approx 2.67\,\sigma_\ast/\sqrt B). Increasing BB does not reduce statistical error.
  • Machine-learning metrics. Resample test examples (do not retrain), the independent unit (user, document), and the same indices for two models in a paired difference. scipy.stats.bootstrap offers percentile, basic and BCa, with paired mode.