Algorithmadvanced
ABC rejection algorithm
Also called rejection ABC.
Draw a parameter from the prior, simulate a data set, and accept the parameter when its summaries lie within epsilon of the observed ones. The accepted draws approximate the posterior.
- Time
- Θ(N C / A) expected
- Space
- Θ(N) extra
- Where
- A = the acceptance probability, P(rho(S(Y), s_obs) <= eps) under the prior predictive; C = the cost of one simulation; N = the number of accepted values
- Model
- Real RAM
- Properties
- randomizednot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Simon Tavaré, David J. Balding, Robert C. Griffiths, Peter Donnelly, Jonathan K. Pritchard, Mark A. Beaumont, 1997
The ABC rejection algorithm samples from an approximate posterior when the likelihood cannot be evaluated but data can be simulated from the model. It draws from the prior , simulates a data set at , and keeps when the summaries lie within a tolerance of the observed summaries . The kept values are an exact, independent sample from the -posterior . With discrete data, a sufficient statistic and , that is the exact posterior. It is the simplest member of approximate Bayesian computation.
In plain words
Suppose you have a machine that can produce fake data for any setting of its knobs, but no formula for how likely real data are. To learn which settings explain the real data, pick a setting at random from what you believed beforehand, run the machine, and look at the fake data. If it looks like the real data, keep the setting; if not, throw it away. Repeat many times. The settings you keep are the ones that often produce data like yours, and in the right proportions. Comparing whole data sets is too strict, so you compare a few numbers that describe them, and you allow a small gap. A smaller gap gives a better answer, but you throw away more runs.
The problem
Input. A proper prior that can be sampled; a simulator that draws a data set for any ; observed data ; a summary map , a distance and a tolerance ; the number of values to keep.
Output. independent draws from , where is the probability that a simulation at is close enough.
The algorithm
ABC-REJECTION(π, simulator, S, s_obs, ρ, ε, N)- 1
K ← empty list - 2
while |K| < N - 3
θ ← a draw from π - 4
Y ← a data set simulated from f(· | θ) - 5
if ρ(S(Y), s_obs) ≤ ε then - 6
append θ to K - 7
return K
L3 and L4 draw a pair from the joint law . L5 keeps the pair when the simulated summaries fall in a ball of radius around the observed ones; this is rejection sampling from the joint law conditioned on that ball, and L6 keeps only the part. The algorithm never evaluates . Each pass of the loop is independent, so the passes can run in parallel, and the implementation also stops after a given number of simulations.
Example
Trace. successes in Bernoulli trials, uniform prior on , = the number of successes, , . With random.Random(3):
| proposal | (L3) | successes (L4) | kept (L5) |
|---|---|---|---|
| 1 | 0.2380 | 3 | yes |
| 2 | 0.4703 | 2 | no |
| 3 | 0.7582 | 7 | no |
| 4 | 0.8009 | 7 | no |
| 5 | 0.5072 | 2 | no |
| 6 | 0.1631 | 1 | no |
| 7 | 0.8539 | 8 | no |
| 8 | 0.0449 | 1 | no |
| 9 | 0.1974 | 2 | no |
| 10 | 0.5201 | 4 | no |
| 11 | 0.9778 | 10 | no |
| 12 | 0.4663 | 5 | no |
One proposal in is kept. The exact acceptance probability is , and the kept values follow the exact posterior Beta(4, 8), with mean and variance .
The effect of the tolerance. Same model, kept values per row, random.Random(2025). The exact columns come from in rational arithmetic.
| acceptance, measured | exact | mean, measured | exact | variance, measured | exact | |
|---|---|---|---|---|---|---|
| 0 | 0.0903 | 0.0909 | 0.3287 | 0.3333 | 0.01632 | 0.01709 |
| 1 | 0.2766 | 0.2727 | 0.3310 | 0.3333 | 0.02158 | 0.02137 |
| 2 | 0.4583 | 0.4545 | 0.3318 | 0.3333 | 0.03048 | 0.02991 |
| 3 | 0.6425 | 0.6364 | 0.3340 | 0.3333 | 0.04188 | 0.04274 |
The window is symmetric around , so the mean does not move, but the variance grows by percent at and more than doubles at . A larger tolerance keeps more proposals and gives a wider answer.
An insufficient summary. Same data, , but = the number of successes in the first five trials only. The kept values then follow Beta(3, 4), the posterior given half of the data: measured mean and variance , against the exact and . The algorithm is correct for the information in , not for the information in .
The curse of dimensionality. with prior ; the exact posterior standard deviation is . With (one number), the acceptance probability halves when halves: , , and for , with posterior standard deviations , , and . With = the whole data vector in and the Euclidean distance, it is at and at , and simulations give only one kept value at .
Correctness
The full proof is in proofs/correctness.md. It proves:
- The -posterior. The kept values are independent draws from , and the number of simulations per kept value is geometric with mean , where .
- Exactness at . For a discrete summary, and , the marginal likelihood of the summary. If the data are discrete and is sufficient, the Fisher-Neyman factorization theorem shows , so is the exact posterior. For the binomial with a uniform prior, .
- The limit . For continuous summaries in with a bounded density continuous at , and .
The key invariant is that each pass of L3 to L5 is an independent draw of from the joint law, kept when falls in a fixed set. What is proved and what is measured: items 1 and 2 are exact, and the tests check them with exact rational probabilities over every random path of one proposal, on random discrete models. Item 3 is a limit; the size of the error at a fixed is not bounded on this page but measured in the tables. The Kolmogorov-Smirnov distance of kept values to Beta(4, 8) is below in the test.
Proof: The law of the values kept by the ABC rejection algorithmfull
Setting. is a proper prior on . For each , is a simulated data set, is a summary map, is the observed summary, is a distance with only if , and . One proposal draws , then , and keeps when . Write
Claim 1: the kept values follow the -posterior
If , the kept values are independent with law
each proposal is kept with probability , and the number of proposals per kept value is geometric with mean .
Proof. For one proposal and a measurable set , conditioning on gives
With the probability of being kept is , and . Proposals use fresh randomness, so they are independent and identically distributed. The first kept proposal therefore comes after a geometric number of trials with success probability , its value has law , and the process starts afresh after it, which makes the kept values independent.
Claim 2: tolerance zero with discrete data
Assume that takes countably many values and . Then , the probability function of the summary, and the kept values follow
The acceptance probability is , the marginal likelihood of the summary.
If moreover the data are discrete and is a sufficient statistic, then is the exact posterior .
Proof. Since only if , the event is ; Claim 1 gives the first two statements by Bayes' theorem for the observation . For the last one, the Fisher-Neyman factorization theorem gives . Summing over the data sets with the observed summary,
where does not depend on . Also . So and are proportional as functions of (when , which holds because was observed), and the two posteriors coincide.
Example. For Bernoulli trials with = the number of successes and a uniform prior on , for every . For , one proposal in is kept. With a window that stays inside , .
Insufficient summaries. If is not sufficient, Claim 2 still holds with , which is a valid posterior given less information, and usually wider than .
Claim 3: tolerance tending to zero with continuous summaries
Assume that has a density that is continuous in at for every and bounded by a constant , that is a norm, and that . Then, as , for every measurable , and , where is the volume of the unit ball of .
Proof. Let be the ball of radius around , of volume . Then is the mean of over , which tends to by continuity and is bounded by . By dominated convergence ( is a probability measure), for every , including . Divide the two limits.
The second limit is the curse of dimensionality: for small the expected number of simulations per kept value is about , which grows like .
What is exact and what is measured
Claims 1 and 2 are exact: with discrete data, a sufficient summary and , ABC rejection is an exact posterior sampler. The tests check Claims 1 and 2 with exact rational probabilities by listing every random path of one proposal. Claim 3 is a limit; at a fixed the error of is not bounded here, and the page measures it.
Complexity
Each pass costs one prior draw and one simulation of cost . The number of passes per kept value is geometric with mean , so values cost in expectation. is the prior predictive probability of the -ball. It falls like for continuous summaries, and it is small when the prior is wide compared with the posterior; for the binomial example, . The kept values take space; nothing else is stored.
Properties
- Exact for . There is no Markov chain and no weight: the kept values are independent and identically distributed.
- Likelihood-free. Only forward simulation is needed.
- Embarrassingly parallel and online. Proposals are independent and can stop at any time.
- Two approximations. The summary loses information unless it is sufficient, and the tolerance widens the answer.
- Gives the evidence of the summary. The acceptance rate estimates , and estimates , which can be used for model choice only when is sufficient for both models together.
Variants and improvements
- Keep the closest fraction. Simulate a fixed number of pairs and keep the fraction with the smallest distances; is then a quantile of the distances. This is the common form in practice.
- Regression adjustment. Beaumont, Zhang and Balding (2002) fit a local linear regression of on among the kept pairs and shift each kept value to , which allows a larger for the same accuracy.
- Smooth kernels. Replace the indicator in L5 by a kernel weight , giving weighted draws.
- Sequential methods. ABC sequential Monte Carlo moves a population through a falling sequence of tolerances, so proposals come from near the posterior instead of the prior. ABC with a Markov chain uses the same acceptance test inside Metropolis-Hastings.
- Scaled distances. When summaries have different scales, divide each by a robust spread, such as the median absolute deviation over prior simulations, before L5.
When to use it
Use ABC rejection when the likelihood is intractable but the model can be simulated fast: coalescent models in population genetics, epidemic models, and stochastic models of cells or ecosystems. It is the right first method when the prior is not much wider than the posterior and there are few summaries, because it is simple, parallel and gives independent draws. When the likelihood can be evaluated, use Bayesian inference with MCMC or importance sampling instead. When the acceptance rate is tiny, use ABC sequential Monte Carlo or regression adjustment. Check the result with simulation-based calibration on simulated data sets.
Pitfalls
- Raw data as the summary. Taking in L5 for continuous data has acceptance probability at and tiny acceptance otherwise, as the five-dimensional row shows. Use a few informative summaries in L5, ideally sufficient or close to it.
- Insufficient summaries. L5 with a summary that drops information gives the posterior given , which can be much wider, or biased for model choice. Choose so that it captures what the parameter changes, and test the choice on simulated data with known .
- Unscaled distances. With the Euclidean distance on summaries of very different scales, L5 effectively uses only the largest one. Scale each summary before L5.
- An improper or very wide prior. L3 needs a proper prior, and a wide one makes tiny. Use a proper prior that is as narrow as the knowledge allows, or a sequential method.
- Reporting as the posterior. With , the kept values are wider than the posterior, by percent in variance at in the table. Report , and check that the answer is stable as falls.
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/abc-rejection-sampling/. The authors are listed in prov/1PE36P.jsonl.
"""The ABC rejection algorithm (Tavare et al. 1997; Pritchard et al. 1999).
Draw theta from the prior, simulate a data set y from the model at theta, and keep
theta when the summaries S(y) lie within eps of the observed summaries s_obs.
The kept values are an exact sample from the eps-posterior
pi_eps(theta) proportional to pi(theta) P_theta(rho(S(Y), s_obs) <= eps).
With eps = 0, discrete data and a sufficient summary, that is the exact posterior.
Cost: each proposal costs one prior draw and one simulation. The expected number of
proposals per accepted value is 1 / P(rho(S(Y), s_obs) <= eps) under the prior
predictive, which grows like eps^(-q) for q continuous summaries.
"""
import random
from typing import Callable
def abc_step(
prior_draw: Callable,
simulate: Callable,
summary: Callable,
s_obs,
distance: Callable,
eps: float,
rng,
) -> tuple:
"""One proposal: returns (theta, accepted). Lines L3 to L5."""
theta = prior_draw(rng) # @line L3
y = simulate(theta, rng) # @line L4
return theta, distance(summary(y), s_obs) <= eps # @line L5
def abc_rejection(
prior_draw: Callable,
simulate: Callable,
summary: Callable,
s_obs,
distance: Callable,
eps: float,
n_accept: int,
rng: random.Random,
max_sims: int = 10**8,
) -> tuple[list, int]:
"""Run proposals until n_accept values are kept or max_sims proposals are made.
Returns (accepted values, number of proposals).
Precondition: prior_draw(rng) draws from a proper prior; simulate(theta, rng) draws a
data set from f(. | theta); distance(a, b) >= 0. The kept values are independent.
"""
accepted = [] # @line L1
sims = 0
while len(accepted) < n_accept and sims < max_sims: # @line L2
sims += 1
theta, ok = abc_step(prior_draw, simulate, summary, s_obs, distance, eps, rng)
if ok:
accepted.append(theta) # @line L6
return accepted, sims # @line L7
class ScriptedRNG:
"""A stand-in for random.Random whose randrange(k) returns scripted values.
Used to enumerate every random path of a discrete sampler with exact probabilities.
When the script runs out it raises NeedChoice(k), so the caller can branch.
"""
class NeedChoice(Exception):
def __init__(self, k: int):
super().__init__(k)
self.k = k
def __init__(self, script: list):
self.script = script
self.pos = 0
def randrange(self, k: int) -> int:
if self.pos == len(self.script):
raise ScriptedRNG.NeedChoice(k)
v = self.script[self.pos][0]
self.pos += 1
return v
def exact_accept_law(run_step: Callable) -> dict:
"""Exact law of one call run_step(rng) -> (theta, accepted) over all random paths.
run_step must use only rng.randrange. Returns {theta: P(theta and accepted)} as
Fractions; their sum is the acceptance probability. Paths are enumerated depth first.
"""
from fractions import Fraction
law: dict = {}
stack = [[]] # each script is a list of (value, range)
while stack:
script = stack.pop()
try:
theta, ok = run_step(ScriptedRNG(script))
except ScriptedRNG.NeedChoice as need:
for v in range(need.k):
stack.append(script + [(v, need.k)])
continue
if ok:
p = Fraction(1)
for _, k in script:
p /= k
law[theta] = law.get(theta, Fraction(0)) + p
return law
test_abc_rejection_sampling.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abc-rejection-sampling/. The authors are listed in prov/1PE36P.jsonl.
"""Tests for the ABC rejection algorithm.
Discrete models: every random path of one proposal is enumerated with exact Fraction
probabilities, so the law of the kept values is compared exactly with Bayes' rule.
Continuous prior: Kolmogorov-Smirnov distance to the exact beta posterior.
"""
import math
import random
import statistics
import unittest
from fractions import Fraction as F
from abc_rejection_sampling import abc_rejection, abc_step, exact_accept_law
def comb(n, k):
return math.comb(n, k)
def discrete_model(thetas, weights, den):
"""Prior on thetas (numerators of p = a/den) with integer weights; Bernoulli trials
drawn by randrange(den) < a, so every path is enumerable."""
total = sum(weights)
def prior_draw(rng):
r = rng.randrange(total)
for a, w in zip(thetas, weights):
if r < w:
return a
r -= w
raise AssertionError
def make_sim(n):
def simulate(a, rng):
return tuple(1 if rng.randrange(den) < a else 0 for _ in range(n))
return simulate
return prior_draw, make_sim
def normalize(law):
z = sum(law.values())
return {k: v / z for k, v in law.items()}, z
def hamming(a, b):
return sum(u != v for u, v in zip(a, b))
class TestExactLaw(unittest.TestCase):
def test_tolerance_zero_sufficient_summary_gives_the_posterior(self):
rng = random.Random(1)
cases = 0
while cases < 500:
den = rng.choice([2, 3, 4])
k = rng.randint(1, min(3, den - 1))
thetas = rng.sample(range(1, den), k)
weights = [rng.randint(1, 3) for _ in thetas]
n = rng.randint(1, 3)
x = tuple(rng.randint(0, 1) for _ in range(n))
s = sum(x)
prior_draw, make_sim = discrete_model(thetas, weights, den)
sim = make_sim(n)
prior = {a: F(w, sum(weights)) for a, w in zip(thetas, weights)}
lik = {a: F(a, den) ** s * (1 - F(a, den)) ** (n - s) for a in thetas}
post, _ = normalize({a: prior[a] * lik[a] for a in thetas})
# S = number of successes (sufficient), eps = 0.
law = exact_accept_law(lambda r: abc_step(prior_draw, sim, sum, s, lambda u, v: abs(u - v), 0, r))
got, acc = normalize(law)
self.assertEqual(got, post)
self.assertEqual(acc, sum(prior[a] * comb(n, s) * lik[a] for a in thetas)) # m_S(s_obs)
# S = the whole data set (also sufficient), eps = 0, Hamming distance.
law = exact_accept_law(lambda r: abc_step(prior_draw, sim, lambda y: y, x, hamming, 0, r))
got, acc = normalize(law)
self.assertEqual(got, post)
self.assertEqual(acc, sum(prior[a] * lik[a] for a in thetas)) # m(x)
# eps = 1 on the count: the eps-posterior pi(a) P_a(|S - s| <= 1).
def window(a):
p = F(a, den)
return sum(comb(n, j) * p**j * (1 - p) ** (n - j) for j in range(max(0, s - 1), min(n, s + 1) + 1))
law = exact_accept_law(lambda r: abc_step(prior_draw, sim, sum, s, lambda u, v: abs(u - v), 1, r))
got, _ = normalize(law)
self.assertEqual(got, normalize({a: prior[a] * window(a) for a in thetas})[0])
# Insufficient summary (the first trial only): the posterior given x_1 alone.
law = exact_accept_law(lambda r: abc_step(prior_draw, sim, lambda y: y[0], x[0], lambda u, v: abs(u - v), 0, r))
got, _ = normalize(law)
p1 = {a: F(a, den) if x[0] == 1 else 1 - F(a, den) for a in thetas}
self.assertEqual(got, normalize({a: prior[a] * p1[a] for a in thetas})[0])
cases += 1
def test_insufficient_summary_differs_from_the_posterior(self):
prior_draw, make_sim = discrete_model([1, 3], [1, 1], 4)
sim = make_sim(3)
x = (1, 1, 1)
full, _ = normalize(exact_accept_law(lambda r: abc_step(prior_draw, sim, sum, 3, lambda u, v: abs(u - v), 0, r)))
first, _ = normalize(exact_accept_law(lambda r: abc_step(prior_draw, sim, lambda y: y[0], 1, lambda u, v: abs(u - v), 0, r)))
self.assertEqual(full, {1: F(1, 28), 3: F(27, 28)})
self.assertEqual(first, {1: F(1, 4), 3: F(3, 4)})
def beta_cdf_int(t, a, b):
"""Beta(a, b) CDF for integer a, b: P(Binomial(a + b - 1, t) >= a)."""
m = a + b - 1
return math.fsum(comb(m, j) * t**j * (1 - t) ** (m - j) for j in range(a, m + 1))
def binomial_setup(n):
def prior_draw(rng):
return rng.random()
def simulate(p, rng):
return sum(1 for _ in range(n) if rng.random() < p)
return prior_draw, simulate
class TestContinuousPrior(unittest.TestCase):
def test_kolmogorov_smirnov_against_the_beta_posterior(self):
# Uniform prior, 3 successes in 10 trials: the posterior is Beta(4, 8).
rng = random.Random(7)
prior_draw, simulate = binomial_setup(10)
n_acc = 2000
acc, sims = abc_rejection(prior_draw, simulate, lambda y: y, 3, lambda u, v: abs(u - v), 0, n_acc, rng)
acc.sort()
d = max(max((i + 1) / n_acc - beta_cdf_int(t, 4, 8), beta_cdf_int(t, 4, 8) - i / n_acc) for i, t in enumerate(acc))
self.assertLess(d, 1.95 / math.sqrt(n_acc))
# Acceptance probability m_S(3) = 1/11.
rate = n_acc / sims
self.assertLess(abs(rate - 1 / 11), 4 * math.sqrt((1 / 11) * (10 / 11) / sims))
def test_positive_tolerance_inflates_the_variance(self):
# eps = 1: pi_eps(p) is proportional to sum_{k=2}^{4} C(10,k) p^k (1-p)^(10-k).
# Mean 1/3 (as the posterior), variance 0.021368 against 0.017094 for eps = 0.
exact_var = F(62, 468) - F(1, 9)
rng = random.Random(8)
prior_draw, simulate = binomial_setup(10)
acc, sims = abc_rejection(prior_draw, simulate, lambda y: y, 3, lambda u, v: abs(u - v), 1, 4000, rng)
self.assertLess(abs(statistics.mean(acc) - 1 / 3), 4 * math.sqrt(float(exact_var) / 4000))
self.assertLess(abs(statistics.variance(acc) - float(exact_var)), 0.0015)
self.assertGreater(statistics.variance(acc), 32 / 1872 + 0.002)
self.assertLess(abs(4000 / sims - 3 / 11), 4 * math.sqrt((3 / 11) * (8 / 11) / sims))
def test_max_sims_limits_the_work(self):
rng = random.Random(9)
prior_draw, simulate = binomial_setup(10)
acc, sims = abc_rejection(prior_draw, simulate, lambda y: y, 3, lambda u, v: abs(u - v), 0, 10**6, rng, max_sims=500)
self.assertEqual(sims, 500)
self.assertLess(len(acc), 500)
if __name__ == "__main__":
unittest.main()
History
Rubin (1984) described the procedure, draw from the prior, simulate, keep the draws whose simulated data match, as a way to explain what a posterior distribution is. Tavaré, Balding, Griffiths and Donnelly (1997) used it with an exact match on the number of segregating sites to infer coalescence times from DNA data. Pritchard, Seielstad, Perez-Lezaun and Feldman (1999) used several summary statistics with a tolerance to study the growth of human populations from Y chromosome data. Beaumont, Zhang and Balding (2002) named the approach approximate Bayesian computation and introduced regression adjustment. Sequential and Markov chain versions followed, and the method spread from population genetics to ecology, epidemiology and systems biology.
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 description of Bayes' rule as drawing a parameter from the prior, simulating data, and keeping the parameter when the simulated data match the observed data (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: rejection sampling of the coalescent with an exact match on the number of segregating sites (general locator)
- Jonathan K. Pritchard, Mark T. Seielstad, Anna Perez-Lezaun and Marcus W. Feldman, Population growth of human Y chromosomes: a study of Y chromosome microsatellites, Molecular Biology and Evolution 16(12), 1999, pages 1791 to 1798: the rejection algorithm with summary statistics and a tolerance (general locator)
- Beaumont, Zhang and Balding 2002, pages 2025 to 2035: the name approximate Bayesian computation, the analysis of the tolerance, and local linear regression adjustment (general locator)
Where this leads
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 1PE36P Edit this page History Report an error Markdown