Algorithmresearch
ABC sequential Monte Carlo
Also called ABC-SMC, ABC population Monte Carlo.
Runs ABC over a falling sequence of tolerances, moving and reweighting a population of particles, so far fewer simulations are wasted than in rejection ABC.
- Time
- Θ(T (N^2 + N C / A)) expected
- Space
- Θ(N) extra
- Where
- A = the smallest acceptance rate over the generations; C = the cost of one simulation; N = the number of particles; T = the number of generations
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark A. Beaumont, Jean Marie Cornuet, Jean Michel Marin, Christian P. Robert, Scott A. Sisson, Tina Toni, 2009
ABC sequential Monte Carlo runs approximate Bayesian computation on a population of particles through a falling sequence of tolerances . The first generation is the ABC rejection algorithm at a loose tolerance. Each later generation draws a particle from the previous one, moves it by a random kernel, simulates data, and keeps the moved particle when the summaries are within the new tolerance. Proposals then come from near the current approximate posterior instead of from the prior, so far fewer simulations are wasted. The moved particles do not follow the prior any more, so each gets the importance weight of Beaumont, Cornuet, Marin and Robert (2009). With these weights, the population of generation targets the -posterior for any previous population.
In plain words
Searching for the settings of a simulator that reproduce the real data, ABC rejection guesses blindly from the prior every time, so a strict match is rare. This method starts with a loose match, which is easy, and keeps a crowd of settings that pass it. Then it tightens the match step by step. At each step it picks a setting from the crowd, nudges it a little, and tests the nudged setting against the stricter match. Most guesses now land in a good region, so fewer simulations are wasted. The crowd was built by nudging, not by guessing from the prior, so some regions are now visited too often. Each setting therefore gets a weight that undoes this. Without the weights, the answer is too narrow.
The problem
Input. A proper prior density that can be sampled and evaluated; a simulator for ; the observed summaries , a distance , and tolerances ; the number of particles.
Output. Particles with weights whose weighted mean of any function estimates the mean of under the -posterior .
The algorithm
ABC-SMC(π, simulator, S, s_obs, ρ, ε₁ ≥ … ≥ ε_T, N)- 1
run ABC rejection at ε₁ to get θ₁..θ_N; Wⱼ ← 1/N - 2
s² ← 2 · (weighted variance of θ₁..θ_N under W) ▷ the kernel K(·|θ') = N(θ', s²) - 3
for t ← 2 to T - 4
for i ← 1 to N - 5
repeat - 6
pick j with probability Wⱼ; θ* ← θⱼ + N(0, s²) - 7
if π(θ*) > 0 then Y ← a data set simulated from f(· | θ*) - 8
until π(θ*) > 0 and ρ(S(Y), s_obs) ≤ ε_t - 9
θᵢ' ← θ*; wᵢ ← π(θ*) / Σⱼ Wⱼ K(θ* | θⱼ) - 10
θ ← θ'; W ← w / Σᵢ wᵢ; recompute s² as in L2 - 11
return θ₁..θ_N and W₁..W_N
L1 is ABC rejection with a loose tolerance, which accepts often. L2 sets the kernel variance to twice the weighted variance of the population, the choice of Beaumont et al. (2009): wide enough to explore, narrow enough to accept often. L6 draws from the mixture of kernels centred at the particles. L7 skips the simulation when the prior is zero, for example outside for a probability. L8 is the ABC test at the new tolerance. L9 is the importance sampling weight: target , proposal , and the unknown acceptance probability cancels. L9 costs kernel evaluations per particle. L10 normalizes the weights and updates the kernel. The effective sample size of the weights, , measures how much the weights vary.
Example
Trace with four particles. successes in Bernoulli trials, uniform prior on , = the number of successes, , tolerances , random.Random(8). Generation 1 (L1) needs simulations and keeps with equal weights. L2 gives . Generation 2 needs simulations:
| new particle | 0.2985 | 0.3659 | 0.3708 | 0.1851 |
|---|---|---|---|---|
| normalized weight | 0.1722 | 0.3075 | 0.3247 | 0.1956 |
The three old particles near make the kernel mixture large there. New particles far from that cluster, at and , have small and get large weights; , close to the cluster, gets the smallest weight.
A full run. Same model, , tolerances , random.Random(2). The last tolerance is and the summary is sufficient, so the target is the exact posterior Beta(7, 15), with mean and variance .
| generation | kernel | simulations | acceptance | ESS | weighted mean | weighted variance | |
|---|---|---|---|---|---|---|---|
| 1 | 6 | 820 | 0.610 | 500 | 0.3171 | 0.038169 | |
| 2 | 3 | 0.276 | 1161 | 0.431 | 495 | 0.3209 | 0.018306 |
| 3 | 1 | 0.191 | 2186 | 0.229 | 493 | 0.3168 | 0.009867 |
| 4 | 0 | 0.140 | 5071 | 0.099 | 476 | 0.3196 | 0.009897 |
The run uses simulations in total. ABC rejection at keeps one proposal in here, so draws cost about simulations. The gain is small in this problem because the uniform prior is not much wider than the posterior. With successes in trials and tolerances , ten runs with use simulations on average, against for rejection.
Dropping the weights. Replace in L9 by . Over ten runs each, the mean of the final weighted variance is with the weights and without them, against the exact : without the weights the answer is percent too narrow. With trials it is with the weights, without, and exact.
Correctness
The full proof is in proofs/correctness.md. It proves:
- Generation 1 follows the -posterior, by the proof for ABC rejection.
- The proposal law. Given the previous population, the kept particles of generation are independent with density proportional to .
- The weight identity. With , for every integrable , whatever the previous population is. The key invariant: at every generation, the weighted population is an importance sample for .
- Consistency of the weighted mean for a fixed previous population as the number of new particles grows, by the law of large numbers.
- Equal weights are wrong. Without L9 the population targets , whose ratio to is proportional to .
What is proved and what is measured: items 1 to 5 are exact. The behaviour of all generations together as grows, and the error at a fixed , are not proved on this page; the tables measure them against the exact posterior. The tests check item 3 in rational arithmetic on random finite models, and the weighted distribution of the final population against Beta(7, 15) with a Kolmogorov-Smirnov bound of . That bound is a working tolerance, since weighted samples do not follow the usual Kolmogorov-Smirnov law.
Proof: The importance weights of ABC sequential Monte Carlofull
Setting. is a prior density on . For a tolerance , write and let
be the -posterior. The tolerances are . At generation the previous population is a fixed set of particles with weights , , and is a transition density, for example the normal density with mean and variance . The mixture
is the density of a proposal on lines L6 and L7.
Claim 1: generation 1
The particles of generation 1 are independent draws from , with equal weights.
Proof. Line L1 is the ABC rejection algorithm at tolerance ; the law of its kept values is , with independence, by Claim 1 of the proof on the ABC rejection algorithm page.
Claim 2: the law of an accepted proposal
Given the previous population, the new particles of generation are independent with density
provided .
Proof. One attempt on lines L6 to L8 draws with probability and then , so has density . It is kept with probability , using fresh simulations. As in rejection sampling, for a set , , so a kept value has density . Attempts are independent given the previous population, so the kept values are independent and identically distributed.
Claim 3: the weights correct the proposal exactly
Assume wherever (true for a normal kernel). Let , the weight of line L9. Then for every function with ,
This holds for every previous population: the particles and weights need not be correct.
Proof. Where ,
and where both sides are . So and . Divide.
The unknown acceptance probability appears in both the target and the proposal law and cancels, so the weight needs only and . This is the weight of Beaumont, Cornuet, Marin and Robert (2009).
Claim 4: consistency for a fixed previous population
Fix the previous population and draw new particles. With normalized weights and a function with , almost surely as .
Proof. By Claim 2 the are independent with density . and , so the strong law of large numbers applies to the numerator and to the denominator . The ratio converges to the ratio of the limits, which is by Claim 3.
Claim 5: equal weights target the wrong law
If line L9 is replaced by , the weighted population of generation targets , not , and
Proof. The first statement is Claim 2 with all weights equal, and the ratio is the display in the proof of Claim 3.
Since is concentrated where the previous particles are, puts too much mass near the centre of the previous population and too little in the tails. With a uniform prior, is the product of and a bump, which is narrower than .
What is proved and what is measured
Claims 1 to 5 are exact. Claim 4 is a limit in the number of particles of one generation, with the previous population held fixed; the joint behaviour of all generations as grows, and the size of the error at a fixed , are not proved here. The page measures them against the exact posterior of a binomial model. The tests check Claim 3 in rational arithmetic on random finite models.
Complexity
Generation needs about simulations of cost , where is its acceptance rate, and kernel evaluations for the weights on L9. Over generations the expected time is with the smallest rate. When simulations are expensive, the simulations dominate; for cheap simulators and large , the term does, and a kernel density approximation of removes it. The population takes space.
Properties
- Not exact. It targets the -posterior, and the weighted estimates have a bias of order , like every self-normalized importance sampling estimate.
- Valid for any kernel. The weight identity holds for every kernel with on the support of the target. The kernel affects only efficiency.
- Parallel within a generation. The particles of one generation are independent given the previous population.
- Weight degeneracy. If the kernel is too wide or too narrow, a few weights dominate, which the effective sample size shows.
- Gives the intermediate posteriors. Each generation is an estimate of , so one run shows how the answer changes as the tolerance falls.
Variants and improvements
- Adaptive tolerances. Choose as a quantile of the distances of the previous generation, or, as in Del Moral, Doucet and Jasra (2012), so that the effective sample size falls by a fixed fraction. Stop when the acceptance rate becomes too small.
- MCMC moves. Del Moral, Doucet and Jasra (2012) resample the population and move each particle by an ABC Metropolis-Hastings step, which needs no weight and keeps the population at the target.
- Local kernels. Use a covariance estimated from the nearest particles, or an optimal local covariance, in place of the single of L2.
- Model choice. Toni and coauthors (2009) add a model index to the particle and run the same scheme to estimate posterior model probabilities, which are valid only with summaries sufficient for the model index.
- Regression adjustment of the final population, as for ABC rejection.
When to use it
Use ABC-SMC when the likelihood is intractable, simulations are costly, and the prior is much wider than the posterior, so that ABC rejection would waste most simulations. It is the standard ABC sampler in systems biology and epidemiology. For cheap simulators and a narrow prior, plain ABC rejection is simpler and gives independent draws. When the likelihood can be evaluated, use sequential Monte Carlo or MCMC on the true posterior. Check the calibration with simulation-based calibration.
Pitfalls
- Missing or wrong weights. Setting on L9 because "the ABC test already selects the right particles" gives a population that is too narrow, by percent in variance in the example. Keep , and recompute the mixture with the previous weights, not the new ones.
- A kernel that is too small. A tiny on L6 gives high acceptance but leaves the population stuck where it started, and the weights then degenerate. Use the rule of L2 or an adaptive kernel, and watch the effective sample size.
- Falling too fast. Jumping from a loose to a strict tolerance in L3 makes the acceptance rate on L8 tiny, like plain rejection. Lower gradually, for example by a quantile rule.
- Forgetting the prior support. If L7 simulates at outside the support, the simulator may fail or return nonsense. Test first, as L7 does.
- Treating the result as the posterior. With or an insufficient summary, the population targets given , not . Report and the summaries.
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-sequential-monte-carlo/. The authors are listed in prov/HY1FY8.jsonl.
"""ABC sequential Monte Carlo, in the population Monte Carlo form of Beaumont, Cornuet,
Marin and Robert (2009), for a scalar parameter.
Generation 1 is ABC rejection at tolerance eps_1. Generation t >= 2 proposes
theta* = theta_j + N(0, s^2) with j drawn from the previous weights, keeps theta* when its
simulated summary is within eps_t, and gives it the importance weight
w = pi(theta*) / sum_j W_j K(theta* | theta_j).
The weighted population targets the eps_t-posterior pi(theta) P_theta(rho <= eps_t), for
any previous population, because the acceptance probability appears in both the target
and the proposal and cancels.
Cost per generation: N / A simulations for acceptance rate A, plus N^2 kernel
evaluations for the weights.
"""
import math
import random
from typing import Callable, Sequence
def normal_pdf(z: float, s: float) -> float:
return math.exp(-0.5 * (z / s) ** 2) / (s * math.sqrt(2 * math.pi))
def weighted_variance(xs: Sequence[float], ws: Sequence[float]) -> float:
m = math.fsum(w * x for x, w in zip(xs, ws))
return math.fsum(w * (x - m) ** 2 for x, w in zip(xs, ws))
def smc_weight(theta, prior_pdf: Callable, prev: Sequence, prev_w: Sequence, kernel_pdf: Callable):
"""The importance weight pi(theta) / sum_j W_j K(theta | theta_j) (line L9).
Works with floats or with Fractions (for the exact tests).
"""
g = sum(w * kernel_pdf(theta, p) for p, w in zip(prev, prev_w))
return prior_pdf(theta) / g
def abc_smc(
prior_draw: Callable,
prior_pdf: Callable,
simulate: Callable,
summary: Callable,
s_obs,
distance: Callable,
eps_schedule: Sequence[float],
n: int,
rng: random.Random,
equal_weights: bool = False,
) -> dict:
"""Run ABC-SMC. Returns the final particles, normalized weights, the kernel scales,
the number of simulations per generation, and the effective sample sizes.
Precondition: eps_schedule is non-increasing; prior_pdf(theta) > 0 exactly where the
prior has mass. equal_weights=True drops the importance weights (a wrong variant,
kept for the tests and the page).
"""
sims = []
parts = []
count = 0
while len(parts) < n: # @line L1
count += 1
th = prior_draw(rng)
if distance(summary(simulate(th, rng)), s_obs) <= eps_schedule[0]:
parts.append(th)
sims.append(count)
weights = [1.0 / n] * n
scales = []
for eps in eps_schedule[1:]: # @line L3
s = math.sqrt(2 * weighted_variance(parts, weights)) # @line L2
s = max(s, 1e-12)
scales.append(s)
cum = []
acc = 0.0
for w in weights:
acc += w
cum.append(acc)
new_parts, new_w = [], []
count = 0
for _ in range(n): # @line L4
while True: # @line L5
j = min(_bisect(cum, rng.random() * acc), n - 1) # @line L6
th = parts[j] + rng.gauss(0.0, s)
if prior_pdf(th) <= 0: # @line L8
continue
count += 1 # count simulations only
y = simulate(th, rng) # @line L7
if distance(summary(y), s_obs) <= eps:
break
new_parts.append(th)
if equal_weights:
new_w.append(1.0)
else:
new_w.append(smc_weight(th, prior_pdf, parts, weights, lambda a, b: normal_pdf(a - b, s))) # @line L9
tot = math.fsum(new_w)
parts, weights = new_parts, [w / tot for w in new_w] # @line L10
sims.append(count)
return { # @line L11
"particles": parts,
"weights": weights,
"scales": scales,
"sims": sims,
"ess": 1.0 / math.fsum(w * w for w in weights),
}
def _bisect(cum: Sequence[float], u: float) -> int:
lo, hi = 0, len(cum)
while lo < hi:
mid = (lo + hi) // 2
if cum[mid] <= u:
lo = mid + 1
else:
hi = mid
return lo
test_abc_sequential_monte_carlo.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abc-sequential-monte-carlo/. The authors are listed in prov/HY1FY8.jsonl.
"""Tests for ABC-SMC: the weight identity in exact arithmetic, and the final population
against the exact beta posterior of a binomial model."""
import math
import random
import unittest
from fractions import Fraction as F
from abc_sequential_monte_carlo import abc_smc, smc_weight, weighted_variance
def beta_cdf_int(t, a, b):
m = a + b - 1
return math.fsum(math.comb(m, j) * t**j * (1 - t) ** (m - j) for j in range(a, m + 1))
class TestWeightIdentity(unittest.TestCase):
def test_weights_correct_any_previous_population_exactly(self):
# Finite parameter set {0..k-1}. Accepted proposals have law q ~ g * a, with
# g = sum_j W_j K(. | theta_j). Weighting by pi / g must give the eps-posterior
# pi * a / (sum pi a) exactly, whatever the previous population is.
rng = random.Random(1)
for _ in range(500):
k = rng.randint(1, 6)
prior = [F(rng.randint(1, 5)) for _ in range(k)]
prior = [p / sum(prior) for p in prior]
a = [F(rng.randint(0, 6), 6) for _ in range(k)]
if sum(p * x for p, x in zip(prior, a)) == 0:
continue
rows = [[F(rng.randint(1, 4)) for _ in range(k)] for _ in range(k)]
kern = [[v / sum(r) for v in r] for r in rows] # kern[old][new], all positive
def kernel_pdf(new, old):
return kern[old][new]
m = rng.randint(1, 5)
prev = [rng.randrange(k) for _ in range(m)]
pw = [F(rng.randint(1, 5)) for _ in range(m)]
pw = [w / sum(pw) for w in pw]
g = [sum(w * kernel_pdf(t, p) for p, w in zip(prev, pw)) for t in range(k)]
q = [g[t] * a[t] for t in range(k)]
w = [smc_weight(t, lambda u: prior[u], prev, pw, kernel_pdf) for t in range(k)]
h = [F(rng.randint(-5, 5)) for _ in range(k)]
lhs = sum(q[t] * w[t] * h[t] for t in range(k)) / sum(q[t] * w[t] for t in range(k))
rhs = sum(prior[t] * a[t] * h[t] for t in range(k)) / sum(prior[t] * a[t] for t in range(k))
self.assertEqual(lhs, rhs)
def test_weighted_variance(self):
self.assertAlmostEqual(weighted_variance([0.0, 1.0], [0.5, 0.5]), 0.25)
def binomial(n):
def prior_draw(rng):
return rng.random()
def prior_pdf(t):
return 1.0 if 0.0 < t < 1.0 else 0.0
def simulate(p, rng):
return sum(1 for _ in range(n) if rng.random() < p)
return prior_draw, prior_pdf, simulate
def wstats(res):
xs, ws = res["particles"], res["weights"]
m = math.fsum(w * x for x, w in zip(xs, ws))
return m, weighted_variance(xs, ws)
class TestBinomial(unittest.TestCase):
def setUp(self):
# 6 successes in 20 trials, uniform prior: the posterior is Beta(7, 15).
self.n, self.x = 20, 6
self.mean, self.var = 7 / 22, 7 * 15 / (22**2 * 23)
def test_final_population_matches_the_exact_posterior(self):
pd, pp, sim = binomial(self.n)
res = abc_smc(pd, pp, sim, lambda y: y, self.x, lambda u, v: abs(u - v), (6, 3, 1, 0), 500, random.Random(2))
m, v = wstats(res)
ess = res["ess"]
self.assertGreater(ess, 400)
self.assertLess(abs(m - self.mean), 4 * math.sqrt(self.var / ess))
self.assertLess(abs(v / self.var - 1), 0.2)
order = sorted(zip(res["particles"], res["weights"]))
cdf, d = 0.0, 0.0
for t, w in order:
f = beta_cdf_int(t, 7, 15)
d = max(d, abs(cdf - f), abs(cdf + w - f))
cdf += w
self.assertLess(d, 2.5 / math.sqrt(ess))
# Fewer simulations than rejection ABC with eps = 0 (21 per kept value).
self.assertLess(sum(res["sims"]), 500 * 21)
def test_dropping_the_weights_gives_too_narrow_an_answer(self):
pd, pp, sim = binomial(self.n)
res = abc_smc(pd, pp, sim, lambda y: y, self.x, lambda u, v: abs(u - v), (6, 3, 1, 0), 500, random.Random(3), equal_weights=True)
_, v = wstats(res)
self.assertLess(v / self.var, 0.88)
if __name__ == "__main__":
unittest.main()
History
Sisson, Fan and Tanaka (2007) proposed the first sequential ABC sampler, based on partial rejection control. Beaumont, Cornuet, Marin and Robert (2009) showed that its weights give a biased answer, and gave the population Monte Carlo version with the weights of L9 and a kernel variance of twice the previous variance. Sisson and coauthors published a correction in 2009. Toni and coauthors (2009) proposed the same weighted scheme for parameter inference and model selection in dynamical systems, which made it popular in systems biology. Del Moral, Doucet and Jasra (2012) placed ABC in the framework of sequential Monte Carlo samplers, with adaptive tolerances and MCMC moves.
References
- Mark A. Beaumont, Jean-Marie Cornuet, Jean-Michel Marin and Christian P. Robert, Adaptive approximate Bayesian computation, Biometrika 96(4), 2009, pages 983 to 990: the ABC population Monte Carlo algorithm, its importance weights, the kernel variance equal to twice the weighted variance of the previous population, and the bias of the earlier partial rejection control weights (general locator)
- Scott A. Sisson, Yanan Fan and Mark M. Tanaka, Sequential Monte Carlo without likelihoods, Proceedings of the National Academy of Sciences 104(6), 2007, pages 1760 to 1765: the first sequential ABC sampler (ABC partial rejection control); see the correction, doi:10.1073/pnas.0908847106, 2009 (general locator)
- Tina Toni, David Welch, Natalja Strelkowa, Andreas Ipsen and Michael P. H. Stumpf, Approximate Bayesian computation scheme for parameter inference and model selection in dynamical systems, Journal of the Royal Society Interface 6(31), 2009, pages 187 to 202: ABC-SMC with importance weights, and its use for model selection (general locator)
- Pierre Del Moral, Arnaud Doucet and Ajay Jasra, An adaptive sequential Monte Carlo method for approximate Bayesian computation, Statistics and Computing 22(5), 2012, pages 1009 to 1020: tolerances chosen adaptively from the effective sample size, with MCMC moves (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 HY1FY8 Edit this page History Report an error Markdown