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
- 05Empirical CDF and sample quantilesSampling distributionStandard errorBias of an estimatorMean squared error bias-variance decompositionConfidence interval and coverageMaximum likelihood estimator (MLE)Simulation study (ADEMP)Paired design and paired test
- 04Bernoulli-trial distributionsWeak law of large numbersStrong law of large numbersCentral limit theorem
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 , 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.
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:
- Why does it work? The plug-in principle: replace the unknown population with the empirical distribution, including for the sampling distribution.
- What exactly is a resample? A multinomial count vector with surprising consequences (63.2 %, maximum).
- What can be estimated? Standard error, bias and intervals (percentile and basic), and when parametric bootstrap helps.
- What about jackknife? Its deterministic predecessor, its formulas and why it fails for the median.
- 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, “” variances, medians and empirical percentiles are plug-in estimates. The principle does not give the best estimator: plug-in variance is biased by factor , as in estimators. It gives the obvious estimator, valid under mild conditions.
Proof
By Glivenko–Cantelli, almost surely. Continuity of at turns uniform convergence into .
∎The assumption is stronger than it looks: the mean is not continuous in sup norm (move mass arbitrarily far to change the mean arbitrarily without letting exceed ), yet 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 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 is itself a functional of :
It depends on (shape, tails, skew) and . If is unknown, estimate it plug-in using . That is bootstrap.
Nonparametric bootstrap
is rarely closed-form, but can be simulated as much as needed:
- For : choose uniform indices from with replacement, form , calculate .
- Summarize replicates : , , interval quantiles.
Two worlds
Understand in parallel. In the real world, population produces sample , yielding ; repeated experiments give the sampling distribution. In the bootstrap world, serves as population, produces resample , yielding .
| Real world | Bootstrap world | |
|---|---|---|
| Population | (unknown) | (known) |
| Data | ||
| Parameter | ||
| Estimate | ||
| Estimation error |
Bootstrap does not assume resembles or resembles . It assumes bootstrap-world error behaves like real-world error . The figure shows this.
Three readings:
- Center belongs to the sample, not population. Bootstrap distribution is centered at (more precisely around it), not . 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 error.
- It improves with , not . At bootstrap shape is a poor approximation, especially for median; at it resembles truth. More replicates only smooth the right histogram.
Two sources of error
The approximation has two steps, each with error:
Statistical error comes from and shrinks only with more data. Monte Carlo error comes from simulating rather than calculating exactly, and shrinks with more replicates (free compared with collecting data). Confusing them is the most frequent conceptual error: increasing 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 , are iid with mean and variance , converging almost surely to (strong law). To apply Lindeberg–Feller to the triangular array, verify Lindeberg’s condition for each :
Indeed, for fixed and large , , so the term is at most , which by the strong law tends to , tending to 0 as by dominated convergence. Thus almost surely conditionally; continuity of the limit makes convergence uniform (Pólya). The CLT also gives and . 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:
almost the classical standard error, with factor from plug-in variance. This is a good implementation smoke test:
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- resample is determined by how often each observation was selected, and those counts have an explicit distribution.
Proof
Each of draws independently selects with probability : the multinomial definition, with binomial marginal . Observation is absent if no draw selects it, probability , tending to (classic limit ). A size- multiset over elements solves in nonnegative integers, counted by stars and bars as . This count depends on . For (3), assume ordered untied data. Observed maximum appears unless no draw selects it; when present it is the resample maximum: probability , decreasing toward from above (for it is ).
∎For distinct values there are multiset resamples, not equally likely: three “triples” each occur with probability , six “doubles” with , and the “balanced” with (sum ). Ideal bootstrap is enumerable for small , but with already has multisets: simulation is practical.
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. : bootstrap invents no data, it changes weights from to with . This connects bootstrap to jackknife (weight 0 for one observation, for others) and modern variants (weighted, Bayesian bootstrap).
The maximum resists bootstrap. Bootstrap sample-maximum distribution has an atom of mass 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.
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 . This answers the motivating question for any computable statistic.
Bootstrap bias applies the two-world analogy to bias : in the bootstrap world, . For plug-in variance from a sample with and , true bias is , and bootstrap estimates near that.
A tempting consequence: subtract known bias. The corrected estimator is
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 exceeds about . The cell checks three estimators, repeating the entire procedure (sample, bootstrap, correction) hundreds of times to measure actual MSE.
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 ( standard errors), because bootstrap bias estimation for nonsmooth statistics is especially noisy. For plug-in variance, with bias () near threshold, correction also loses (8 % worse). Only for , a smooth function of the mean with bias – standard errors, does correction help (16 % and 24 % lower MSE, more at smaller ). 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 yields several intervals. Three simple ones share an idea but treat skew differently.
Normal interval. If is approximately normal, . Bootstrap supplies only standard error.
Basic (pivotal) interval. Start with the two-world analogy. If is the quantile of error , then ; solving for ,
The are unknown, but bootstrap error has quantiles , where is the quantile of replicates. Substitute:
the percentile interval reflected about .
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 , basic endpoints are and . (2) Quantiles commute with increasing maps: . But unless is affine. (3) Set and . Real world gives , and by hypothesis bootstrap reproduces , so has quantiles . The basic interval for is , which by symmetry equals , the percentile interval for ; coverage is because . By (2), transforming by gives the percentile interval for and preserves coverage.
∎Condition (3) is a normalizing pivot: a scale where error is symmetric and parameter-independent. Fisher’s correlation transform is the classic example: percentile interval for works despite skew in , being equivalent to a symmetric interval in . Both intervals are first order: each tail’s coverage error is order , no better than normal. Second-order corrections (BCa, bootstrap-) are the subject of the next lesson.
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 falls below nominal, and the worst case (standard deviation of an exponential distribution with ) is very far from 95%.
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 no interval reaches 95% (not even for the mean of normal data, which stays at 0.92, whereas the exact 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 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 with . If the data are known (or assumed) to come from a family , there is a much more refined estimate of : , with 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 , sampling-distribution approximation error is smaller than in the nonparametric case.
- It works with small , where 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 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.
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 (the analogy 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 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 times, leaving out one observation each time.
The second equality for is algebra: . For the sample mean, exactly (the proof exercise in this lesson), so the jackknife generalizes the classical standard error. Unlike the bootstrap, dispersion of the jackknife replicates does not directly estimate that of the statistic: the replicates are very close (each shares observations with any other), and the factor together with the undivided sum of squares rescales that dispersion to the standard error.
Bias, from order to order
Proof
Each is the estimator with observations, so , and the same holds for its mean . Thus
because the term cancels () and remainders are . As and , the claim follows.
∎The canonical example: plug-in variance has , i.e. and , and the jackknife corrects it exactly to (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 with smooth , the difference produced by removing one observation is small and linear in that observation:
and so and : the variance estimate by linearization (the same sandwich variance as for the -estimators in lesson 8). In other words, the jackknife evaluates the influence function without differentiating. That is its strength (deterministic, 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 ordered observations , the median is . 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:
The pseudo-values take three distinct values (two if is even). That is very little information: jackknife variance depends only on the two spacings and around the median, and those spacings are random and do not concentrate as grows.
Proof
Sketch. With , where and are the first two values in the table (those occurring times each), the central value contributes and
so . The spacings of order statistics around the median, multiplied by , converge jointly to independent exponentials with mean 1 (a classical order-statistics result): . Substituting, and division by yields . The mean is , because .
∎The jackknife for the median errs by a random factor that does not vanish with : the ratio of jackknife to true standard error has, even for enormous , a 10% probability of falling below and another 10% of exceeding . (Its mean is 1, but the mean jackknife variance is 50% larger than the true variance.) With even , failure is worse: pseudo-values take only two values, , jackknife variance depends on one spacing, and the same argument gives limit , with mean 2 (also written , since ). 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.
A remedy exists: the delete- jackknife, which removes observations at a time and is consistent for the median if and (Shao and Wu, 1989). For suitable , 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.
| Bootstrap | Jackknife | |
|---|---|---|
| Statistic evaluations | (hundreds to thousands) | |
| Randomness | yes (Monte Carlo error) | none |
| Nonsmooth statistics (median, quantiles) | yes | fails |
| Intervals | yes (percentile, basic, …) | not directly |
| Bias | yes | yes, to order |
| Idea | random resamples | linearization, remove one observation |
The following cell implements everything from scratch: vectorized bootstrap (the 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.
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 exactly and corrects plug-in variance to , 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:
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 replicates is itself an estimate, and its error depends on the use.
For standard error. The sample standard deviation of independent replicates with kurtosis has approximate relative variance (delta method applied to sample variance, whose variance is ). Its coefficient of variation is
With it is 5%; with , 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 from replicates has standard deviation , where is the bootstrap density. For the 2.5% quantile of a normal distribution with standard deviation , and
With it is , and with , , 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, is a convenient choice for interval endpoints: Monte Carlo standard deviation falls to .
The figure’s final takeaway: replicates reduce Monte Carlo error, not statistical error. With 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 quantile is defined as ordered replicate number (the classical convention, not the default linear interpolation of np.quantile), choosing such that is an integer (with , or ) makes endpoints actual replicates without interpolation; fixing the seed makes the analysis reproducible (but no less uncertain: change it to see Monte Carlo error).
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 of measured on 600 examples does not have of : it has an estimate with error. And the metric (AUC, , 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 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 users with sessions each and we resample rows, bootstrap assumes independent observations and underestimates error. Resample users, with all their rows (cluster bootstrap). Standard-error inflation follows the design effect seen in cluster sampling, for variance, with 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.
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.
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:
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
Step 1 of 4. What are and ?
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)Summary
- Plug-in. A parameter is a functional , estimated by . The sampling distribution of is also a functional of , and estimating it by plug-in is bootstrap.
- Nonparametric bootstrap. Resample observations with replacement, recompute, and repeat times. It bets that error resembles . 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 (a resample contains 63.2% distinct observations), there are multisets, and the maximum repeats with probability (bootstrap fails for extremes).
- Standard error, bias and intervals. is the replicates’ standard deviation; bootstrap bias is rarely worth subtracting (rule ). Percentile and basic coincide for symmetric bootstrap; percentile is invariant under increasing transformations. Both are first-order and their coverage with small falls below nominal.
- Parametric bootstrap. Simulate from instead of : more efficient if the model is correct, false if not.
- Jackknife. , exact for the mean (), reduces bias from order to and linearizes the influence function. For the median it sees only three distinct values and its standard error converges to , not the truth: it is inconsistent.
- Replicates. : hundreds for standard error. Interval endpoints require thousands (standard deviation of a 2.5% quantile is ). Increasing 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.bootstrapoffers percentile, basic and BCa, withpairedmode.