Techniqueadvanced
Approximate Bayesian computation
Also called likelihood-free inference.
Bayesian inference without a likelihood: simulate data from parameters drawn from the prior and keep those whose summary statistics are close to the observed ones.
Approximate Bayesian computation (ABC) is a family of methods for Bayesian inference when the likelihood cannot be computed but data can be simulated from the model. It replaces the condition "the simulated data equal the observed data" by "the summaries of the simulated data are within of the observed summaries". Every ABC method targets the -posterior
where is a summary map and a distance. Two approximations separate from the true posterior: the summaries, which lose information unless they are sufficient, and the tolerance . The methods differ in how they sample (rejection, Markov chains, sequential Monte Carlo) and in how they correct for afterwards.
In plain words
Some models are easy to run forward but hard to write down as a formula. A model of how genes spread through a population, or how a disease spreads through a city, can produce fake data for any setting, but no one can compute how likely the real data are. ABC learns the settings anyway. Pick a setting from what you believed beforehand, run the model, and compare a few key numbers of the fake data with those of the real data. Keep the setting when they are close. The kept settings form an approximate answer. The answer depends on which numbers you compare and on how close counts as close. Choosing those two things well is most of the work.
When it applies
- The model can be simulated, but the likelihood cannot be evaluated. Typical cases are coalescent models in population genetics, stochastic epidemic and ecological models, and agent-based models. If the likelihood can be evaluated, even slowly, likelihood-based methods are more accurate.
- A proper prior that can be sampled. All ABC samplers start from prior draws.
- A small set of informative summaries. The cost grows like for summaries, so must be small; and the answer is only as good as the information in .
- Simulations are affordable. Even good ABC samplers need thousands to millions of simulations.
The template
The holes are the summaries S, the distance ρ, the tolerance ε, the sampler SAMPLER and the correction ADJUST.
ABC(x, π, SIMULATE, S, ρ, ε, SAMPLER, ADJUST)- 1
s_obs ← S(x) ▷ hole S: the summaries - 2
accept(θ, Y) ← [ρ(S(Y), s_obs) ≤ ε] ▷ holes ρ and ε - 3
(θᵢ, sᵢ), i = 1..N ← SAMPLER(π, SIMULATE, accept) ▷ rejection, MCMC or SMC - 4
θᵢ ← ADJUST(θᵢ, sᵢ, s_obs) ▷ e.g. regression; the identity if none - 5
return θ₁..θ_N ▷ they target π_ε, or an adjusted version
Common choices:
SAMPLER= rejection: draw from the prior and keep it when it passes L2; the ABC rejection algorithm proves that the kept values are exact draws from .SAMPLER= Markov chain: a Metropolis-Hastings chain on whose proposal is accepted only if a fresh simulation passes L2 and the usual prior and proposal ratio test passes. It leaves invariant.SAMPLER= sequential Monte Carlo: ABC-SMC moves a weighted population through falling tolerances.εas a quantile: simulate a fixed number of pairs and keep the closest fraction, for example percent.ρscaled: divide each summary by its spread across prior simulations before taking the Euclidean distance.
Why the template targets . The pair drawn from and kept when lies in the set has -marginal , up to a constant. With , discrete data and a sufficient , this is the exact posterior, by the Fisher-Neyman factorization theorem. Both proofs are on the ABC rejection page.
Regression adjustment (Beaumont, Zhang and Balding 2002). Among the kept pairs, fit by weighted linear regression, with Epanechnikov weights , and replace by .
Why it works. Suppose that, under the joint law of , with independent of . Then has the law of , and every adjusted value has that law, whatever is. So the tolerance no longer widens the answer. When the relation is not linear or the spread of depends on , the adjustment is only approximately right, which is why it is applied locally, within a moderate .
Classic examples
Binomial data with rejection. For successes in trials, a uniform prior and = the number of successes, ABC rejection with keeps one proposal in and gives the exact posterior Beta(4, 8). With the variance of the kept values grows from to . That page has the full tables.
Sequential ABC on the same model. With successes in trials, ABC-SMC with tolerances and particles reaches Beta(7, 15) with simulations, against about for rejection. With successes in trials the saving is a factor of two.
Population genetics. Tavaré, Balding, Griffiths and Donnelly (1997) inferred the age of the most recent common ancestor of a sample of DNA sequences under the coalescent by keeping the simulated genealogies whose number of segregating sites matched the data. The summary is discrete, so the match was exact. Pritchard and coauthors (1999) used several summaries of Y chromosome data with a tolerance.
Regression adjustment for a normal mean. with prior and ; the exact posterior has mean and standard deviation . With simulations from random.Random(30):
| kept | plain mean | plain sd | adjusted mean | adjusted sd | |
|---|---|---|---|---|---|
| 0.1 | 501 | 0.6643 | 0.4691 | 0.6574 | 0.4687 |
| 0.5 | 2545 | 0.6256 | 0.5333 | 0.6449 | 0.4508 |
| 1.0 | 5033 | 0.6084 | 0.7190 | 0.6436 | 0.4494 |
| 2.0 | 9626 | 0.5402 | 1.1763 | 0.6468 | 0.4472 |
Without adjustment, the standard deviation grows with ; with it, keeps half of all simulations and is still within percent of the exact value. Here the relation of to is exactly linear with normal noise, the case in which the adjustment is exact.
Model choice needs more than sufficiency within each model. Robert, Cornuet, Marin and Pillai (2011) give this example. Model P: are Poisson() with Exp(1). Model G: they are geometric, , with Uniform(0, 1). The sum is sufficient within each model. The exact evidences are
Within model , the law of given does not depend on the parameter: it is multinomial, , under P, and uniform over the compositions, , under G. So , and the Bayes factors satisfy
ABC with and estimates , not . For and , for every data set, while has and has ; the factors are and . With equal prior model probabilities and simulations per run from one random.Random(4) stream, ABC with gives for and for (exact for : ). ABC on the sorted data, which are sufficient for both the parameter and the model index, gives for (exact: ) and for (exact: ). The Bayes factor from an insufficient summary can point to the wrong model.
Variations
- Choice of summaries. Semi-automatic ABC fits a regression of on many candidate statistics from pilot simulations and uses the fitted values as ; other methods select summaries by information criteria or learn them with neural networks.
- Kernel ABC. Replace the indicator of L2 by a smooth kernel weight , giving weighted samples.
- Non-linear adjustment. Replace the linear regression of L4 by a heteroscedastic non-linear regression, such as a neural network.
- Synthetic likelihood. Assume that is normal given , estimate its mean and covariance from simulations at each , and use the normal density as an approximate likelihood inside MCMC.
- Neural posterior estimation. Train a conditional density estimator on simulated pairs to approximate directly; this is the modern form of likelihood-free inference, and it is checked with simulation-based calibration.
- Model checking. The same simulations give a posterior predictive check of the summaries, which shows whether the model can reproduce the data at all.
Pitfalls
- Treating as the posterior. L2 with widens the answer: in the table, the standard deviation is instead of at . Report , check stability as it falls, or adjust in L4.
- Insufficient summaries in model choice. Using L1 with summaries sufficient within each model gives the Bayes factor of the summaries, which in the example is where the truth is . Use summaries whose means differ between the models (Marin, Pillai, Robert and Rousseau 2014), or avoid ABC model choice.
- Too many summaries. L2 with summaries keeps a fraction of order ; with the whole data vector of five normal values, simulations kept a single value at . Reduce the summaries to a few informative ones, one per parameter if possible.
- Unscaled distance. In L2, a summary measured in thousands drowns a summary measured in fractions. Scale each summary first.
- Extrapolating the adjustment. L4 with a global linear fit over a huge tolerance relies on linearity far from . Keep the Epanechnikov weights and a moderate , and compare the adjusted answer for two tolerances.
- No check of calibration. ABC answers can be overconfident without any warning. Run the whole pipeline on simulated data sets with known parameters and test the coverage, as in simulation-based calibration.
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/approximate-bayesian-computation/. The authors are listed in prov/5HMWEW.jsonl.
"""Approximate Bayesian computation: the template with a rejection sampler and an
optional local linear regression adjustment (Beaumont, Zhang and Balding 2002), plus
the exact Bayes factors of the Poisson versus geometric example of model choice.
abc returns the kept parameters together with their simulated summaries.
Cost: n_sims prior draws and simulations, then O(k) for the k kept pairs.
"""
import math
import random
from fractions import Fraction
from typing import Callable, Sequence
def abc(
x,
prior_draw: Callable,
simulate: Callable,
summary: Callable,
distance: Callable,
eps: float,
n_sims: int,
rng: random.Random,
adjust: bool = False,
) -> list:
"""The template with SAMPLER = rejection and ADJUST = regression (if adjust).
Returns a list of (theta, s, weight). Without adjustment all weights are 1.
Precondition: scalar theta and scalar summary when adjust is True.
"""
s_obs = summary(x) # @line L1
def accept(s): # @line L2
return distance(s, s_obs) <= eps
kept = []
for _ in range(n_sims): # @line L3
th = prior_draw(rng)
s = summary(simulate(th, rng))
if accept(s):
kept.append((th, s, 1.0))
if adjust:
kept = regression_adjust(kept, s_obs, eps) # @line L4
return kept # @line L5
def regression_adjust(kept: Sequence, s_obs: float, eps: float) -> list:
"""Local linear regression adjustment with Epanechnikov weights.
Fit theta = a + b (s - s_obs) by weighted least squares over the kept pairs,
with weights 1 - (|s - s_obs| / eps)^2, and return (theta - b (s - s_obs), s, weight).
If the summaries do not vary, nothing is changed.
"""
ws = [max(0.0, 1.0 - ((s - s_obs) / eps) ** 2) if eps > 0 else 1.0 for _, s, _ in kept]
tot = math.fsum(ws)
if tot == 0:
return list(kept)
sm = math.fsum(w * (s - s_obs) for w, (_, s, _) in zip(ws, kept)) / tot
tm = math.fsum(w * t for w, (t, _, _) in zip(ws, kept)) / tot
sxx = math.fsum(w * (s - s_obs - sm) ** 2 for w, (_, s, _) in zip(ws, kept))
if sxx == 0:
return list(kept)
sxy = math.fsum(w * (s - s_obs - sm) * (t - tm) for w, (t, s, _) in zip(ws, kept))
b = sxy / sxx
return [(t - b * (s - s_obs), s, w) for w, (t, s, _) in zip(ws, kept)]
def weighted_mean_var(kept: Sequence) -> tuple[float, float]:
tot = math.fsum(w for _, _, w in kept)
m = math.fsum(w * t for t, _, w in kept) / tot
v = math.fsum(w * (t - m) ** 2 for t, _, w in kept) / tot
return m, v
# Model choice: Poisson(lambda), lambda ~ Exp(1), against Geometric(p) on {0, 1, ...},
# P(x | p) = p (1 - p)^x, p ~ Uniform(0, 1). All values are exact Fractions.
def evidence_poisson(xs: Sequence[int]) -> Fraction:
"""m_P(x) = Gamma(S + 1) / ((n + 1)^(S + 1) prod x_i!)."""
n, s = len(xs), sum(xs)
return Fraction(math.factorial(s), (n + 1) ** (s + 1) * math.prod(math.factorial(v) for v in xs))
def evidence_geometric(xs: Sequence[int]) -> Fraction:
"""m_G(x) = B(n + 1, S + 1) = n! S! / (n + S + 1)!."""
n, s = len(xs), sum(xs)
return Fraction(math.factorial(n) * math.factorial(s), math.factorial(n + s + 1))
def evidence_poisson_sum(n: int, s: int) -> Fraction:
"""Marginal probability of S = s under the Poisson model: n^s / (n + 1)^(s + 1)."""
return Fraction(n**s, (n + 1) ** (s + 1))
def evidence_geometric_sum(n: int, s: int) -> Fraction:
"""Marginal probability of S = s under the geometric model: C(n + s - 1, s) B(n + 1, s + 1)."""
return math.comb(n + s - 1, s) * Fraction(math.factorial(n) * math.factorial(s), math.factorial(n + s + 1))
def abc_model_choice(xs: Sequence[int], summary: Callable, n_sims: int, rng: random.Random) -> tuple[int, int]:
"""ABC rejection over (model, parameter) with equal prior model probabilities and eps = 0.
Returns (kept under Poisson, kept under geometric). Their ratio estimates the Bayes
factor of the summary, which equals the true one only if the summary is sufficient
for the model index as well.
"""
n = len(xs)
s_obs = summary(xs)
counts = [0, 0]
for _ in range(n_sims):
m = rng.randrange(2)
if m == 0:
lam = rng.expovariate(1.0)
y = [_poisson(lam, rng) for _ in range(n)]
else:
p = rng.random()
y = [_geometric(p, rng) for _ in range(n)]
if summary(y) == s_obs:
counts[m] += 1
return counts[0], counts[1]
def _poisson(lam: float, rng: random.Random) -> int:
k, prod, lim = 0, rng.random(), math.exp(-lam)
while prod > lim:
k += 1
prod *= rng.random()
return k
def _geometric(p: float, rng: random.Random) -> int:
"""Number of failures before the first success."""
if p >= 1.0:
return 0
u = 1.0 - rng.random()
return int(math.log(u) / math.log1p(-p)) if p > 0 else 10**9
test_approximate_bayesian_computation.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-bayesian-computation/. The authors are listed in prov/5HMWEW.jsonl.
"""Tests for the ABC template: exact Bayes factors of the Poisson and geometric models,
ABC model choice with a summary that is or is not sufficient for the model index, and
the regression adjustment."""
import itertools
import math
import random
import unittest
from fractions import Fraction as F
from approximate_bayesian_computation import (
abc,
abc_model_choice,
evidence_geometric,
evidence_geometric_sum,
evidence_poisson,
evidence_poisson_sum,
regression_adjust,
weighted_mean_var,
)
class TestExactBayesFactors(unittest.TestCase):
def test_page_values(self):
self.assertEqual(evidence_poisson((0, 0, 3)) / evidence_geometric((0, 0, 3)), F(35, 64))
self.assertEqual(evidence_poisson((1, 1, 1)) / evidence_geometric((1, 1, 1)), F(105, 32))
self.assertEqual(evidence_poisson_sum(3, 3) / evidence_geometric_sum(3, 3), F(189, 128))
def test_sum_evidences_add_up_over_data_sets(self):
# m(S = s) is the sum of m(x) over all x with sum s.
for n in range(1, 4):
for s in range(0, 6):
xs_all = [x for x in itertools.product(range(s + 1), repeat=n) if sum(x) == s]
self.assertEqual(sum(evidence_poisson(x) for x in xs_all), evidence_poisson_sum(n, s))
self.assertEqual(sum(evidence_geometric(x) for x in xs_all), evidence_geometric_sum(n, s))
def test_true_bayes_factor_is_the_summary_one_times_a_data_factor(self):
# B(x) = B_S(s) * h_P(x) / h_G(x), with h_P(x) = s! / (n^s prod x_i!) the multinomial
# probability of x given s, and h_G(x) = 1 / C(n + s - 1, s), uniform on compositions.
rng = random.Random(1)
for _ in range(500):
n = rng.randint(1, 6)
xs = [rng.randint(0, 5) for _ in range(n)]
s = sum(xs)
b = evidence_poisson(xs) / evidence_geometric(xs)
bs = evidence_poisson_sum(n, s) / evidence_geometric_sum(n, s)
hp = F(math.factorial(s), n**s * math.prod(math.factorial(v) for v in xs))
hg = F(1, math.comb(n + s - 1, s))
self.assertEqual(b, bs * hp / hg)
class TestModelChoice(unittest.TestCase):
def test_sum_is_not_sufficient_for_the_model_but_the_sorted_data_are(self):
rng = random.Random(4)
xs = (0, 0, 3)
target_s = F(189, 128) / (1 + F(189, 128)) # 0.5962 for any data with S = 3
target = F(35, 64) / (1 + F(35, 64)) # 0.3535, the true posterior probability
a, b = abc_model_choice(xs, sum, 100000, rng)
p = a / (a + b)
self.assertLess(abs(p - float(target_s)), 4 * math.sqrt(p * (1 - p) / (a + b)))
c, d = abc_model_choice(xs, lambda y: tuple(sorted(y)), 100000, rng)
q = c / (c + d)
self.assertLess(abs(q - float(target)), 4 * math.sqrt(q * (1 - q) / (c + d)))
self.assertGreater(p - q, 0.15)
class TestRegressionAdjustment(unittest.TestCase):
def test_exact_linear_relation_is_removed(self):
rng = random.Random(2)
for _ in range(500):
a, b = rng.uniform(-5, 5), rng.uniform(-5, 5)
s_obs = rng.uniform(-1, 1)
ss = [s_obs + rng.uniform(-1, 1) for _ in range(rng.randint(2, 20))]
kept = [(a + b * (s - s_obs), s, 1.0) for s in ss]
out = regression_adjust(kept, s_obs, 1.0)
for t, _, _ in out:
self.assertAlmostEqual(t, a, places=8)
def test_normal_mean_with_a_large_tolerance(self):
# x_i ~ N(theta, 1), n = 5, theta ~ N(0, 3^2); exact posterior sd 0.4423.
rng = random.Random(11)
xs = [round(rng.gauss(1.0, 1.0), 2) for _ in range(5)]
n, tau = 5, 3.0
v = 1 / (n + 1 / tau**2)
m = v * sum(xs)
def prior_draw(r):
return r.gauss(0, tau)
def simulate(t, r):
return [r.gauss(t, 1) for _ in range(n)]
def summary(y):
return sum(y) / len(y)
plain = abc(xs, prior_draw, simulate, summary, lambda u, w: abs(u - w), 2.0, 20000, random.Random(30))
adj = abc(xs, prior_draw, simulate, summary, lambda u, w: abs(u - w), 2.0, 20000, random.Random(30), adjust=True)
_, vp = weighted_mean_var(plain)
ma, va = weighted_mean_var(adj)
self.assertGreater(math.sqrt(vp), 1.0)
self.assertLess(abs(math.sqrt(va) - math.sqrt(v)), 0.03)
self.assertLess(abs(ma - m), 0.05)
if __name__ == "__main__":
unittest.main()
Exercises
- Show that for Bernoulli trials with a uniform prior and = the number of successes, ABC rejection with keeps a proposal with probability , whatever the observed count is. What is the probability for the window when it stays inside ?
- Let with known, a flat prior on , and . Show that is the law of with and Uniform independent, so its variance is .
- In the Poisson against geometric example, derive , and the factors and . Find a data set with and for which the true Bayes factor is largest.
- Show that for independent and identically distributed data, the sorted data set is sufficient for the model index of any two models, so ABC with on sorted discrete data gives the true posterior model probabilities.
- Show that the ABC Metropolis-Hastings chain, which accepts a move only if a fresh simulation at passes L2 and a uniform draw is below , satisfies detailed balance with respect to the joint law .
References
- Donald B. Rubin, Bayesianly justifiable and relevant frequency calculations for the applied statistician, Annals of Statistics 12(4), 1984, pages 1151 to 1172: drawing from the prior, simulating, and keeping matches as a description of Bayes' rule (general locator)
- Beaumont, Zhang and Balding 2002, pages 2025 to 2035: the name, the tolerance, and local linear regression adjustment with Epanechnikov weights (general locator)
- Christian P. Robert, Jean-Marie Cornuet, Jean-Michel Marin and Natesh S. Pillai, Lack of confidence in approximate Bayesian computation model choice, Proceedings of the National Academy of Sciences 108(37), 2011, pages 15112 to 15117: summaries sufficient within each model need not be sufficient for model choice; the Poisson against geometric example (general locator)
- Marin, Pillai, Robert and Rousseau 2014, pages 833 to 859: conditions on the summaries under which ABC model choice is consistent (general locator)
- Simon Tavaré, David J. Balding, Robert C. Griffiths and Peter Donnelly, Inferring coalescence times from DNA sequence data, Genetics 145(2), 1997, pages 505 to 518 (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 5HMWEW Edit this page History Report an error Markdown