Algorithmresearch
Simulation-based calibration
Also called SBC.
Checks a Bayesian sampler by drawing parameters from the prior, simulating data, and testing that the rank of the true parameter among posterior draws is uniform.
- Time
- Θ(N (S + C + L)) worst
- Space
- Θ(L) extra
- Where
- C = the cost of one run of the sampler under test; L = the number of posterior draws per replication; N = the number of replications; S = the cost of one simulation of data
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sean Talts, Michael Betancourt, Daniel Simpson, Aki Vehtari, Andrew Gelman, Samantha R. Cook, Donald B. Rubin, 2018
Simulation-based calibration (SBC) checks that a Bayesian computation is correct, using only the ability to sample from the prior and to simulate data. It repeats one experiment times: draw a parameter from the prior, simulate data from it, run the method under test on to get posterior draws, and record the rank of among the values for a chosen function . Given , the true parameter is itself a draw from the exact posterior, so if the method returns independent exact posterior draws, the rank is uniform on . A histogram of the ranks that is not flat shows an error, and its shape shows which kind: a U shape for posteriors that are too narrow, a hump for posteriors that are too wide, and a slope for a bias.
In plain words
You have a program that claims to compute the answer to a Bayesian question, and you want to know whether it is right without knowing the right answer. Make up a true value the way the model says values arise, make fake data from it, and ask the program for a sample of plausible values. If the program is right, the true value looks like just one more member of that sample. So it is equally likely to land at any position when you sort the sample: lowest, highest, or anywhere between. Repeat this many times and count the positions. A flat count is what a correct program gives. Too many lowest and highest positions mean the program is too sure of itself; too few mean it is not sure enough; a lean to one side means it is biased.
The problem
Input. A prior to draw from; a simulator of data ; the method under test, which given data returns draws meant to come from the posterior ; a real function of the parameter, such as one coordinate; the number of replications .
Output. The counts of the ranks over the replications, and a test of their uniformity.
What the test can show. Uniform ranks are necessary for a correct method, not sufficient. They test that the computed posterior is calibrated on average over the prior and the data, not that it is right for every data set.
The algorithm
SBC(π, SIMULATE, SAMPLER, f, N, L)- 1
counts[0..L] ← 0 - 2
for n ← 1 to N - 3
θ̃ ← a draw from the prior π - 4
ỹ ← SIMULATE(θ̃) - 5
θ₁..θ_L ← SAMPLER(ỹ, L) ▷ the method under test - 6
r ← #{l : f(θ_l) < f(θ̃)} + U{0..#{l : f(θ_l) = f(θ̃)}} ▷ ties broken at random - 7
counts[r] ← counts[r] + 1 - 8
return counts ▷ uniform on 0..L if SAMPLER is correct
L3 and L4 draw from the joint law of the model. The joint density equals , so is a draw from the prior predictive law and, given , is a draw from the exact posterior. L5 runs the method on . L6 computes the rank. The term , a uniform integer up to the number of ties, matters only when can take repeated values, for example with a discrete parameter. L8 returns the counts; the usual test is Pearson's chi-squared test against equal expected counts, often after merging the ranks into equal bins, together with a plot of the histogram.
Markov chain samplers. If L5 runs a Markov chain, its draws are correlated, and correlated draws give a U-shaped histogram even when the chain targets the right law. Talts and coauthors (2018) run a longer chain and keep every -th state, with the chain length divided by its effective sample size, so that about nearly independent draws remain.
Example
Model. and , so the posterior is , with standard deviation . The function is .
Trace. Six replications with exact posterior draws, from random.Random(3):
| posterior mean | the 4 draws, sorted | rank | ||
|---|---|---|---|---|
| 1 | 0.095 | 0.211 | 0.193, 0.275, 0.508, 0.986 | 0 |
| 2 | 1.127 | 0.735 | 0.071, 0.120, 0.192, 0.638 | 4 |
| 3 | , , , | 3 | ||
| 4 | , , , | 4 | ||
| 5 | 1.045 | 0.461 | , 0.015, 0.141, 0.898 | 4 |
| 6 | , , , | 2 |
Each rank is between (the truth is below all draws) and (above all). Six ranks say little; uniformity shows only over many replications.
Correct and wrong samplers. replications with draws, from random.Random(7). The ranks are merged into bins of ; a flat histogram has per bin. The -value is from the chi-squared test on all ranks ( degrees of freedom).
| sampler | counts in 7 bins | -value | shape |
|---|---|---|---|
| exact posterior | 140, 147, 139, 160, 122, 150, 142 | 0.69 | flat |
| standard deviation | 254, 111, 85, 100, 104, 99, 247 | U | |
| standard deviation | 66, 134, 190, 228, 175, 148, 59 | hump | |
| mean standard deviations | 277, 187, 175, 112, 101, 89, 59 | falling | |
| the prior, ignoring the data | 147, 142, 135, 155, 135, 141, 145 | 0.25 | flat |
| exact Markov chain, | 292, 90, 119, 76, 82, 81, 260 | U | |
| the same chain, every 19th state | 149, 128, 140, 154, 149, 127, 153 | 0.41 | flat |
When the draws are too narrow, the truth often falls outside them, so ranks and are common. When they are too wide, the truth sits in their middle. When they are shifted up, the truth tends to be below them. The prior sampler passes, although it ignores the data: the truth and the draws are then independent draws from the prior, so the rank is uniform. The Markov chain has the exact posterior as its stationary law, and its first state is an exact draw, but with lag-one correlation its consecutive states cluster, and the truth falls outside the cluster too often. The effective sample size of such a chain is , so keeping every th state of a chain of length restores a flat histogram.
Correctness
The full proof is in proofs/correctness.md. It proves:
- The truth is a posterior draw. Given , has the law , by Bayes' theorem.
- Uniform ranks. If the method returns independent draws from the exact posterior and has no atoms, the rank is uniform on . The values are exchangeable given , so the truth is equally likely to hold each position.
- Ties. With random tie breaking, as in L6, the rank is uniform with no condition on atoms; the plain count of smaller values is not, since rank is then too likely.
- What is tested. With a continuous computed posterior distribution function , the rank is binomial given , and the ranks are uniform for every exactly when is Uniform(0, 1). This explains the shapes and why the prior sampler passes.
What is proved and what is only measured: claims 1 to 4 are exact, and the tests check claim 3 and the prior sampler in exact rational arithmetic on discrete models. The chi-squared law of the test statistic is a large-sample approximation. With Markov chain draws none of the claims apply; the effect of thinning in the table is measured only.
A correction. Theorem 1 of Talts and coauthors (2018) states uniformity of the plain rank for any one-dimensional function. It needs the condition of claim 2: a constant , or a discrete parameter, gives ties, and the plain rank is then not uniform. The randomized rank of L6 removes the condition.
Proof: Uniform ranks under a correct sampler, with ties, and what uniformity testsfull
Setting. A prior and a model define the joint law of , with marginal and posterior . One replication of SBC draws , then , then from the sampler under test given . A real function of the parameter is fixed. Write and . The plain rank is ; the randomized rank of L6 is
with drawn independently given the values.
Claim 1: the true parameter is a posterior draw given the data
Given , has the law .
Proof. The pair has density by Bayes' theorem, so the conditional density of given is .
Claim 2: rank uniformity without ties
Suppose the sampler returns independent with law , independent of given , and suppose that for almost every the law of under has no atoms. Then for , and almost surely.
Proof. Fix . By Claim 1 and the assumption, are independent values with the same atomless law, so they are distinct with probability one, and . Write and , and let be the rank of among the others. The vector is exchangeable, so swapping and shows that has the same law as . For distinct values, exactly one index has rank , so . Taking expectations, . Averaging over gives the claim.
Claim 3: randomized ranks are uniform even with ties
Under the sampler assumption of Claim 2, but with no condition on atoms, for . If ties have positive probability, the plain rank is not uniform: whenever .
Proof. Let be independent Uniform(0, 1) values, independent of everything else, and order the pairs lexicographically. Given the pairs are independent and identically distributed, and they are distinct with probability one because the are. The argument of Claim 2 shows that the lexicographic rank of is uniform on . Now fix the values . Let . Then , and the second term is the rank of among independent uniform values, which is uniform on . So given the values, and have the same law, hence the same unconditional law, which is uniform.
For the second part, always, so , and on the event that all values are equal, while is positive with probability . That event has positive probability, which makes the inequality strict.
A correction to the usual statement. Talts and coauthors (2018, Theorem 1) state uniformity of the plain rank for any one-dimensional function. That needs the atomless condition of Claim 2: for a constant , the plain rank is in every replication. With discrete parameters, or with a function such as an indicator, use the randomized rank of Claim 3.
Claim 4: what uniform ranks test
Let the sampler return, given , independent draws from some law such that the distribution function is continuous, and let . Then
and the rank is uniform on for every if and only if is Uniform(0, 1).
Proof. Given and , each is below with probability , independently, and ties have probability zero because is continuous. So is binomial given , which gives the formula. If is uniform, . Conversely, if the rank is uniform for every , then gives for all , which are the moments of Uniform(0, 1). A law on is determined by its moments, so is uniform.
So SBC tests whether the value of the computed posterior distribution function at the true parameter, , is uniform. A correct sampler passes by Claim 1, since then is the probability integral transform of a draw from its own continuous law. A sampler whose posteriors are too narrow puts near and , which gives a U-shaped rank histogram; one that is too wide puts near , which gives a hump; one that is shifted up makes small. A sampler that returns the prior for every also passes: then and the draws are independent draws from , and is uniform. Uniform ranks are therefore necessary for a correct sampler but not sufficient.
What is proved and what is measured
Claims 1 to 4 are exact; the tests check Claim 3 and the prior-sampler remark in exact rational arithmetic on discrete models. Two parts of the method are not proved here. The chi-squared test of the rank counts uses Pearson's approximation of the statistic by the chi-squared law with degrees of freedom, which holds as the number of replications grows. When the draws come from a Markov chain, they are dependent, Claims 2 to 4 do not apply, and the fact that thinning to about effective draws restores near-uniform ranks (Talts and coauthors 2018, Algorithm 2) is measured on the page, not proved.
Complexity
Each replication makes one prior draw, one simulation of cost , one run of the method of cost , and comparisons, so the total time is . The run of the method is usually the dominant cost, since it is a full posterior computation; SBC costs times one analysis. The replications are independent and run in parallel. With a Markov chain thinned by , includes chain steps. The memory is the draws of one replication and the counts, .
How many replications are needed: under uniformity each count is binomial, with relative spread . To see a percent excess in a bin of of the ranks with a few standard errors, must be in the thousands, which is why moderate catches only clear errors.
Properties
- Randomized. The counts and the -value vary with the seed; a correct method fails the test at level in a fraction of runs.
- Needs no exact posterior. Only prior draws and data simulation are required, so it checks methods for models where no other reference exists.
- Checks one function at a time. A separate histogram is needed for each coordinate or function , and errors that affect only the dependence between coordinates can pass all of them.
- Necessary, not sufficient. It checks calibration averaged over the prior predictive law. The prior sampler passes, and a method that is wrong for some data sets and wrong in the other direction for others can pass.
- Diagnostic shapes. The histogram shows the kind of error, not only its presence.
Variants and improvements
- Posterior quantiles. Cook, Gelman and Rubin (2006) used the quantile of the truth among the draws, transformed to the normal scale, and combined the results across parameters. With finite the quantile is discrete, so its law is not exactly uniform; ranks remove that problem.
- Bins. Merge the ranks into bins of equal size, with dividing , to stabilize the counts.
- Tests on the empirical distribution function. Compare the empirical distribution function of the normalized ranks with the uniform one, for example by a Kolmogorov-Smirnov test or simultaneous confidence bands; these are more powerful than the histogram for smooth departures.
- Data-dependent test quantities. Taking to depend on the data as well, such as the log-likelihood of at , can reveal errors that every coordinate misses (Modrák and coauthors 2023).
- Amortized methods. For neural posterior estimators and other likelihood-free methods, such as approximate Bayesian computation, each replication is cheap once the method is trained, so SBC with large is a standard check.
When to use it
Use SBC when you write a new sampler, a new model implementation, or an approximate method such as variational inference or ABC, and want evidence that it computes the posterior it should. It finds coding errors in the model, wrong priors in the sampler, and approximations that are systematically too narrow or too wide. For a single data set and an exact-in-principle sampler such as Hamiltonian Monte Carlo, convergence checks such as the Gelman-Rubin diagnostic are cheaper; SBC checks the method over the whole prior. To check the model against real data, use a posterior predictive check instead: SBC assumes the model is true.
Pitfalls
- Autocorrelated draws. Taking consecutive states of a Markov chain in L5 gives a U-shaped histogram even for a correct chain; in the example, . Thin the chain to about effective draws.
- Plain ranks with ties. Counting only the smaller values in L6 when has atoms makes rank too likely, which looks like an error of the method. Break ties at random.
- Drawing the truth from a different prior. If L3 draws from a prior other than the one the method uses, the truth is no longer a posterior draw, and correct methods fail. Use the same prior in both places, or use SBC exactly to detect such a mismatch.
- Reading a flat histogram as proof. The prior sampler gives flat ranks in the example. A flat histogram from L8 says the method is calibrated on average, not that it uses the data correctly; compare also the posterior spread with the prior spread.
- Too few replications. With of a few hundred, the histogram of L8 is noisy, and only large errors are visible. Choose in the thousands for subtle errors, and use the same seed scheme to reproduce failures.
- Priors that are too wide. Very wide priors in L3 simulate extreme data sets on which the method fails for numerical reasons that never matter in practice. Use the prior of the actual analysis, and inspect failing replications.
Implementations
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/simulation-based-calibration/. The authors are listed in prov/GB2WNE.jsonl.
"""Simulation-based calibration (Talts, Betancourt, Simpson, Vehtari and Gelman 2018).
Draw a parameter from the prior, simulate data from it, ask the sampler under test for L
posterior draws given those data, and record the rank of the true parameter among the
draws. If the sampler returns independent draws from the true posterior, the ranks are
uniform on {0, ..., L}. Ties are broken at random, which keeps the ranks uniform when the
quantity has atoms.
"""
import math
import random
from typing import Callable, Sequence
def rank_with_ties(f_true: float, f_draws: Sequence[float], rng: random.Random) -> int:
"""Number of draws below f_true, plus a uniform share of the draws equal to it."""
below = sum(1 for v in f_draws if v < f_true)
ties = sum(1 for v in f_draws if v == f_true)
return below + (rng.randint(0, ties) if ties else 0)
def sbc(
prior_draw: Callable,
simulate: Callable,
posterior_draws: Callable,
f: Callable,
n_reps: int,
n_draws: int,
rng: random.Random,
) -> list[int]:
"""Return the counts of the ranks 0..n_draws over n_reps replications.
posterior_draws(y, n_draws, rng) is the sampler under test.
"""
counts = [0] * (n_draws + 1) # @line L1
for _ in range(n_reps): # @line L2
theta = prior_draw(rng) # @line L3
y = simulate(theta, rng) # @line L4
draws = posterior_draws(y, n_draws, rng) # @line L5
r = rank_with_ties(f(theta), [f(t) for t in draws], rng) # @line L6
counts[r] += 1 # @line L7
return counts # @line L8
def bin_counts(counts: Sequence[int], n_bins: int) -> list[int]:
"""Merge the L + 1 rank counts into n_bins equal bins; n_bins must divide L + 1."""
width, rem = divmod(len(counts), n_bins)
if rem:
raise ValueError("the number of bins must divide L + 1")
return [sum(counts[b * width:(b + 1) * width]) for b in range(n_bins)]
def chi2_sf(x: float, k: int) -> float:
"""P(X >= x) for X chi-squared with k degrees of freedom, in closed form.
Even k: exp(-x/2) sum_{j < k/2} (x/2)^j / j!.
Odd k: erfc(sqrt(x/2)) + exp(-x/2) sum_{j < (k-1)/2} (x/2)^(j+1/2) / Gamma(j + 3/2).
"""
if x <= 0:
return 1.0
h = x / 2
if k % 2 == 0:
term, total = 1.0, 1.0
for j in range(1, k // 2):
term *= h / j
total += term
return math.exp(-h) * total
total = math.erfc(math.sqrt(h))
term = math.sqrt(h) / math.gamma(1.5)
for j in range((k - 1) // 2):
total += math.exp(-h) * term
term *= h / (j + 1.5)
return total
def chi2_uniformity(counts: Sequence[int]) -> tuple[float, float]:
"""Pearson's chi-squared statistic against equal expected counts, and its p-value."""
n, b = sum(counts), len(counts)
e = n / b
stat = math.fsum((c - e) ** 2 / e for c in counts)
return stat, chi2_sf(stat, b - 1)
def thin(chain: Sequence, step: int, n: int) -> list:
"""Every step-th state of the chain, n of them (Talts et al., Algorithm 2)."""
out = list(chain[step - 1::step])[:n]
if len(out) < n:
raise ValueError("chain too short for this thinning")
return out
# A conjugate test model: theta ~ N(0, 1), y_1..y_m ~ N(theta, 1);
# the posterior is N(sum(y) / (m + 1), 1 / (m + 1)).
def normal_model(m: int):
def prior_draw(rng):
return rng.gauss(0.0, 1.0)
def simulate(theta, rng):
return [rng.gauss(theta, 1.0) for _ in range(m)]
def posterior(y):
return sum(y) / (m + 1), 1.0 / (m + 1)
return prior_draw, simulate, posterior
def gaussian_sampler(posterior: Callable, scale: float = 1.0, shift: float = 0.0) -> Callable:
"""Independent draws from N(mean + shift * sd, (scale * sd)^2); scale 1 and shift 0 is correct."""
def draws(y, n, rng):
mu, v = posterior(y)
sd = math.sqrt(v)
return [rng.gauss(mu + shift * sd, scale * sd) for _ in range(n)]
return draws
def ar1_sampler(posterior: Callable, rho: float, step: int = 1) -> Callable:
"""A Markov chain with the exact posterior as its stationary law, started at a
posterior draw: x' = mu + rho (x - mu) + sqrt(1 - rho^2) sd e. Keeps every step-th state."""
def draws(y, n, rng):
mu, v = posterior(y)
sd = math.sqrt(v)
x = rng.gauss(mu, sd)
c = math.sqrt(1 - rho * rho) * sd
chain = []
for _ in range(n * step):
x = mu + rho * (x - mu) + c * rng.gauss(0.0, 1.0)
chain.append(x)
return thin(chain, step, n)
return draws
test_simulation_based_calibration.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simulation-based-calibration/. The authors are listed in prov/GB2WNE.jsonl.
"""Tests for simulation-based calibration: the exact law of the rank in a discrete model
(uniform with random tie breaking, not uniform without it), uniform ranks for a correct
sampler, the characteristic shapes for wrong ones, and thinning of a Markov chain."""
import itertools
import math
import random
import unittest
from fractions import Fraction as F
from simulation_based_calibration import (
ar1_sampler,
bin_counts,
chi2_sf,
chi2_uniformity,
gaussian_sampler,
normal_model,
sbc,
)
def exact_rank_law(prior, like, post_of, n_draws, randomize=True):
"""The exact law of the rank of theta~ among n_draws draws from post_of(y), for a model
with finitely many parameter values and data values. prior[t] and like[t][y] are Fractions."""
k = len(prior)
ys = range(len(like[0]))
law = [F(0)] * (n_draws + 1)
for y in ys:
q = post_of(y)
for t in range(k):
joint = prior[t] * like[t][y]
if joint == 0:
continue
for draws in itertools.product(range(k), repeat=n_draws):
pd = math.prod((q[d] for d in draws), start=F(1))
below = sum(1 for d in draws if d < t)
ties = sum(1 for d in draws if d == t)
if randomize:
for r in range(below, below + ties + 1):
law[r] += joint * pd / (ties + 1)
else:
law[below] += joint * pd
return law
class TestExactRankLaw(unittest.TestCase):
def test_uniform_with_random_ties_and_also_for_the_prior(self):
rng = random.Random(1)
for _ in range(500):
k = rng.randint(2, 4)
m = rng.randint(1, 3)
raw = [rng.randint(1, 9) for _ in range(k)]
prior = [F(v, sum(raw)) for v in raw]
ps = sorted(rng.sample([F(1, 5), F(2, 5), F(3, 5), F(4, 5), F(1, 2)], k))
like = [[math.comb(m, y) * p**y * (1 - p) ** (m - y) for y in range(m + 1)] for p in ps]
def post_of(y):
joint = [prior[t] * like[t][y] for t in range(k)]
s = sum(joint)
return [j / s for j in joint]
n_draws = rng.randint(1, 3)
law = exact_rank_law(prior, like, post_of, n_draws)
self.assertEqual(law, [F(1, n_draws + 1)] * (n_draws + 1))
# without random tie breaking, rank 0 is too likely
plain = exact_rank_law(prior, like, post_of, n_draws, randomize=False)
self.assertEqual(sum(plain), 1)
self.assertGreater(plain[0], F(1, n_draws + 1))
# a sampler that ignores the data and returns the prior also passes
law_prior = exact_rank_law(prior, like, lambda y: prior, n_draws)
self.assertEqual(law_prior, [F(1, n_draws + 1)] * (n_draws + 1))
class TestNormalModel(unittest.TestCase):
L = 20
def run_sbc(self, sampler):
prior_draw, simulate, _ = normal_model(5)
return sbc(prior_draw, simulate, sampler, lambda t: t, 1000, self.L, random.Random(7))
def test_correct_sampler_gives_uniform_ranks(self):
_, _, post = normal_model(5)
c = self.run_sbc(gaussian_sampler(post))
self.assertEqual(sum(c), 1000)
self.assertGreater(chi2_uniformity(c)[1], 0.01)
self.assertGreater(chi2_uniformity(bin_counts(c, 7))[1], 0.01)
def test_wrong_samplers_give_their_shapes(self):
_, _, post = normal_model(5)
expected_ends = 2 * 1000 / (self.L + 1)
narrow = self.run_sbc(gaussian_sampler(post, scale=0.6))
self.assertLess(chi2_uniformity(narrow)[1], 1e-10)
self.assertGreater(narrow[0] + narrow[-1], 2 * expected_ends) # U shape
wide = self.run_sbc(gaussian_sampler(post, scale=1.5))
self.assertLess(chi2_uniformity(wide)[1], 1e-10)
self.assertLess(wide[0] + wide[-1], expected_ends / 2) # hump
shifted = self.run_sbc(gaussian_sampler(post, shift=0.5))
self.assertLess(chi2_uniformity(shifted)[1], 1e-10)
mean_rank = sum(r * c for r, c in enumerate(shifted)) / 1000
self.assertLess(mean_rank, self.L / 2 - 2) # draws too high, so the truth ranks low
def test_prior_sampler_is_not_detected(self):
c = self.run_sbc(lambda y, n, rng: [rng.gauss(0.0, 1.0) for _ in range(n)])
self.assertGreater(chi2_uniformity(c)[1], 0.01)
def test_autocorrelated_chain_fails_and_thinning_fixes_it(self):
_, _, post = normal_model(5)
raw = self.run_sbc(ar1_sampler(post, 0.9))
self.assertLess(chi2_uniformity(raw)[1], 1e-10)
self.assertGreater(raw[0] + raw[-1], 3 * 2 * 1000 / (self.L + 1))
# effective sample size of an AR(1) chain: n (1 - rho) / (1 + rho), so thin by 19
thinned = self.run_sbc(ar1_sampler(post, 0.9, 19))
self.assertGreater(chi2_uniformity(thinned)[1], 0.01)
class TestChiSquared(unittest.TestCase):
def test_closed_forms(self):
# upper 5 percent points from standard tables
for x, k in ((3.841, 1), (5.991, 2), (7.815, 3), (30.144, 19), (31.410, 20)):
self.assertAlmostEqual(chi2_sf(x, k), 0.05, places=3)
for x in (0.1, 1.0, 4.0, 20.0):
self.assertAlmostEqual(chi2_sf(x, 1), math.erfc(math.sqrt(x / 2)), places=12)
self.assertAlmostEqual(chi2_sf(x, 2), math.exp(-x / 2), places=12)
# P(chi2_{k+2} >= x) = P(chi2_k >= x) + (x/2)^(k/2) e^(-x/2) / Gamma(k/2 + 1)
for k in range(1, 12):
h = x / 2
self.assertAlmostEqual(chi2_sf(x, k + 2), chi2_sf(x, k) + h ** (k / 2) * math.exp(-h) / math.gamma(k / 2 + 1), places=12)
if __name__ == "__main__":
unittest.main()
History
Geweke (2004) tested posterior simulators by comparing two ways of drawing from the joint law of parameters and data. Cook, Gelman and Rubin (2006) proposed to validate Bayesian software by simulating parameters from the prior and data from the model, and checking that the posterior quantiles of the true parameters are uniform. Gelman (2017) published a correction noting that dependence between draws changes the law of their test statistics. Talts, Betancourt, Simpson, Vehtari and Gelman (2018) replaced the quantiles by rank statistics, whose law is exactly uniform for independent draws, interpreted the shapes of the rank histogram, and gave a thinning rule for Markov chains. SBC is now a standard check in probabilistic programming and in simulation-based inference.
References
- Sean Talts, Michael Betancourt, Daniel Simpson, Aki Vehtari and Andrew Gelman, Validating Bayesian inference algorithms with simulation-based calibration, 2018, Section 4.1 and Algorithm 1 (rank statistics and the SBC histogram), Section 4.2 (U shape for posteriors that are too narrow, hump for too wide, skew for bias), Section 5.1 and Algorithm 2 (thinning a Markov chain by its effective sample size), Appendix B (proof of Theorem 1)
- Samantha R. Cook, Andrew Gelman and Donald B. Rubin, Validation of software for Bayesian models using posterior quantiles, Journal of Computational and Graphical Statistics 15(3), 2006, pages 675 to 692: posterior quantiles of the true parameter are uniform for correct software (general locator)
- Andrew Gelman, Correction to Cook, Gelman and Rubin (2006), Journal of Computational and Graphical Statistics, 2017, the dependence created by autocorrelated draws changes the law of the test statistics of the 2006 paper (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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GB2WNE Edit this page History Report an error Markdown