Techniquecore
Parametric bootstrap
Also called model-based bootstrap.
Fit a parametric model, simulate new data sets from the fitted model, and recompute the statistic on each. Accurate when the model is right, and misleading when it is wrong.
The parametric bootstrap estimates the sampling distribution of a statistic by simulation from a fitted model. It fits a parametric family to the data, draws many data sets of the same size from , and recomputes the statistic on each. It differs from the nonparametric bootstrap only in the distribution it draws from: instead of the empirical distribution . When the model is right it is more accurate, and when the statistic is pivotal in the model, a test based on it has exact level.
In plain words
You have seven survival times and you believe they follow an exponential law, the law of waiting times with no memory. That law has only one number to choose, its average. So you set the average to the average of your data.
Now you have a full model, and a computer can produce as many fake data sets from it as you like. Make a few thousand fake sets of seven times, compute your statistic on each, and look at how much it varies. That spread is your error estimate.
The ordinary bootstrap reuses only the seven numbers you saw. The model-based version can produce values that you did not see, for example a time longer than the longest one. This helps when the model is good. If the model is bad, the fake data are wrong, and so is the answer.
When it applies
- The data come from a parametric family that you trust, for example exponential lifetimes, Poisson counts or a normal linear model, and has a consistent estimator , often the maximum likelihood estimate.
- The statistic has no closed-form distribution, or only a large-sample approximation that is poor at your .
- The model can be simulated. Each replicate costs one simulation and one evaluation of the statistic, and often one refit.
- For tests: the null hypothesis is a parametric model with unknown nuisance parameters. Simulate from the model fitted under the null.
The template
The holes are the model family , the fitting rule, the statistic and the number of replicates .
PARAMETRIC-BOOTSTRAP(x_1, ..., x_n, fit, F, s, b)- 1
θ̂ ← fit(x_1, ..., x_n) - 2
for j ← 1 to b do - 3
x* ← n independent draws from F_θ̂ - 4
θ*_j ← s(x*) ▷ s may refit the model on x* - 5
return θ*_1, ..., θ*_b
The replicates are then used as in the nonparametric bootstrap: their standard deviation is a standard error, their mean minus is a bias estimate, and their quantiles give intervals.
A test with exact level. Let be a test statistic whose law under the null model is the same for every . Such a is a pivotal quantity under . Then the simulated values have exactly the null law of , whatever is, and the observed value and the simulated values are exchangeable under . So the Monte Carlo p-value , with the number of simulated values at least as large as the observed one, satisfies by the rank argument of the permutation test. If is not pivotal, the level is only approximate, because .
Exponential model, exactly. If is exponential with mean , then , and is the mean of exponential draws with mean . That is a Gamma law with shape and scale , with mean and variance . So the ideal parametric bootstrap standard error of the mean is , which is also the standard error that the inverse Fisher information of the model gives at . The nonparametric bootstrap gives instead. The two agree only if , which the exponential model predicts.
Normal model, exactly. If , then for each simulated sample the studentized mean has exactly the law, because is pivotal. So a parametric bootstrap-t interval reproduces the t confidence interval, up to Monte Carlo error. The tests check this: with , and seed 3, the 0.975 quantile of is within Monte Carlo error of .
Worked example. The 7 treated mice of Efron and Tibshirani (Table 2.1) lived 94, 197, 16, 38, 99, 141 and 23 days, with mean and .
- Under the exponential model, the standard error of the mean is . With
random.Random(1)and , lines L1 to L5 gave . The nonparametric bootstrap gives . The difference comes from the model: an exponential law with mean 87 has standard deviation 87, and the data have only 67. - The same run for the median gave a standard error of , against for the ideal nonparametric bootstrap.
- A test of normality: the Kolmogorov-Smirnov distance between the data and the normal law with the sample mean and standard deviation is . With simulated normal samples of size 7 and
random.Random(1), the Monte Carlo p-value is . Seven values give no evidence against normality, which also shows how weak such a test is at this size.
Classic examples
- The Lilliefors test. The Kolmogorov-Smirnov test with the normal mean and variance estimated from the data. The statistic is invariant under with , so it is pivotal in the normal location-scale family, and the parametric bootstrap gives a test of exact level. Lilliefors (1967) made his table this way. With and seed 7 the simulated 5% critical value at was .
- Standard errors in a model fit by maximum likelihood, when the information-based standard error is unreliable, for example for a function of the parameters near a boundary.
- The number of components of a mixture. The likelihood ratio statistic for against components does not have its usual chi-squared limit, because the null lies on the boundary. Simulate it from the fitted -component model.
- Goodness of fit for generalized linear models, where the deviance is only roughly chi-squared for small counts.
- The bootstrap-t interval with a parametric resampling plan, which gives intervals with good coverage when the model is close to right; see the bootstrap-t interval.
Variations
- Semiparametric bootstrap. Keep a parametric part and resample the rest from the data. In regression, fit the mean model and resample the residuals: the mean is parametric and the error law is nonparametric.
- Simulation under the null. For a test, fit the model under , not under the alternative, and simulate from that fit. Simulating from the unrestricted fit gives a test with the wrong level.
- Double bootstrap. When is not pivotal, a second level of simulation from each estimates and corrects the level error, at a cost of fits.
- Smoothed bootstrap. Draw from a kernel density estimate. It sits between the parametric and the nonparametric bootstrap.
Pitfalls
- A wrong model. The method answers the question "how would the statistic vary if the model were true". For the mouse data, the exponential model gives a standard error for the mean 40% larger than the nonparametric one. Check the fit, or compare with the nonparametric bootstrap.
- Ignoring the estimation of parameters. Using the plain Kolmogorov-Smirnov p-value after estimating the mean and the variance is very conservative. In 2000 normal samples of size 20 with seed 6, the asymptotic Kolmogorov-Smirnov p-value was never below 0.05, though the nominal size is 0.05. Simulate the null law with the parameters re-estimated in each replicate, as line L4 does.
- Not refitting in each replicate. If the statistic involves , line L4 must recompute it on . Reusing from line L1 ignores its variability.
- Simulating under the alternative. For a test, the fitted model of line L1 must satisfy .
- Treating a non-pivotal test as exact. The exact-level argument needs the null law of not to depend on . Otherwise the level error is of the order of the error of , and a double bootstrap or a pivotal statistic is better.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parametric-bootstrap/. The authors are listed in prov/EDDGAQ.jsonl.
import math
import random
import statistics
from fractions import Fraction
from statistics import NormalDist
from typing import Callable, Sequence
def parametric_bootstrap(
x: Sequence[float],
fit: Callable[[Sequence[float]], object],
sample: Callable[[object, int, random.Random], list],
statistic: Callable[[Sequence[float]], float],
b: int,
rng: random.Random,
) -> list:
"""Replicates statistic(x*) for b samples x* of size n drawn from the fitted model."""
if b < 1:
raise ValueError("b must be at least 1")
n = len(x)
theta_hat = fit(x) # @line L1
reps = []
for _ in range(b): # @line L2
xs = sample(theta_hat, n, rng) # @line L3
reps.append(statistic(xs)) # @line L4
return reps # @line L5
# The exponential model with mean mu.
def fit_exponential(x: Sequence[float]) -> float:
return statistics.fmean(x)
def sample_exponential(mu: float, n: int, rng: random.Random) -> list:
return [rng.expovariate(1.0 / mu) for _ in range(n)]
# The normal model with mean mu and standard deviation sigma (maximum likelihood fit).
def fit_normal(x: Sequence[float]) -> tuple:
return statistics.fmean(x), statistics.pstdev(x)
def sample_normal(theta: tuple, n: int, rng: random.Random) -> list:
mu, sigma = theta
return [rng.gauss(mu, sigma) for _ in range(n)]
def ks_normal_statistic(x: Sequence[float]) -> float:
"""Kolmogorov-Smirnov distance between the sample and N(xbar, s^2), s with divisor n - 1.
The statistic is the same for x and a + c x with c > 0, so its null law does not
depend on the normal parameters.
"""
n = len(x)
if n < 2:
raise ValueError("need at least two values")
mu, s = statistics.fmean(x), statistics.stdev(x)
if s == 0:
raise ValueError("all values are equal")
phi = NormalDist().cdf
d = 0.0
for i, v in enumerate(sorted(x), start=1):
u = phi((v - mu) / s)
d = max(d, i / n - u, u - (i - 1) / n)
return d
def lilliefors_test(x: Sequence[float], b: int, rng: random.Random) -> tuple:
"""Monte Carlo test of normality with estimated mean and variance.
Returns (d, p) with p = (1 + c)/(1 + b), where c counts the simulated statistics
at least as large as d. Because the statistic is invariant under a + c x, the
simulation can use N(0, 1), and the test has exact level for every n.
"""
d = ks_normal_statistic(x)
n = len(x)
reps = parametric_bootstrap(x, lambda _: (0.0, 1.0), sample_normal, ks_normal_statistic, b, rng)
c = sum(1 for t in reps if t >= d)
return d, Fraction(1 + c, 1 + b)
def t_pivot(xs: Sequence[float], mu: float) -> float:
"""(xbar - mu) / (s / sqrt(n)), the studentized mean."""
return (statistics.fmean(xs) - mu) / (statistics.stdev(xs) / math.sqrt(len(xs)))
test_parametric_bootstrap.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parametric-bootstrap/. The authors are listed in prov/EDDGAQ.jsonl.
import math
import random
import statistics
from statistics import NormalDist
import pytest
from parametric_bootstrap import (
fit_exponential,
fit_normal,
ks_normal_statistic,
lilliefors_test,
parametric_bootstrap,
sample_exponential,
sample_normal,
t_pivot,
)
TREATMENT = [94, 197, 16, 38, 99, 141, 23]
T_9_0975 = 2.262157 # the 0.975 quantile of Student's t with 9 degrees of freedom
def test_exponential_standard_error():
"""In the exponential model, xbar* is Gamma(n, xbar/n), so its sd is exactly xbar/sqrt(n)."""
b = 20000
reps = parametric_bootstrap(TREATMENT, fit_exponential, sample_exponential, statistics.fmean, b, random.Random(1))
exact = statistics.fmean(TREATMENT) / math.sqrt(len(TREATMENT))
se = statistics.stdev(reps)
# sd of the sample sd of b Gamma(7) means is about se * sqrt((kurtosis - 1) / (4 b)), kurtosis 3 + 6/7.
assert abs(se - exact) < 4 * exact * math.sqrt((2 + 6 / 7) / (4 * b))
assert abs(statistics.fmean(reps) - statistics.fmean(TREATMENT)) < 4 * exact / math.sqrt(b)
def test_normal_t_pivot_is_student_t():
rng = random.Random(2)
x = [rng.gauss(5.0, 2.0) for _ in range(10)]
mu_hat = statistics.fmean(x)
b = 20000
reps = parametric_bootstrap(x, fit_normal, sample_normal, lambda xs: t_pivot(xs, mu_hat), b, random.Random(3))
reps.sort()
q = reps[math.ceil(0.975 * b) - 1]
# The density of t_9 at 2.262 is about 0.0409, so the quantile has sd about 0.027.
sd = math.sqrt(0.975 * 0.025 / b) / 0.0409
assert abs(q - T_9_0975) < 4 * sd
frac = sum(1 for t in reps if abs(t) <= T_9_0975) / b
assert abs(frac - 0.95) < 4 * math.sqrt(0.95 * 0.05 / b)
def brute_ks(x):
"""KS distance by evaluating F_n and the fitted normal just left and right of every point."""
n = len(x)
mu, s = statistics.fmean(x), statistics.stdev(x)
nd = NormalDist(mu, s)
best = 0.0
for v in x:
right = sum(1 for w in x if w <= v) / n
left = sum(1 for w in x if w < v) / n
best = max(best, abs(right - nd.cdf(v)), abs(left - nd.cdf(v)))
return best
def test_ks_statistic_against_definition():
rng = random.Random(4)
for n in (2, 3, 5, 10, 25):
x = [rng.gauss(0, 1) for _ in range(n)]
assert math.isclose(ks_normal_statistic(x), brute_ks(x), rel_tol=1e-12, abs_tol=1e-12)
x = [1.0, 2.0, 2.0, 3.0, 7.0]
assert math.isclose(ks_normal_statistic(x), brute_ks(x), rel_tol=1e-12)
def test_ks_statistic_is_location_scale_invariant():
rng = random.Random(5)
x = [rng.expovariate(1.0) for _ in range(15)]
y = [3.0 + 2.5 * v for v in x]
assert math.isclose(ks_normal_statistic(x), ks_normal_statistic(y), rel_tol=1e-9)
def test_lilliefors_size_and_power():
rng = random.Random(6)
r, b, n, alpha = 300, 99, 20, 0.05
size = power = 0
for _ in range(r):
_, p = lilliefors_test([rng.gauss(10, 3) for _ in range(n)], b, rng)
size += p <= alpha
_, p = lilliefors_test([rng.expovariate(1.0) for _ in range(n)], b, rng)
power += p <= alpha
tol = 4 * math.sqrt(alpha * (1 - alpha) / r)
assert size / r <= alpha + tol
assert power / r > 0.5
def test_errors():
with pytest.raises(ValueError):
ks_normal_statistic([1.0])
with pytest.raises(ValueError):
ks_normal_statistic([2.0, 2.0, 2.0])
with pytest.raises(ValueError):
parametric_bootstrap([1.0, 2.0], fit_normal, sample_normal, statistics.fmean, 0, random.Random(1))
Exercises
- Show that in the exponential model has the Gamma law with shape and scale , and find the exact and quantiles of for in terms of chi-squared quantiles.
- Show that the Kolmogorov-Smirnov distance between and does not change under with . Deduce that the parametric bootstrap test of normality has exact level.
- In the normal model, show that the parametric bootstrap distribution of is , and conclude that the parametric bootstrap-t interval is the t interval when .
- In the Poisson model with mean , find the ideal parametric bootstrap variance of and compare it with the nonparametric one.
- Give a model and a statistic for which the parametric bootstrap test has a level far from even for large . (Hint: a statistic whose null law changes quickly with a nuisance parameter that is poorly estimated.)
References
- Bradley Efron and Robert J. Tibshirani, An Introduction to the Bootstrap, Chapman and Hall, 1993, Chapter 6 (the bootstrap estimate of standard error, with the parametric bootstrap as a variant)
- A. C. Davison and D. V. Hinkley, Bootstrap Methods and their Application, Cambridge University Press, 1997, Chapter 2 (parametric simulation) and Chapter 4 (tests, including parametric bootstrap tests and Monte Carlo tests)
- Bradley Efron, Bootstrap methods, another look at the jackknife, The Annals of Statistics 7(1), 1979, pp. 1 to 26 (the bootstrap from an estimated distribution, which may be parametric)
- Hubert W. Lilliefors, On the Kolmogorov-Smirnov test for normality with mean and variance unknown, Journal of the American Statistical Association 62(318), 1967, pp. 399 to 402 (critical values by simulation when the parameters are estimated)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag EDDGAQ Edit this page History Report an error Markdown