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 , a statistic of the data that may also depend on the parameters. Draw from the posterior, draw a replicated data set of the same size from the model at , and compare with . Repeating this gives the posterior predictive distribution of the test quantity, and the posterior predictive p-value
where the probability is over and . A value near or 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 , 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 , from Markov chain Monte Carlo or any other sampler, and a way to simulate data from the model at a given .
- 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 . A statistic that the model fits by construction, such as a sufficient statistic of its parameters, gives near whatever the data.
The template
The holes are the test quantity T and the draws θ_s (the reference distribution).
PPC(x, θ₁..θ_S, SIMULATE, T)- 1
count ← 0 - 2
for s ← 1 to S ▷ hole: draws from the posterior - 3
x_rep ← SIMULATE(θ_s) ▷ same size and design as x - 4
if T(x_rep, θ_s) ≥ T(x, θ_s) then count ← count + 1 ▷ hole T - 5
return p_B ≈ count / S, and the pairs (T(x_rep, θ_s), T(x, θ_s)) for a plot
Common choices:
Ta 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.Ta discrepancy: a function of both, such as the chi-squared discrepancy of Gelman, Meng and Stern (1996). In L4 it is evaluated at the same for the real and the replicated data.θ_sfrom the posterior: the posterior predictive check. From the prior: a prior predictive check, which tests the prior as well. From the posterior without observation : a cross-validated check of observation .- Graphical: plot the observed data among a few replicated data sets, or the observed on the histogram of replicated . A plot often shows the kind of misfit better than the number .
Facts about when the model is true. Suppose the data are drawn from the prior predictive law, that is, from the prior and from the model. Write for the classical p-value at a known , so .
Mean. with independent given . By symmetry this is , which is for a continuous .
Meng's bound. . Proof. is a classical p-value at the true , so for every , and its quantile function satisfies . Let , an event determined by . Then . Among all events of probability , is smallest when holds the smallest values of , so . Hence , and .
So a check at level never rejects a true model more often than . In the other direction, is usually far more concentrated near than a uniform value, and a small is stronger evidence of misfit than the same classical p-value.
Classic examples
The normal mean: the pile-up near 1/2. with known, prior , and . With , the posterior is with and , and . So
When the model is true, is standard normal, so , with , and . Since , is less spread than a uniform value, whose variance is the case . With :
| sd of | ||||
|---|---|---|---|---|
| 1 | 0.577 | 0.200 | 0.0022 | 0.757 |
| 10 | 0.218 | 0.085 | above 0.999 | |
| 100 | 0.071 | 0.028 | 1 | |
| uniform | 1 | 0.289 | 0.05 | 0.5 |
With , data sets from random.Random(5) and draws each, the template gives sd and a share in . The sample mean is sufficient for , 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 , the sample variance. Its law, , does not depend on , so the posterior predictive law of is its sampling law, is the classical chi-squared p-value, and 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: Poisson() with Gamma(1, rate 0.25), so Gamma(, rate ). Test quantity: the dispersion index , near for Poisson data. With :
| data | values | for | for | for | |
|---|---|---|---|---|---|
| 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 is impossible under a Poisson law with mean near . The mean, a sufficient statistic, gives for both data sets. The number of zeros, in B, gives 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 ( data sets drawn from the prior predictive), the dispersion index gives with sd , close to uniform, while the mean gives sd .
The chi-squared discrepancy. For a model with means and variances , the discrepancy 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 = the correlation of the residuals with a covariate left out of the model, or the largest absolute residual.
Variations
- Prior predictive check. Draw 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 for each, and use their distribution to turn 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 itself carries, so that the data are not used twice; the result is close to uniform under the model.
- Cross-validated checks. Compare each with its predictive law given the other data, for example by the probability integral transform of , 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 as a uniform p-value. Under a true model, piles up near ; with in the normal example, is , not . A check in L4 that gives is not reassuring evidence of fit, and is strong evidence of misfit.
- A test quantity the model fits by construction. Taking
Tin L4 to be a sufficient statistic, such as the sample mean of a Poisson model, gives for any data; in the count example it was for both data sets. ChooseTto 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 .
- Different for the two sides of a discrepancy. When
Tdepends on , L4 must use the same for and . 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 draws in L2, the smallest positive value is ; in the table means fewer than in . Report it as , and increase if the size matters.
- Testing many quantities without a plan. Trying many test quantities and reporting the smallest 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.
# 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
- In the normal mean example, derive and . What happens as and as ?
- Show that for standard normal , by writing as the probability that two independent standard normal values lie below . Deduce the variance of .
- Show that if the law of given does not depend on , then equals the classical p-value, and it is uniform under the model when is continuous.
- Prove that under the prior predictive law. For Bernoulli data with = the number of successes and a uniform prior on the success probability, compute for .
- For the Poisson-gamma model with prior Gamma(, rate ) and , show that the posterior predictive mean of is , which tends to the observed as . Explain why this statistic cannot detect overdispersion or outliers.
References
- 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)
- 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)
- 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)
- 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)
- Bayarri and Berger 2000, pages 1127 to 1142: the partial posterior predictive and conditional predictive p-values, which are closer to uniform (general locator)
- 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.
| 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 | W2 basic |
|
Tag 2TJBEH Edit this page History Report an error Markdown