Algorithm Search⌘K

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 {Fθ}\{F_\theta\} to the data, draws many data sets of the same size from Fθ^F_{\hat\theta}, and recomputes the statistic on each. It differs from the nonparametric bootstrap only in the distribution it draws from: Fθ^F_{\hat\theta} instead of the empirical distribution F^n\hat F_n. 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 FθF_\theta that you trust, for example exponential lifetimes, Poisson counts or a normal linear model, and θ\theta has a consistent estimator θ^\hat\theta, often the maximum likelihood estimate.
  • The statistic has no closed-form distribution, or only a large-sample approximation that is poor at your nn.
  • 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 FθF_\theta, the fitting rule, the statistic ss and the number of replicates bb.

  1. PARAMETRIC-BOOTSTRAP(x_1, ..., x_n, fit, F, s, b)
  2. 1θ̂ ← fit(x_1, ..., x_n)
  3. 2for j ← 1 to b do
  4. 3x* ← n independent draws from F_θ̂
  5. 4θ*_j ← s(x*) ▷ s may refit the model on x*
  6. 5return θ*_1, ..., θ*_b

The replicates are then used as in the nonparametric bootstrap: their standard deviation is a standard error, their mean minus s(x)s(x) is a bias estimate, and their quantiles give intervals.

A test with exact level. Let TT be a test statistic whose law under the null model FθF_\theta is the same for every θ\theta. Such a TT is a pivotal quantity under H0H_0. Then the simulated values T(x1∗),…,T(xb∗)T(x^*_1), \ldots, T(x^*_b) have exactly the null law of T(X)T(X), whatever θ^\hat\theta is, and the observed value and the bb simulated values are exchangeable under H0H_0. So the Monte Carlo p-value (1+c)/(1+b)(1 + c)/(1 + b), with cc the number of simulated values at least as large as the observed one, satisfies P(p≤α)≤αP(p \le \alpha) \le \alpha by the rank argument of the permutation test. If TT is not pivotal, the level is only approximate, because θ^≠θ\hat\theta \neq \theta.

Exponential model, exactly. If FμF_\mu is exponential with mean μ\mu, then μ^=xˉ\hat\mu = \bar x, and Xˉ∗\bar X^* is the mean of nn exponential draws with mean xˉ\bar x. That is a Gamma law with shape nn and scale xˉ/n\bar x/n, with mean xˉ\bar x and variance xˉ2/n\bar x^2/n. So the ideal parametric bootstrap standard error of the mean is xˉ/n\bar x/\sqrt{n}, which is also the standard error that the inverse Fisher information of the model gives at μ^\hat\mu. The nonparametric bootstrap gives (n−1)/n S/n\sqrt{(n - 1)/n} \, S/\sqrt{n} instead. The two agree only if S≈xˉS \approx \bar x, which the exponential model predicts.

Normal model, exactly. If Fθ=N(μ,σ2)F_\theta = N(\mu, \sigma^2), then for each simulated sample the studentized mean T∗=(Xˉ∗−μ^)/(S∗/n)T^* = (\bar X^* - \hat\mu)/(S^*/\sqrt{n}) has exactly the tn−1t_{n - 1} law, because T∗T^* is pivotal. So a parametric bootstrap-t interval reproduces the t confidence interval, up to Monte Carlo error. The tests check this: with n=10n = 10, b=20000b = 20000 and seed 3, the 0.975 quantile of T∗T^* is within Monte Carlo error of t9,0.975=2.262157t_{9, 0.975} = 2.262157.

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 86.8686.86 and S=66.77S = 66.77.

  • Under the exponential model, the standard error of the mean is 86.86/7=32.8386.86/\sqrt{7} = 32.83. With random.Random(1) and b=2000b = 2000, lines L1 to L5 gave 32.8232.82. The nonparametric bootstrap gives 23.3623.36. 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 33.5933.59, against 37.8337.83 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 D=0.196D = 0.196. With b=999b = 999 simulated normal samples of size 7 and random.Random(1), the Monte Carlo p-value is 279/500=0.558279/500 = 0.558. 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 x↦a+cxx \mapsto a + c x with c>0c > 0, 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 b=20000b = 20000 and seed 7 the simulated 5% critical value at n=20n = 20 was 0.1920.192.
  • 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 kk against k+1k + 1 components does not have its usual chi-squared limit, because the null lies on the boundary. Simulate it from the fitted kk-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 H0H_0, not under the alternative, and simulate from that fit. Simulating from the unrestricted fit gives a test with the wrong level.
  • Double bootstrap. When TT is not pivotal, a second level of simulation from each Fθ^∗F_{\hat\theta^*} estimates and corrects the level error, at a cost of b1b2b_1 b_2 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 θ^\hat\theta, line L4 must recompute it on x∗x^*. Reusing θ^\hat\theta from line L1 ignores its variability.
  • Simulating under the alternative. For a test, the fitted model of line L1 must satisfy H0H_0.
  • Treating a non-pivotal test as exact. The exact-level argument needs the null law of TT not to depend on θ\theta. Otherwise the level error is of the order of the error of θ^\hat\theta, 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.

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

  1. Show that in the exponential model Xˉ∗\bar X^* has the Gamma law with shape nn and scale xˉ/n\bar x/n, and find the exact 0.0250.025 and 0.9750.975 quantiles of Xˉ∗/xˉ\bar X^*/\bar x for n=7n = 7 in terms of chi-squared quantiles.
  2. Show that the Kolmogorov-Smirnov distance between xx and N(xˉ,S2)N(\bar x, S^2) does not change under xi↦a+cxix_i \mapsto a + c x_i with c>0c > 0. Deduce that the parametric bootstrap test of normality has exact level.
  3. In the normal model, show that the parametric bootstrap distribution of (Xˉ∗−xˉ)/(S∗/n)(\bar X^* - \bar x)/(S^*/\sqrt{n}) is tn−1t_{n-1}, and conclude that the parametric bootstrap-t interval is the t interval when b→∞b \to \infty.
  4. In the Poisson model with mean λ\lambda, find the ideal parametric bootstrap variance of Xˉ∗\bar X^* and compare it with the nonparametric one.
  5. Give a model and a statistic for which the parametric bootstrap test has a level far from α\alpha even for large nn. (Hint: a statistic whose null law changes quickly with a nuisance parameter that is poorly estimated.)

References

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises