Algorithm Search⌘K

Techniquecore

Posterior predictive check

Also called posterior predictive p-value.

Checks a Bayesian model by comparing a statistic of the data with its distribution in replicated data drawn from the posterior predictive.

A posterior predictive check asks whether data simulated from a fitted Bayesian model look like the observed data. Choose a test quantity T(x,θ)T(x, \theta), a statistic of the data that may also depend on the parameters. Draw θ\theta from the posterior, draw a replicated data set xrepx^{\mathrm{rep}} of the same size from the model at θ\theta, and compare T(xrep,θ)T(x^{\mathrm{rep}}, \theta) with T(x,θ)T(x, \theta). Repeating this gives the posterior predictive distribution of the test quantity, and the posterior predictive p-value

pB=P(T(xrep,θ)≥T(x,θ)∣x),p_B = P\big(T(x^{\mathrm{rep}}, \theta) \ge T(x, \theta) \mid x\big),

where the probability is over θ∼π(θ∣x)\theta \sim \pi(\theta \mid x) and xrep∼f(⋅∣θ)x^{\mathrm{rep}} \sim f(\cdot \mid \theta). A value near 00 or 11 shows that the model cannot reproduce that feature of the data. The check uses only posterior draws and a simulator, so it applies to any model that can be fitted. Its p-value is not uniform when the model is true: it piles up near 1/21/2, so it is conservative.

In plain words

After fitting a model, use it to make fake data sets, as many as you like, each one the size of the real data. If the model describes the data well, the real data should look like one more fake data set. Pick a feature to compare, such as the largest value, the number of zeros, or how spread out the values are, and see where the real value falls among the fake ones. If it lies far out, beyond almost all fake values, the model misses that feature, and the feature tells you how to fix it. Because the fake data come from a model already fitted to the real data, they tend to resemble the real data more than they should, so the check is gentle: it rarely raises a false alarm, but it can miss real problems.

When it applies

  • A fitted Bayesian model with posterior draws θ1,…,θS\theta_1, \ldots, \theta_S, from Markov chain Monte Carlo or any other sampler, and a way to simulate data from the model at a given θ\theta.
  • A question about fit. The check looks for features of the data that the model does not capture, such as overdispersion, outliers, skewness, trends in residuals or dependence. It does not compare two models; for that, use Bayes factors or predictive scores such as WAIC.
  • A test quantity chosen for the question. The check has power only against misfit that changes TT. A statistic that the model fits by construction, such as a sufficient statistic of its parameters, gives pBp_B near 1/21/2 whatever the data.

The template

The holes are the test quantity T and the draws θ_s (the reference distribution).

  1. PPC(x, θ₁..θ_S, SIMULATE, T)
  2. 1count ← 0
  3. 2for s ← 1 to S ▷ hole: draws from the posterior
  4. 3x_rep ← SIMULATE(θ_s) ▷ same size and design as x
  5. 4if T(x_rep, θ_s) ≥ T(x, θ_s) then count ← count + 1 ▷ hole T
  6. 5return p_B ≈ count / S, and the pairs (T(x_rep, θ_s), T(x, θ_s)) for a plot

Common choices:

  • T a statistic of the data: the maximum, the minimum, the number of zeros, the sample variance, an autocorrelation, or a quantile. Choose one the model does not fit directly.
  • T a discrepancy: a function of both, such as the chi-squared discrepancy ∑i(xi−E[xi∣θ])2/Var(xi∣θ)\sum_i (x_i - \mathbb{E}[x_i \mid \theta])^2/\mathrm{Var}(x_i \mid \theta) of Gelman, Meng and Stern (1996). In L4 it is evaluated at the same θs\theta_s for the real and the replicated data.
  • θ_s from the posterior: the posterior predictive check. From the prior: a prior predictive check, which tests the prior as well. From the posterior without observation ii: a cross-validated check of observation ii.
  • Graphical: plot the observed data among a few replicated data sets, or the observed TT on the histogram of replicated TT. A plot often shows the kind of misfit better than the number pBp_B.

Facts about pBp_B when the model is true. Suppose the data are drawn from the prior predictive law, that is, θ\theta from the prior and xx from the model. Write pθ(x)=P(T(X′,θ)≥T(x,θ)∣θ)p_\theta(x) = P(T(X', \theta) \ge T(x, \theta) \mid \theta) for the classical p-value at a known θ\theta, so pB(x)=E[pθ(x)∣x]p_B(x) = \mathbb{E}[p_\theta(x) \mid x].

Mean. E[pB]=P(T(X′,θ)≥T(X,θ))\mathbb{E}[p_B] = P(T(X', \theta) \ge T(X, \theta)) with X,X′X, X' independent given θ\theta. By symmetry this is 12(1+P(T(X′,θ)=T(X,θ)))\frac12(1 + P(T(X', \theta) = T(X, \theta))), which is 12\frac12 for a continuous TT.

Meng's bound. P(pB≤α)≤2αP(p_B \le \alpha) \le 2\alpha. Proof. U=pθ(X)U = p_\theta(X) is a classical p-value at the true θ\theta, so P(U≤u)≤uP(U \le u) \le u for every uu, and its quantile function satisfies QU(t)≥tQ_U(t) \ge t. Let A={pB≤α}A = \{p_B \le \alpha\}, an event determined by xx. Then E[U1A]=E[pB1A]≤αP(A)\mathbb{E}[U\mathbf{1}_A] = \mathbb{E}[p_B\mathbf{1}_A] \le \alpha P(A). Among all events of probability P(A)P(A), E[U1A]\mathbb{E}[U\mathbf{1}_A] is smallest when AA holds the smallest values of UU, so E[U1A]≥∫0P(A)QU(t) dt≥P(A)2/2\mathbb{E}[U\mathbf{1}_A] \ge \int_0^{P(A)} Q_U(t)\, dt \ge P(A)^2/2. Hence P(A)2/2≤αP(A)P(A)^2/2 \le \alpha P(A), and P(A)≤2αP(A) \le 2\alpha. ■\blacksquare

So a check at level α\alpha never rejects a true model more often than 2α2\alpha. In the other direction, pBp_B is usually far more concentrated near 1/21/2 than a uniform value, and a small pBp_B is stronger evidence of misfit than the same classical p-value.

Classic examples

The normal mean: the pile-up near 1/2. x1,…,xn∼N(θ,σ2)x_1, \ldots, x_n \sim N(\theta, \sigma^2) with σ\sigma known, prior θ∼N(0,τ2)\theta \sim N(0, \tau^2), and T=xˉT = \bar x. With s2=σ2/ns^2 = \sigma^2/n, the posterior is N(m,v)N(m, v) with v=τ2s2/(τ2+s2)v = \tau^2 s^2/(\tau^2 + s^2) and m=vxˉ/s2m = v\bar x/s^2, and xˉrep∣x∼N(m,v+s2)\bar x^{\mathrm{rep}} \mid x \sim N(m, v + s^2). So

pB=Φ(m−xˉv+s2)=Φ(−cZ),Z=xˉτ2+s2,c=s22τ2+s2.p_B = \Phi\Big(\frac{m - \bar x}{\sqrt{v + s^2}}\Big) = \Phi(-cZ), \qquad Z = \frac{\bar x}{\sqrt{\tau^2 + s^2}}, \qquad c = \sqrt{\frac{s^2}{2\tau^2 + s^2}}.

When the model is true, ZZ is standard normal, so P(pB≤α)=Φ(zα/c)P(p_B \le \alpha) = \Phi(z_\alpha/c), with zα=Φ−1(α)z_\alpha = \Phi^{-1}(\alpha), and Var(pB)=arcsin⁡ ⁣(c2/(1+c2))/(2π)\mathrm{Var}(p_B) = \arcsin\!\big(c^2/(1 + c^2)\big)/(2\pi). Since c<1c < 1, pBp_B is less spread than a uniform value, whose variance 1/121/12 is the case c=1c = 1. With σ=τ=1\sigma = \tau = 1:

nn cc sd of pBp_B P(pB≤0.05)P(p_B \le 0.05) P(0.25<pB<0.75)P(0.25 < p_B < 0.75)
1 0.577 0.200 0.0022 0.757
10 0.218 0.085 2×10−142 \times 10^{-14} above 0.999
100 0.071 0.028 10−12010^{-120} 1
uniform 1 0.289 0.05 0.5

With n=1n = 1, 20002000 data sets from random.Random(5) and S=500S = 500 draws each, the template gives sd 0.2010.201 and a share 0.7520.752 in (0.25,0.75)(0.25, 0.75). The sample mean is sufficient for θ\theta, so the posterior adapts to it and the check has almost no power for it. This is the conservative behaviour that Robins, van der Vaart and Ventura (2000) prove in general.

An ancillary statistic gives an exact p-value. In the same model, take T=S2T = S^2, the sample variance. Its law, σ2n−1χn−12\frac{\sigma^2}{n-1}\chi^2_{n-1}, does not depend on θ\theta, so the posterior predictive law of TT is its sampling law, pBp_B is the classical chi-squared p-value, and pBp_B is exactly uniform when the model is true. A test quantity whose law depends little on the parameters gives a check with nearly correct error rates.

Overdispersed counts. Model: x1,…,x20∼x_1, \ldots, x_{20} \sim Poisson(λ\lambda) with λ∼\lambda \sim Gamma(1, rate 0.25), so λ∣x∼\lambda \mid x \sim Gamma(1+∑xi1 + \sum x_i, rate 20.2520.25). Test quantity: the dispersion index T=s2/xˉT = s^2/\bar x, near 11 for Poisson data. With S=4000S = 4000:

data values T(x)T(x) pBp_B for T=s2/xˉT = s^2/\bar x pBp_B for T=xˉT = \bar x pBp_B for T=max⁡T = \max
A: Poisson(4) 1, 1, 2, 3, 3, 3, 4 (ten times), 5, 5, 6, 7 0.54 0.949 0.493 0.814
B: mixed Poisson, mean 4, variance 12 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4 (six times), 5, 5, 6, 29 8.45 0.000 0.495 0.000

The dispersion and the maximum both reject the Poisson model for data set B, whose value 2929 is impossible under a Poisson law with mean near 44. The mean, a sufficient statistic, gives pB≈1/2p_B \approx 1/2 for both data sets. The number of zeros, 11 in B, gives pB=0.27p_B = 0.27 and misses the misfit too. A hierarchical model with a gamma law for each count's rate, which gives negative binomial counts, is the usual fix. When the Poisson model is true (400400 data sets drawn from the prior predictive), the dispersion index gives pBp_B with sd 0.2850.285, close to uniform, while the mean gives sd 0.0650.065.

The chi-squared discrepancy. For a model with means μi(θ)\mu_i(\theta) and variances σi2(θ)\sigma_i^2(\theta), the discrepancy ∑i(xi−μi(θ))2/σi2(θ)\sum_i (x_i - \mu_i(\theta))^2/\sigma_i^2(\theta) is the Bayesian form of the chi-squared goodness-of-fit test. It is evaluated at each posterior draw, for the observed and the replicated data, with no estimate plugged in and no degrees of freedom to count.

Regression. For a linear regression, replicate the responses at the observed covariates and compare residual plots, or use TT = the correlation of the residuals with a covariate left out of the model, or the largest absolute residual.

Variations

  • Prior predictive check. Draw θ\theta from the prior in L2. Its p-value is uniform under the model, but it rejects good models whose prior is vague.
  • Calibrated p-values. Simulate many data sets from the prior predictive law, compute pBp_B for each, and use their distribution to turn pBp_B into a uniform p-value. This is costly, since every replicate needs a new posterior; it is the same loop as simulation-based calibration, which checks the computation instead of the model.
  • Partial posterior predictive and conditional predictive p-values (Bayarri and Berger 2000). Remove from the posterior the information that TT itself carries, so that the data are not used twice; the result is close to uniform under the model.
  • Cross-validated checks. Compare each xix_i with its predictive law given the other data, for example by the probability integral transform of xix_i, which is uniform under a good model. Pareto smoothed importance sampling computes all these leave-one-out laws from one posterior sample. See also cross-validation.
  • Hierarchical replication. In a hierarchical model, choose which levels to replicate: new data for the same groups, or new groups as well. The choice decides which part of the model the check tests.
  • Likelihood-free models. The template needs only a simulator, so it also checks models fitted by approximate Bayesian computation.

Pitfalls

  • Reading pBp_B as a uniform p-value. Under a true model, pBp_B piles up near 1/21/2; with n=10n = 10 in the normal example, P(pB≤0.05)P(p_B \le 0.05) is 2×10−142 \times 10^{-14}, not 0.050.05. A check in L4 that gives pB=0.2p_B = 0.2 is not reassuring evidence of fit, and pB=0.01p_B = 0.01 is strong evidence of misfit.
  • A test quantity the model fits by construction. Taking T in L4 to be a sufficient statistic, such as the sample mean of a Poisson model, gives pB≈1/2p_B \approx 1/2 for any data; in the count example it was 0.490.49 for both data sets. Choose T to target a feature the model does not fit directly.
  • Replicating with a different design. If L3 simulates data of another size, other covariates or another censoring pattern than the observed data, the comparison in L4 is meaningless. Replicate exactly the design of xx.
  • Different θ\theta for the two sides of a discrepancy. When T depends on θ\theta, L4 must use the same θs\theta_s for T(xrep,θs)T(x^{\mathrm{rep}}, \theta_s) and T(x,θs)T(x, \theta_s). Using a point estimate for the observed side and draws for the replicated side changes the reference law.
  • Too few draws for a small p-value. With SS draws in L2, the smallest positive value is 1/S1/S; pB=0p_B = 0 in the table means fewer than 11 in 40004000. Report it as pB<1/Sp_B < 1/S, and increase SS if the size matters.
  • Testing many quantities without a plan. Trying many test quantities and reporting the smallest pBp_B finds misfit that is not there. Choose quantities that answer questions relevant to the use of the model.

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.

posterior_predictive_check.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/posterior-predictive-check/. The authors are listed in prov/2TJBEH.jsonl.
"""Posterior predictive checks (Rubin 1984; Gelman, Meng and Stern 1996).

ppc draws one replicated data set for each posterior draw and returns the posterior
predictive p-value P(T(x_rep, theta) >= T(x, theta) | x), with the pairs of values for a
plot. The closed forms below give the exact p-value and its law under the model for the
normal mean with a normal prior, where the p-values pile up near 1/2.
"""

import math
import random
from statistics import NormalDist
from typing import Callable, Sequence

_N = NormalDist()


def ppc(
    x,
    draws: Sequence,
    simulate: Callable,
    T: Callable,
    rng: random.Random,
) -> tuple[float, list[tuple[float, float]]]:
    """The template: returns (p-value, [(T(x_rep, theta_s), T(x, theta_s)) for each s])."""
    count = 0  # @line L1
    pairs = []
    for theta in draws:  # @line L2
        x_rep = simulate(theta, rng)  # @line L3
        t_rep, t_obs = T(x_rep, theta), T(x, theta)
        if t_rep >= t_obs:  # @line L4
            count += 1
        pairs.append((t_rep, t_obs))
    return count / len(draws), pairs  # @line L5


# Normal mean: x_1..x_n ~ N(theta, sigma^2), sigma known, theta ~ N(0, tau^2).

def normal_posterior(xbar: float, n: int, sigma: float, tau: float) -> tuple[float, float]:
    v = 1.0 / (n / sigma**2 + 1.0 / tau**2)
    return v * n * xbar / sigma**2, v


def ppp_mean(xbar: float, n: int, sigma: float, tau: float) -> float:
    """Exact posterior predictive p-value of T = the sample mean: P(xbar_rep >= xbar | x)."""
    m, v = normal_posterior(xbar, n, sigma, tau)
    return 1.0 - _N.cdf((xbar - m) / math.sqrt(v + sigma**2 / n))


def pileup_factor(n: int, sigma: float, tau: float) -> float:
    """c with p = Phi(-c Z), Z standard normal, when the data come from the model."""
    s2 = sigma**2 / n
    return math.sqrt(s2 / (2 * tau**2 + s2))


def ppp_mean_tail(alpha: float, c: float) -> float:
    """P(p <= alpha) for p = Phi(-c Z): Phi(z_alpha / c)."""
    return _N.cdf(_N.inv_cdf(alpha) / c)


def ppp_mean_variance(c: float) -> float:
    """Var(p) for p = Phi(-c Z): arcsin(c^2 / (1 + c^2)) / (2 pi); 1/12 when c = 1."""
    return math.asin(c * c / (1 + c * c)) / (2 * math.pi)


def chi2_sf_even(x: float, k: int) -> float:
    """P(chi^2_k >= x) for even k."""
    h = x / 2
    term, total = 1.0, 1.0
    for j in range(1, k // 2):
        term *= h / j
        total += term
    return math.exp(-h) * total


def ppp_variance_known_sigma(xs: Sequence[float], sigma: float) -> float:
    """p-value of T = the sample variance when sigma is known. T is ancillary, so its
    posterior predictive law is its sampling law, (sigma^2 / (n - 1)) chi^2_{n-1}.
    Requires n - 1 even."""
    n = len(xs)
    if (n - 1) % 2:
        raise ValueError("n - 1 must be even for the closed form")
    m = sum(xs) / n
    s2 = sum((v - m) ** 2 for v in xs) / (n - 1)
    return chi2_sf_even((n - 1) * s2 / sigma**2, n - 1)


# Counts: x_i ~ Poisson(lambda), lambda ~ Gamma(a, rate b); posterior Gamma(a + sum x, b + n).

def poisson(lam: float, rng: random.Random) -> int:
    if lam > 30:
        # sum of independent Poisson parts keeps the product method stable
        k = int(lam // 30)
        return sum(poisson(lam / (k + 1), rng) for _ in range(k + 1))
    k, prod, lim = 0, rng.random(), math.exp(-lam)
    while prod > lim:
        k += 1
        prod *= rng.random()
    return k


def dispersion(xs: Sequence[int], _theta=None) -> float:
    """Sample variance over sample mean; about 1 for Poisson data."""
    n = len(xs)
    m = sum(xs) / n
    if m == 0:
        return 0.0
    return sum((v - m) ** 2 for v in xs) / (n - 1) / m


def poisson_gamma_check(xs: Sequence[int], a: float, b: float, n_draws: int, rng: random.Random, T=dispersion) -> float:
    n, s = len(xs), sum(xs)
    draws = [rng.gammavariate(a + s, 1.0 / (b + n)) for _ in range(n_draws)]
    p, _ = ppc(xs, draws, lambda lam, r: [poisson(lam, r) for _ in range(n)], T, rng)
    return p
test_posterior_predictive_check.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/posterior-predictive-check/. The authors are listed in prov/2TJBEH.jsonl.
"""Tests for posterior predictive checks: the template against closed forms, the pile-up
of p-values near 1/2 when the model is true, Meng's bound P(p <= alpha) <= 2 alpha and
the mean (1 + P(tie)) / 2 in exact arithmetic, the uniform p-value of an ancillary
statistic, and the detection of overdispersed counts."""

import math
import random
import statistics
import unittest
from fractions import Fraction as F

from posterior_predictive_check import (
    dispersion,
    normal_posterior,
    pileup_factor,
    poisson,
    poisson_gamma_check,
    ppc,
    ppp_mean,
    ppp_mean_tail,
    ppp_mean_variance,
    ppp_variance_known_sigma,
)


def mean_stat(y, _theta=None):
    return sum(y) / len(y)


class TestNormalMean(unittest.TestCase):
    def test_template_matches_the_closed_form(self):
        rng = random.Random(1)
        n, sigma, tau = 10, 1.0, 1.0
        xs = [rng.gauss(0.8, sigma) for _ in range(n)]
        m, v = normal_posterior(mean_stat(xs), n, sigma, tau)
        draws = [rng.gauss(m, math.sqrt(v)) for _ in range(20000)]
        p, pairs = ppc(xs, draws, lambda t, r: [r.gauss(t, sigma) for _ in range(n)], mean_stat, rng)
        exact = ppp_mean(mean_stat(xs), n, sigma, tau)
        self.assertEqual(len(pairs), 20000)
        self.assertLess(abs(p - exact), 4 * math.sqrt(exact * (1 - exact) / 20000))

    def test_p_values_pile_up_near_one_half(self):
        n, sigma, tau = 1, 1.0, 1.0
        c = pileup_factor(n, sigma, tau)
        self.assertAlmostEqual(c, 1 / math.sqrt(3), places=12)
        rng = random.Random(2)
        ps = []
        for _ in range(4000):
            th = rng.gauss(0, tau)
            xbar = rng.gauss(th, sigma / math.sqrt(n))
            ps.append(ppp_mean(xbar, n, sigma, tau))
        sd = statistics.pstdev(ps)
        self.assertLess(abs(sd - math.sqrt(ppp_mean_variance(c))), 0.01)
        self.assertLess(sd, 0.25)  # a uniform p-value has sd 0.2887
        mid = sum(0.25 < p < 0.75 for p in ps) / len(ps)
        z = statistics.NormalDist().inv_cdf(0.75) / c
        exact_mid = 2 * statistics.NormalDist().cdf(z) - 1  # 0.757, against 0.5 for uniform
        self.assertLess(abs(mid - exact_mid), 4 * math.sqrt(exact_mid * (1 - exact_mid) / len(ps)))
        self.assertLess(sum(p <= 0.05 for p in ps) / len(ps), 0.01)
        self.assertAlmostEqual(ppp_mean_tail(0.05, c), 0.00219, places=5)

    def test_variance_formula(self):
        nd = statistics.NormalDist()
        self.assertAlmostEqual(ppp_mean_variance(1.0), 1 / 12, places=14)
        for c in (0.1, 0.3, 0.7, 1.0, 2.0):
            # Simpson's rule for E[Phi(cZ)^2] - 1/4 over z in [-10, 10]
            h, k = 0.01, 2000
            vals = [nd.cdf(c * (-10 + h * i)) ** 2 * nd.pdf(-10 + h * i) for i in range(k + 1)]
            integral = h / 3 * (vals[0] + vals[-1] + 4 * sum(vals[1:-1:2]) + 2 * sum(vals[2:-1:2]))
            self.assertAlmostEqual(integral - 0.25, ppp_mean_variance(c), places=8)


def discrete_ppp_law(prior, like):
    """Exact posterior predictive p-values of T(y) = y for every y, and the prior predictive m(y)."""
    k, ys = len(prior), range(len(like[0]))
    m = [sum(prior[t] * like[t][y] for t in range(k)) for y in ys]
    tail = [[sum(like[t][z] for z in ys if z >= y) for y in ys] for t in range(k)]
    p = [sum(prior[t] * like[t][y] * tail[t][y] for t in range(k)) / m[y] for y in ys]
    return p, m


class TestExactDiscrete(unittest.TestCase):
    def test_meng_bound_and_the_mean(self):
        rng = random.Random(3)
        for _ in range(300):
            k = rng.randint(1, 4)
            n = rng.randint(1, 8)
            raw = [rng.randint(1, 9) for _ in range(k)]
            prior = [F(v, sum(raw)) for v in raw]
            ps = [F(rng.randint(1, 9), 10) for _ in range(k)]
            like = [[math.comb(n, y) * q**y * (1 - q) ** (n - y) for y in range(n + 1)] for q in ps]
            p, m = discrete_ppp_law(prior, like)
            # Meng (1994): P(p <= alpha) <= 2 alpha; it suffices to check at the attained values
            for a in p:
                self.assertLessEqual(sum(mm for pp, mm in zip(p, m) if pp <= a), 2 * a)
            # E[p] = (1 + P(Y = Y')) / 2 for Y, Y' independent given theta
            tie = sum(prior[t] * sum(v * v for v in like[t]) for t in range(k))
            self.assertEqual(sum(pp * mm for pp, mm in zip(p, m)), (1 + tie) / 2)


class TestAncillaryStatistic(unittest.TestCase):
    def test_sample_variance_with_known_sigma_is_uniform(self):
        rng = random.Random(4)
        n, sigma, tau = 5, 1.0, 2.0
        ps = []
        for _ in range(3000):
            th = rng.gauss(0, tau)
            xs = [rng.gauss(th, sigma) for _ in range(n)]
            ps.append(ppp_variance_known_sigma(xs, sigma))
        ps.sort()
        ks = max(max((i + 1) / len(ps) - v, v - i / len(ps)) for i, v in enumerate(ps))
        self.assertLess(ks, 1.63 / math.sqrt(len(ps)))
        # the template gives the same value on one data set
        xs = [rng.gauss(0.5, sigma) for _ in range(n)]
        m, v = normal_posterior(sum(xs) / n, n, sigma, tau)
        draws = [rng.gauss(m, math.sqrt(v)) for _ in range(20000)]

        def s2(y, _t=None):
            mu = sum(y) / len(y)
            return sum((a - mu) ** 2 for a in y) / (len(y) - 1)

        p, _ = ppc(xs, draws, lambda t, r: [r.gauss(t, sigma) for _ in range(n)], s2, rng)
        exact = ppp_variance_known_sigma(xs, sigma)
        self.assertLess(abs(p - exact), 4 * math.sqrt(exact * (1 - exact) / 20000) + 1e-9)


class TestCounts(unittest.TestCase):
    def test_overdispersion_is_detected(self):
        rng = random.Random(8)
        xa = [poisson(4.0, rng) for _ in range(20)]
        xb = [poisson(rng.gammavariate(2.0, 2.0), rng) for _ in range(20)]
        pa = poisson_gamma_check(xa, 1.0, 0.25, 4000, random.Random(9))
        pb = poisson_gamma_check(xb, 1.0, 0.25, 4000, random.Random(9))
        self.assertGreater(pa, 0.05)
        self.assertLess(pb, 0.01)
        self.assertGreater(dispersion(xb), 5)
        # the sample mean is sufficient for lambda, so its p-value is near 1/2 for both
        for xs in (xa, xb):
            pm = poisson_gamma_check(xs, 1.0, 0.25, 4000, random.Random(9), mean_stat)
            self.assertLess(abs(pm - 0.5), 0.05)


if __name__ == "__main__":
    unittest.main()

Exercises

  1. In the normal mean example, derive c=s2/(2τ2+s2)c = \sqrt{s^2/(2\tau^2 + s^2)} and P(pB≤α)=Φ(zα/c)P(p_B \le \alpha) = \Phi(z_\alpha/c). What happens as τ→0\tau \to 0 and as τ→∞\tau \to \infty?
  2. Show that E[Φ(cZ)2]=14+12πarcsin⁡c21+c2\mathbb{E}[\Phi(cZ)^2] = \frac14 + \frac{1}{2\pi}\arcsin\frac{c^2}{1 + c^2} for standard normal ZZ, by writing Φ(cZ)2\Phi(cZ)^2 as the probability that two independent standard normal values lie below cZcZ. Deduce the variance of pBp_B.
  3. Show that if the law of T(X)T(X) given θ\theta does not depend on θ\theta, then pBp_B equals the classical p-value, and it is uniform under the model when TT is continuous.
  4. Prove that E[pB]=12(1+P(T(X′)=T(X)))\mathbb{E}[p_B] = \frac12(1 + P(T(X') = T(X))) under the prior predictive law. For Bernoulli data with TT = the number of successes and a uniform prior on the success probability, compute E[pB]\mathbb{E}[p_B] for n=1n = 1.
  5. For the Poisson-gamma model with prior Gamma(aa, rate bb) and T=∑ixiT = \sum_i x_i, show that the posterior predictive mean of TT is n(a+∑ixi)/(b+n)n(a + \sum_i x_i)/(b + n), which tends to the observed ∑ixi\sum_i x_i as a,b→0a, b \to 0. Explain why this statistic cannot detect overdispersion or outliers.

References

  1. Donald B. Rubin, Bayesianly justifiable and relevant frequency calculations for the applied statistician, Annals of Statistics 12(4), 1984, pages 1151 to 1172: the posterior predictive distribution of a test statistic and the tail-area probability as a model check (general locator)
  2. Gelman, Meng and Stern 1996, pages 733 to 807, with the discussion: discrepancies that depend on the parameters, their computation by simulation, and the chi-squared discrepancy (general locator)
  3. Xiao-Li Meng, Posterior predictive p-values, Annals of Statistics 22(3), 1994, pages 1142 to 1160: the bound P(p <= alpha) <= 2 alpha under the prior predictive law, and the concentration of the p-value near 1/2 (general locator)
  4. James M. Robins, Aad van der Vaart and Valérie Ventura, Asymptotic distribution of p values in composite null models, Journal of the American Statistical Association 95(452), 2000, pages 1143 to 1156: the posterior predictive p-value is asymptotically conservative, with a law more concentrated near 1/2 than the uniform, when the mean of the statistic depends on the parameter (general locator)
  5. Bayarri and Berger 2000, pages 1127 to 1142: the partial posterior predictive and conditional predictive p-values, which are closer to uniform (general locator)
  6. Irwin Guttman, The use of the concept of a future observation in goodness-of-fit problems, Journal of the Royal Statistical Society Series B 29(1), 1967, pages 83 to 100 (general locator)

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)
WritingW2 basic
  • three classic examples