Particle filters and sequential Monte Carlo
Multimodal or strongly non-Gaussian posteriors can be represented by weighted particles. Starting with self-normalized importance sampling for densities known up to a constant, we build sequential importance sampling, diagnose weight degeneracy with effective sample size, compare resampling schemes and implement the bootstrap filter, whose unbiased likelihood estimate combines SMC with MCMC.
After this lesson you can
- Estimate expectations under an unnormalized density with self-normalized importance sampling and quantify bias and variance.
- Derive sequential importance sampling and the recursive weight update.
- Calculate weight effective sample size and decide when to resample.
- Implement multinomial, stratified and systematic resampling and compare variance.
- Implement the bootstrap filter and apply it to robot localization and stochastic volatility.
- Explain why the particle filter likelihood estimator is unbiased and how PMMH uses it.
Before you start
A cloud to represent uncertainty
A robot receives distances to beacons and imperfect measurements of its movement. Its position is not a known point, but a conditional distribution. If the robot is transported without its odometer knowing, a cloud that only follows previous dynamics may remain far from the true position. Observe what happens when new global hypotheses are introduced.
The figure uses an explicit model: true motion follows commands and the filter adds normal noise of standard deviation 0.2 per coordinate to particles; the three distances have normal noise of standard deviation 0.35. After each measurement it resamples systematically and, if requested, replaces a fraction with uniform positions. That injection changes the inferred model: it is a recovery strategy, not an exact Bayesian update under the original dynamics. Map boundaries also clip simulated positions.
The Kalman filter represents belief with a Gaussian and is exact for the linear Gaussian model. The EKF linearizes a nonlinear observation, but a single Gaussian cannot describe two separated modes. A weighted cloud can retain them, provided the proposal visits both.
Here the prior is and . The particle line uses 1200 prior samples with fixed seed, weighted by likelihood, and a Gaussian kernel of width 0.18. EKF differentiates at the prior mean, whose sign decides the mode it approaches. At zero the derivative does not exist, so no EKF is defined without an additional convention.
Self-normalized importance sampling
Let be a density known up to its constant , and a proposal covering the support of . For define . By change of measure, and . The self-normalized importance estimate is
If and relevant expectations are finite, the strong law applied to numerator and denominator yields almost sure convergence of to . The ratio is generally biased at finite even if is unbiased. With finite second moments and usual delta-method assumptions,
Variance also depends on , not only weights. A proposal ideal for one function may be poor for another. In finite arithmetic calculate , subtract before exponentiating and normalize. This is the same reason for working in log space as in the forward algorithm.
To see the variance’s origin, write and . Around , the differential of is . The linear term is therefore the mean of , which has zero expectation. Its variance yields the expression above via the central limit theorem. A second-order expansion, when moments and tail control justify taking expectations of the remainder, gives leading bias
Bias is not necessarily negative: it depends on correlation between weight and function. Required moments may also be infinite if has tails that are too light. Then neither the variance formula nor accuracy of order is justified, even if the estimate appears stable in one run.
If all weights are equal, ESS is ; if only one is positive, it is 1. Do not confuse this definition with the autocorrelation-based ESS of a Markov chain. A large ESS also does not detect a mode the proposal never visited.
The upper bound follows from Cauchy: , and the lower from . For example, four equal weights have ESS 4, whereas has ESS 1. If the threshold is , resampling occurs when concentration crosses that practical criterion, not because is a universal mathematical boundary.
Sequential importance and genealogy
State evolves according to and produces observed datum with density . For the full trajectory, the proposal factors into . The ratio between joint target density and proposal gives the sequential importance sampling update:
For the transition is replaced with the initial prior. The proposal must be positive where the numerator is positive. As ratios multiply, weights often concentrate and few useful trajectories remain. This is not a universal law for every model: if proposal and target coincide exactly, all weights can remain equal.
The recursive ratio follows by dividing the joint trajectory density by the proposal and canceling the previous ratio. SIS therefore need not recalculate the whole past probability. But storing full trajectories needs more memory and, when an ancestor is copied, several paths share its past. Even with uniform current weights, that genealogy limits what can be learned about old states.
The figure’s model is , , and , . The prior is and the series is simulated with a fixed seed. Weights are shown after resampling when ESS falls below half of 150 particles. Simulations with and without resampling use the same observation series, but not the same future particles.
Resampling does not create information
Resampling replaces particles by copies, with expected count for particle . Multinomial resampling takes independent indices from the categorical distribution. Stratified resampling takes a uniform draw in each interval ; systematic uses one initial uniform and an equally spaced grid. Residual resampling first assigns copies and distributes the remainder according to normalized residuals.
The figure defines four weights as . The three methods preserve expected copy count, but their dependencies differ. Multinomial count variance is exactly . Systematic resampling does not universally dominate stratified for every function and ordering: comparing individual counts does not prove an ordering of every estimate. Resampling even with uniform weights can introduce unnecessary duplicates, particularly with the multinomial method.
With , the first particle has weight 0.5 and thus expects two of four copies. In systematic and stratified resampling that particle’s interval occupies exactly two full strata, so it gets two copies every repetition. In multinomial resampling its count follows a binomial with variance 1. Bars are Monte Carlo estimates of those variances, so the multinomial bar need not equal exactly 1.
Bootstrap filter and likelihood
The bootstrap filter uses the transition as proposal, . By cancellation, the increment is simply . Propagate, weight, calculate ESS and resample if it falls below a threshold. A filter with very precise observations may propose particles far from the data and retain only a few with appreciable weight. A locally optimal proposal incorporates the data and minimizes conditional variance of incremental weight, but can be hard to sample or normalize.
The constant normalizing that proposal is the conditional predictive . Substituting it into the importance ratio makes the increment independent of new sample and equal to that predictive. For a fixed ancestor its conditional variance is zero, the minimum possible. Increments can still vary among ancestors, so “optimal” does not mean absence of global degeneracy. Auxiliary models can select ancestors taking the datum’s predictive probability into account too.
At each step there are two different distributions. The predictive propagates the previous belief; the filtered multiplies it by and normalizes. The filtered distribution answers where the state is now using only available data. The smoothed for incorporates future observations and requires another calculation. Following ancestors is one possible approximation, but repeated resampling makes many paths share distant ancestors. Current weight ESS does not measure that problem; the genealogy figure counts initial ancestors precisely to distinguish them.
With resampling at every step, the particle likelihood estimator is the product of mean incremental likelihoods. With adaptive resampling it is also the product of incremental means, retaining previous normalized weights when not resampling. It is nonnegative and unbiased for under conditionally unbiased offspring resampling and integrability conditions. Its logarithm is generally not unbiased: Jensen gives when the logarithm is integrable.
To understand unbiasedness, multiply the normalized empirical measure by the accumulated evidence estimator. Resampling preserves its conditional expectation; propagation and weighting apply kernel . By induction, the expectation of that unnormalized measure matches the joint measure of . Evaluating it at the constant function 1 gives evidence. This proof does not claim each random factor is separately unbiased or independent.
Specifically, denote and . Conditional on the previous system, both no resampling and resampling with expected counts give . The initial case is the integral of the prior times the first likelihood. Iterated expectation completes the induction. For adaptive resampling, the decision must be measurable with respect to information available before selecting ancestors.
In PMMH a new parameter is proposed and an independent likelihood estimate obtained. The Metropolis ratio uses that nonnegative estimate, prior and proposal. On rejection the previous estimate is also retained; recalculating it would change the algorithm. The exact result is the marginal posterior in an augmented space under the method’s assumptions, not a guarantee of fast mixing. See the original work of Andrieu, Doucet and Holenstein.
If is the proposal and the new estimate, acceptance probability is the minimum of 1 and
An especially high noisy estimate can cause the chain to stick for a long time. Increasing particles costs more per iteration and normally reduces noise, but the optimal budget depends on the problem. The following comparison measures that variation in one example, not a universal particle count.
Lab: stochastic volatility
Generate a synthetic series with , and , for . Data are simulated, not real returns. Cells share state and run in order. The following implementation retains the previous weight when it does not resample and accumulates likelihood in log space.
import numpy as np
from scipy.special import logsumexp
def systematic(weights, rng):
n = len(weights)
cdf = np.cumsum(weights)
cdf[-1] = 1.0
return np.searchsorted(cdf, (rng.random() + np.arange(n)) / n, side="right")
def sv_filter(y, phi, sigma, n, rng, threshold=0.5):
h = rng.normal(0, sigma / np.sqrt(1 - phi**2), n)
logw = np.full(n, -np.log(n))
logz = 0.0
means = []
for t, obs in enumerate(y):
if t:
h = phi * h + sigma * rng.normal(size=n)
logg = -0.5 * (np.log(2 * np.pi) + h + obs**2 * np.exp(-h))
loginc = logsumexp(logw + logg)
logz += loginc
logw += logg - loginc
w = np.exp(logw)
means.append(np.dot(w, h))
if 1 / np.sum(w**2) < threshold * n:
h = h[systematic(w, rng)]
logw = np.full(n, -np.log(n))
return logz, np.asarray(means)
rng_data = np.random.default_rng(44)
phi_true, sigma = 0.9, 0.3
h = np.empty(30)
h[0] = rng_data.normal(0, sigma / np.sqrt(1 - phi_true**2))
for t in range(1, len(h)):
h[t] = phi_true * h[t-1] + sigma * rng_data.normal()
y = np.exp(h / 2) * rng_data.normal(size=len(h))
for n in (100, 500, 2000):
estimates = [sv_filter(y, phi_true, sigma, n, np.random.default_rng(s))[0] for s in range(20)]
print("N", n, "media log Z", round(np.mean(estimates), 3), "varianza log Z", round(np.var(estimates, ddof=1), 4))The comparison repeats filtering on the same series, varying only Monte Carlo seeds. Twenty repetitions describe this run, not prove monotonicity or precisely quantify a small variance. To estimate persistence, the following PMMH uses a uniform prior on and a symmetric normal proposal. At the boundary it rejects the proposal; it retains the previous estimate when rejecting.
def pmmh(y, sigma, n, steps, rng):
phi = 0.5
ll, _ = sv_filter(y, phi, sigma, n, rng)
chain, accepted = [], 0
for _ in range(steps):
candidate = phi + rng.normal(0, 0.08)
if abs(candidate) < 0.99:
proposed_ll, _ = sv_filter(y, candidate, sigma, n, rng)
if np.log(rng.random()) < proposed_ll - ll:
phi, ll = candidate, proposed_ll
accepted += 1
chain.append(phi)
return np.asarray(chain), accepted / steps
chain, rate = pmmh(y, sigma, 300, 250, np.random.default_rng(90))
print("aceptación", round(rate, 3), "media segunda mitad", round(chain[125:].mean(), 3))This short chain checks the workflow, not posterior convergence or accuracy. For a real analysis increase iterations, run multiple chains, check traces and diagnostics, and explore sensitivity to prior and particle count. True persistence in the simulation need not equal the posterior mean of a finite series.
Lab: comparison with Kalman
For , and , Kalman gives an exact reference. Compare mean squared error of the final filtered mean across independent seeds. The rate is an asymptotic statement under assumptions, not a guarantee that every pair of sizes improves in any finite experiment.
rg = np.random.default_rng(3)
x, observations = 0.0, []
for t in range(12):
x = rg.normal() if t == 0 else 0.8*x + rg.normal(0, 0.5)
observations.append(x + rg.normal(0, 0.7))
m, v = 0.0, 1.0
for t, obs in enumerate(observations):
if t:
m, v = 0.8*m, 0.8**2*v + 0.5**2
k = v / (v + 0.7**2)
m, v = m + k*(obs-m), (1-k)*v
def linear_filter(n, seed):
r = np.random.default_rng(seed)
p = r.normal(size=n)
w = np.full(n, 1/n)
for t, obs in enumerate(observations):
if t:
p = 0.8*p + r.normal(0, 0.5, n)
lw = np.log(w) - 0.5*((obs-p)/0.7)**2
w = np.exp(lw-logsumexp(lw))
estimate = np.dot(w, p)
if 1/np.sum(w*w) < n/2:
p = p[systematic(w, r)]
w = np.full(n, 1/n)
return estimate
print("media exacta", round(m, 4))
for n in (100, 400, 1600):
errors = np.array([linear_filter(n, s)-m for s in range(40)])
print("N", n, "RMSE", round(np.sqrt(np.mean(errors**2)), 4))Here Kalman costs less and has no Monte Carlo error. Particles justify the cost when non-Gaussian shape, constraints or nonlinearity matter and a proposal can cover the posterior. An EKF can be cheap and useful, but its linearization does not ensure retention of all modes.
The comparison fixes one observation sequence and repeats the algorithm, so estimated RMSE measures Monte Carlo variability and bias against that sequence’s exact filtered mean. It does not measure prediction error against the true state or average over all possible sequences. To study that second objective, generate many sequences, run both filters on each and separate data uncertainty from algorithm uncertainty. The relation among the cell’s three RMSE values is an empirical check of this run, not a proof of the general rate.
Local lab: particles library
The particles documentation defines the same model and provides a bootstrap filter. Install particles locally before running. NumPy and Generator seeds follow different streams, so compare distributions of estimates, not step-by-step equality. The clock measures this machine and load, not a universal library property.
import time
import numpy as np
from scipy.special import logsumexp
import particles
from particles import state_space_models as ssm
# El runtime local es independiente del navegador: reconstruye datos y filtro.
phi_true, sigma = 0.9, 0.3
rng_data = np.random.default_rng(44)
h = np.empty(30)
h[0] = rng_data.normal(0, sigma / np.sqrt(1-phi_true**2))
for t in range(1, len(h)):
h[t] = phi_true*h[t-1] + sigma*rng_data.normal()
y = np.exp(h/2) * rng_data.normal(size=len(h))
def sv_local(y, phi, sigma, n, rng):
h = rng.normal(0, sigma/np.sqrt(1-phi**2), n)
logw = np.full(n, -np.log(n))
logz = 0.0
for t, obs in enumerate(y):
if t:
h = phi*h + sigma*rng.normal(size=n)
lg = -0.5*(np.log(2*np.pi) + h + obs**2*np.exp(-h))
inc = logsumexp(logw+lg)
logz += inc
logw += lg-inc
w = np.exp(logw)
if 1/np.sum(w*w) < n/2:
cdf = np.cumsum(w)
cdf[-1] = 1.0
h = h[np.searchsorted(cdf, (rng.random()+np.arange(n))/n, side='right')]
logw = np.full(n, -np.log(n))
return logz
model = ssm.StochVol(mu=0.0, rho=phi_true, sigma=sigma)
fk = ssm.Bootstrap(ssm=model, data=y)
own, lib = [], []
start = time.perf_counter()
for seed in range(20):
own.append(sv_local(y, phi_true, sigma, 500, np.random.default_rng(seed)))
own_time = time.perf_counter() - start
start = time.perf_counter()
for seed in range(20):
np.random.seed(seed)
pf = particles.SMC(fk=fk, N=500, resampling='systematic', ESSrmin=0.5)
pf.run()
lib.append(pf.logLt)
lib_time = time.perf_counter() - start
print("propio: media, desviación", np.mean(own), np.std(own, ddof=1))
print("particles: media, desviación", np.mean(lib), np.std(lib, ddof=1))
print("tiempos relativos propio/biblioteca", own_time / lib_time)npm run lab and open the connection link.Exercises
Step 1 of 3. Which resampling property is needed?
systematic_resample(weights, u) in O(N) time. Weights are nonnegative and sum to one; u lies in [0,1). Return indices of the N positions , with index zero for the first particle.def systematic_resample(weights, u):
passsnis(log_target, sample_proposal, log_proposal, f, N). Functions operate on arrays; sample_proposal(N) returns samples. Return estimate, ESS and estimate of the normalization constant. Assume positive finite weights and a constant representable in floating point.def snis(log_target, sample_proposal, log_proposal, f, N):
passSummary
- Self-normalized importance sampling is a ratio normally biased at finite size. ESS measures concentration, not mode coverage.
- SIS accumulates importance ratios; bootstrap uses the transition and weights by observation. Precise data may require a guided proposal.
- Resampling stabilizes weights and reduces genealogical diversity. Estimated evidence on the linear scale is unbiased under the stated conditions; PMMH retains the previous estimate on rejection.
- Compare particles with Kalman when an exact reference exists, and distinguish a short check from a convergence study.