AI Wiki中文/EN

Particle filters: tracking a belief with weighted samples

粒子滤波

Represent a Bayes filter's belief by weighted random samples, derive sequential importance sampling and the bootstrap filter, see why weights degenerate and what resampling fixes and breaks, and compare a bootstrap filter with an EKF on Gordon, Salmond and Smith's scalar benchmark.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A cloud of guesses instead of a formula

A particle filter tracks a hidden quantity, such as a robot’s position, by keeping many random guesses called particles. Each guess gets a weight that says how well it explains the latest measurement; good guesses are copied and bad ones are dropped. It is useful when the uncertainty has a shape that one bell curve cannot describe. An example is a sensor that cannot tell whether a target is to the left or to the right.

The state estimation article derived the Bayes filter: predict the state with a motion model, then correct the prediction with the new measurement. That repeating predict-and-correct loop is exact on paper. In practice the belief, the probability distribution over the state, must be stored in some form. For linear models with Gaussian noise the belief stays Gaussian, and the Kalman filter computes it exactly. For nonlinear or non-Gaussian problems there is in general no exact formula. The usual workaround, the extended Kalman filter (EKF), squeezes the belief into one Gaussian, which can badly distort it and cause the filter to drift off track (diverge). Motivation

In 1993 Gordon, Salmond and Smith proposed a simpler route. Store the belief as a set of random samples instead of a function. Move every sample through the motion model. Then weight the samples by the new measurement and draw a fresh set from those weights. They called it the bootstrap filter. Bootstrap filter

The same idea has several names. Arulampalam and co-authors call it a sequential Monte Carlo (SMC) approach. They list other names for it: bootstrap filtering, the condensation algorithm, particle filtering, interacting particle approximations and survival of the fittest. Names Doucet and Johansen use SMC for a wider family of methods, of which particle methods are one part. SMC methods

A small example shows why samples help. Suppose a sensor reports x2/20x^2/20 plus noise. A reading of 5 fits x=10x=10 and x=−10x=-10 equally well. A single Gaussian must pick one side, or sit in the middle near zero where neither answer lies. A cloud of particles can simply keep two clumps, one near each answer. The worked example below uses exactly this sensor.

The trade-off is heavier computation and some new ways to fail. With too few particles, or particles in the wrong places, the cloud stops describing the belief. This article explains the mechanics and those failure modes. The best-known robotics use, Monte Carlo localization, is covered in robot localization. Background: importance sampling, Monte Carlo integration and Bayes’ theorem.

From samples to a filter

This section builds the particle filter in steps: a sample-based belief, importance weights, the bootstrap filter, resampling and its side effects.

A belief made of weighted samples

A particle is one possible value of the state, written xk(i)x_k^{(i)}, with a weight wk(i)w_k^{(i)}. With NN particles the belief is approximated as follows.

p(xk∣y1:k)≈∑i=1Nwk(i) δ ⁣(xk−xk(i)),∑i=1Nwk(i)=1p(x_k\mid y_{1:k})\approx\sum_{i=1}^{N}w_k^{(i)}\,\delta\!\left(x_k-x_k^{(i)}\right),\qquad \sum_{i=1}^{N}w_k^{(i)}=1

In words: the belief about the state at step kk, given measurements y1y_1 to yky_k, is replaced by NN weighted spikes at the particle positions. Here δ\delta is the Dirac delta, a spike of total area one, and the weights add up to one. An average under the belief, such as the posterior mean, becomes a weighted sum ∑iwk(i)xk(i)\sum_i w_k^{(i)}x_k^{(i)}. As NN grows, this weighted-sample description becomes equivalent to the exact belief. Representation

Särkkä notes that the Monte Carlo error of such averages shrinks like N−1/2N^{-1/2} whatever the state dimension, but adds “at least in theory, not necessarily in practice”. Monte Carlo approximation Doucet and Johansen explain one reason: the constants in the error bounds typically grow with the state dimension, polynomially or even exponentially. Monte Carlo and dimension

Importance weights and sequential importance sampling

We usually cannot draw samples from the belief directly. Importance sampling gets around this: draw from a convenient proposal distribution π\pi, then correct each sample by a weight equal to target density over proposal density. Sequential importance sampling (SIS) does this one time step at a time. Each particle is extended by a draw xk(i)∼π(xk∣xk−1(i),yk)x_k^{(i)}\sim\pi(x_k\mid x_{k-1}^{(i)},y_k), and Särkkä and Doucet–Johansen give its weight update as follows. SIS weights, eq. (7.25) SIS for filtering

wk(i)∝wk−1(i) p ⁣(yk∣xk(i))p ⁣(xk(i)∣xk−1(i))π ⁣(xk(i)∣xk−1(i),yk)w_k^{(i)}\propto w_{k-1}^{(i)}\,\frac{p\!\left(y_k\mid x_k^{(i)}\right)p\!\left(x_k^{(i)}\mid x_{k-1}^{(i)}\right)}{\pi\!\left(x_k^{(i)}\mid x_{k-1}^{(i)},y_k\right)}

In words: a particle’s new weight is its old weight, times how well it explains the measurement yky_k, times how plausible its move is under the motion model, divided by how likely the proposal was to make that move.

The choice of π\pi matters. The proposal that minimises the variance of the weights, called the optimal proposal, is p(xk∣xk−1,yk)p(x_k\mid x_{k-1},y_k): it looks at the new measurement before moving the particle. Its weight factor is p(yk∣xk−1)p(y_k\mid x_{k-1}). It is often impossible to sample from or to evaluate, so approximations built from the EKF or the unscented Kalman filter are used instead. Optimal proposal, eqs. (39)–(40) Särkkä warns that such Gaussian proposals can make the filter fail and should be used with extreme care, for example by inflating the covariance or using a Student’s t distribution. Optimal importance distribution, eq. (7.33) Arulampalam and co-authors conclude that choosing the importance density is the crucial design step. Conclusions

The bootstrap filter

The simplest choice is to propose with the motion model itself, π=p(xk∣xk−1)\pi=p(x_k\mid x_{k-1}). The motion terms then cancel, and the weight is just the likelihood.

xk(i)∼p ⁣(xk∣xk−1(i)),wk(i)∝p ⁣(yk∣xk(i))x_k^{(i)}\sim p\!\left(x_k\mid x_{k-1}^{(i)}\right),\qquad w_k^{(i)}\propto p\!\left(y_k\mid x_k^{(i)}\right)

In words: move each particle by simulating the motion model with random noise, then weight it by how likely the new measurement is from its new position. Old weights do not carry over, because they were reset to equal values at the last resampling.

This is Gordon, Salmond and Smith’s bootstrap filter. It starts by drawing NN samples from the prior. Each step predicts by passing every sample through the system model with sampled noise. It then weights each sample by its normalised likelihood and resamples NN times from those weights. Algorithm Bootstrap filter, Alg. 7.5

Gordon and colleagues list only three requirements. The initial density can be sampled, the likelihood has a known functional form, and the process noise can be sampled. No linearity or Gaussian assumption is needed. Requirements The weakness is that particles move without looking at the measurement. Särkkä says this makes the filter easy to implement but potentially in need of very many samples. Bootstrap weaknesses Arulampalam and co-authors call it inefficient and sensitive to outliers. SIR

Weight degeneracy and the effective sample size

Plain SIS has a serious flaw. After a few steps nearly all the weight sits on one particle and the rest contribute almost nothing. This is called weight degeneracy. Arulampalam and co-authors cite a result of Doucet (1998) that the variance of the importance weights can only increase over time, so degeneracy cannot be avoided without remedies. Degeneracy Särkkä writes that this problem prevented practical use of particle filters for many years. Degeneracy

Doucet and Johansen put a number on it in a toy example whose target factorises. With a proposal variance of 1.2, plain importance sampling over 1000 steps would need about 2×10232\times10^{23} particles to reach a relative variance of 0.01. With resampling the variance grows only linearly in time, and about 10410^4 particles suffice. They call the toy target overly favourable to SMC, so this gap of “19 orders of magnitude” is not a general figure. Toy example

A standard measure of degeneracy is the effective sample size (ESS).

Neff=1∑i=1N(wk(i))2N_{\mathrm{eff}}=\frac{1}{\sum_{i=1}^{N}\left(w_k^{(i)}\right)^{2}}

In words: with normalised weights, NeffN_{\mathrm{eff}} equals NN when all weights are equal and 1 when one particle holds all the weight, so it reads as “how many particles are really working”. For weights 0.5, 0.3, 0.15 and 0.05 it is 1/0.365≈2.741/0.365\approx2.74.

Doucet and Johansen recommend resampling only when the ESS drops below a threshold, typically N/2N/2. ESS and adaptive resampling Särkkä gives N/10N/10 as an example threshold. Effective number of particles, eq. (7.27) Labbe suggests N/2N/2 as a starting point that varies by problem. Particle resampling These are rules of thumb, not laws.

Resampling

Resampling draws NN new particles from the current weighted set and resets all weights to 1/N1/N. High-weight particles are copied and low-weight ones disappear. In expectation this leaves the distribution unchanged, but it adds Monte Carlo noise. Resampling, Alg. 7.3 Resampling Doucet and Johansen describe the trade-off: resampling costs extra variance now and buys stability later, which is why they resample only when the ESS is low. Resampling trade-off

Common unbiased schemes are multinomial, residual, stratified and systematic resampling. Systematic resampling uses a single random number for all NN draws.

uj=u1+j−1N,u1∼U ⁣(0,1N),parent(j)=min⁡{i:∑l=1iw(l)≥uj}u_j=u_1+\frac{j-1}{N},\quad u_1\sim\mathcal{U}\!\left(0,\tfrac{1}{N}\right),\qquad \text{parent}(j)=\min\Big\{i:\sum_{l=1}^{i}w^{(l)}\ge u_j\Big\}

In words: place NN evenly spaced pointers uju_j over the running total of the weights, starting from a random point u1u_1 in the first interval of width 1/N1/N. Each pointer picks the first particle whose running total reaches it (U\mathcal U is the uniform distribution). A particle with weight ww therefore gets about NwNw copies. With weights 0.5, 0.3, 0.15, 0.05 and u1=0.1u_1=0.1, the pointers 0.1, 0.35, 0.6 and 0.85 give copies (2, 1, 1, 0).

The sources disagree on which scheme is best, so each view is attributed here. Doucet and Johansen call systematic resampling the most widely used and usually the best, while noting it is not guaranteed best in general. Resampling schemes Arulampalam and co-authors also prefer systematic resampling, because it runs in O(N)O(N) time and minimises Monte Carlo variation. Systematic resampling Särkkä instead calls stratified resampling optimal in terms of variance, citing Kitagawa (1996). Stratified resampling Labbe’s practical comparison advises against multinomial resampling and finds stratified and systematic similar in practice. Resampling methods

What resampling breaks

Resampling cures weight degeneracy but causes sample impoverishment. Copying the best particles again and again reduces the number of distinct values. With very small process noise, all particles can collapse to a single point within a few steps. Resampling also limits parallel implementation. Impoverishment Impoverishment Gordon and colleagues saw this from the start: when the likelihood is concentrated relative to the prior, a few samples are copied many times and the rest vanish. Collapse

Several remedies have been proposed. Roughening adds a small random jitter after resampling; Gordon and colleagues used it, together with a step they called prior editing, and described both as “somewhat ad hoc”. Roughening Regularisation resamples from a smoothed kernel density instead of the spikes. Resample-move applies Markov chain Monte Carlo (MCMC) moves that leave the posterior unchanged. Arulampalam and co-authors note that the regularised filter loses the guarantee of asymptotically sampling from the posterior. Remedies

A further problem concerns whole histories. Each particle carries a path of earlier states. After many resampling steps, all particles descend from the same ancestor at any fixed earlier time, so the posterior over long paths cannot be approximated well. This is path degeneracy. Doucet and Johansen add that estimates for recent states can still keep an error that stays bounded over time, under mixing conditions. Path degeneracy

How many particles?

Gordon and colleagues justified their filter only as N→∞N\to\infty. They wrote that results for finite NN are very hard to prove. They named three factors that drive the number needed: the state dimension, how well prior and likelihood overlap, and the number of time steps. Sample size

Their four-dimensional bearings-only tracking example needed 4000 samples, plus roughening (tuning constant 0.2) and prior editing. They noted that a grid of the same size would have only about 8 points per coordinate. The EKF diverged in that example. Bearings-only example

Rao–Blackwellised particle filters

When part of the model is linear-Gaussian given the rest, there is no need to sample everything. A Rao–Blackwellised particle filter samples only some variables, for example a discrete switching mode, and handles the linear-Gaussian part with a Kalman filter attached to each particle. By the Rao–Blackwell theorem this gives estimates with lower variance. Rao–Blackwellised PF

A bootstrap filter on a classic benchmark

This section runs a bootstrap filter on the scalar model of Gordon, Salmond and Smith and compares it with SIS and an EKF. The program is original synthetic code, numpy only, with fixed seeds. The model is their equations (9)–(10). Model, eqs. (9)–(10)

xk=xk−12+25 xk−11+xk−12+8cos⁡(1.2(k−1))+wk,yk=xk220+vkx_k=\frac{x_{k-1}}{2}+\frac{25\,x_{k-1}}{1+x_{k-1}^{2}}+8\cos\big(1.2(k-1)\big)+w_k,\qquad y_k=\frac{x_k^{2}}{20}+v_k

In words: the state follows a strongly nonlinear recursion with a periodic push and process noise wk∼N(0,10)w_k\sim\mathcal N(0,10). The sensor sees only the square of the state divided by 20, plus noise vk∼N(0,1)v_k\sim\mathcal N(0,1); the second number in N(⋅,⋅)\mathcal N(\cdot,\cdot) is a variance.

The true start is x0=0.1x_0=0.1 and the run lasts T=50T=50 steps. Gordon and colleagues write the filter’s prior as “N(0,2)” without saying whether 2 is the variance or the standard deviation. We read it as variance 2; that is our assumption. The EKF baseline linearises the model around its current mean; its derivation belongs to extended Kalman filter. Particle intervals are the weighted 2.5% and 97.5% quantiles. EKF intervals are the mean ± 1.96 standard deviations.

import numpy as np

# Synthetic study of the bootstrap particle filter on the scalar benchmark model
# used by Gordon, Salmond and Smith (1993, eqs. 9-10). Everything is simulated.
Q, R, T = 10.0, 1.0, 50


def f(x, k):
    return 0.5 * x + 25.0 * x / (1.0 + x * x) + 8.0 * np.cos(1.2 * (k - 1))


def h(x):
    return x * x / 20.0


def simulate(seed):
    rng = np.random.default_rng(seed)
    x, xs, ys = 0.1, [], []
    for k in range(1, T + 1):
        x = f(x, k) + rng.normal(0.0, np.sqrt(Q))
        xs.append(x)
        ys.append(h(x) + rng.normal(0.0, np.sqrt(R)))
    return np.array(xs), np.array(ys)


def ess(w):
    return 1.0 / np.sum(w * w)


def systematic(w, u1):
    n = len(w)
    points = u1 + np.arange(n) / n
    idx = np.searchsorted(np.cumsum(w), points)
    return np.minimum(idx, n - 1)


def particle_filter(ys, n, seed, mode):
    rng = np.random.default_rng(seed)
    x = rng.normal(0.0, np.sqrt(2.0), n)
    w = np.full(n, 1.0 / n)
    out = {"mean": [], "lo": [], "hi": [], "ess": [], "distinct": [], "pos": []}
    for k in range(1, T + 1):
        x = f(x, k) + rng.normal(0.0, np.sqrt(Q), n)
        logl = -0.5 * (ys[k - 1] - h(x)) ** 2 / R
        w = w * np.exp(logl - logl.max())
        w = w / w.sum()
        order = np.argsort(x)
        cdf = np.cumsum(w[order])
        out["mean"].append(np.sum(w * x))
        out["lo"].append(x[order][np.searchsorted(cdf, 0.025)])
        out["hi"].append(x[order][min(np.searchsorted(cdf, 0.975), n - 1)])
        out["ess"].append(ess(w))
        out["pos"].append(np.sum(w[x > 0]))
        if mode == "always" or (mode == "adaptive" and ess(w) < n / 2):
            idx = systematic(w, rng.uniform(0.0, 1.0 / n))
            x, w = x[idx], np.full(n, 1.0 / n)
        out["distinct"].append(len(np.unique(x)))
    return {key: np.array(v) for key, v in out.items()}


def ekf(ys):
    m, P = 0.0, 2.0
    means, lo, hi = [], [], []
    for k in range(1, T + 1):
        F = 0.5 + 25.0 * (1.0 - m * m) / (1.0 + m * m) ** 2
        m, P = f(m, k), F * P * F + Q
        H = m / 10.0
        S = H * P * H + R
        K = P * H / S
        m, P = m + K * (ys[k - 1] - h(m)), (1.0 - K * H) * P
        means.append(m)
        lo.append(m - 1.96 * np.sqrt(P))
        hi.append(m + 1.96 * np.sqrt(P))
    return np.array(means), np.array(lo), np.array(hi)


def rmse(a, b):
    return float(np.sqrt(np.mean((a - b) ** 2)))


def cover(xs, lo, hi):
    return float(np.mean((xs >= lo) & (xs <= hi)))


print("1) Hand check: four normalized weights")
w4 = np.array([0.5, 0.3, 0.15, 0.05])
print("   ESS = 1/sum(w^2) = %.4f" % ess(w4))
idx4 = systematic(w4, 0.1)
print("   systematic resampling with u1=0.1: points", np.round(0.1 + np.arange(4) / 4, 3),
      "-> parents", idx4, "-> copies", np.bincount(idx4, minlength=4))

xs, ys = simulate(1)
print("\n2) One synthetic run (seed 1), T=50, N=500")
pf = particle_filter(ys, 500, 11, "always")
sis = particle_filter(ys, 500, 11, "never")
ada = particle_filter(ys, 500, 11, "adaptive")
em, elo, ehi = ekf(ys)
print("   method            RMSE   95%-interval coverage")
for name, r in [("bootstrap (SIR)", pf), ("adaptive ESS<N/2", ada), ("SIS, no resample", sis)]:
    print("   %-17s %6.2f   %.2f" % (name, rmse(r["mean"], xs), cover(xs, r["lo"], r["hi"])))
print("   %-17s %6.2f   %.2f" % ("EKF", rmse(em, xs), cover(xs, elo, ehi)))

print("\n3) Weight degeneracy without resampling (ESS out of N=500)")
for k in [1, 2, 5, 10, 50]:
    print("   k=%2d  SIS ESS %7.2f   bootstrap ESS before resampling %6.1f"
          % (k, sis["ess"][k - 1], pf["ess"][k - 1]))
print("   adaptive filter resampled at %d of %d steps" % (int(np.sum(ada["ess"] < 250)), T))

print("\n4) Sign ambiguity: y = x^2/20 cannot tell x from -x")
k = int(np.argmin(np.abs(pf["pos"] - 0.5) + (np.abs(xs) < 5) * 10)) + 1
print("   step k=%d: true x=%.2f, weight on x>0: %.3f, posterior mean %.2f"
      % (k, xs[k - 1], pf["pos"][k - 1], pf["mean"][k - 1]))
print("   bimodal steps (weight on each sign >= 0.2): %d of %d"
      % (int(np.sum((pf["pos"] > 0.2) & (pf["pos"] < 0.8))), T))

print("\n5) Distinct particle values after resampling (bootstrap, N=500)")
print("   min %d, median %d, max %d" % (pf["distinct"].min(), np.median(pf["distinct"]),
                                       pf["distinct"].max()))

print("\n6) Monte Carlo spread: 20 synthetic data sets x 1 filter run each")
data = [simulate(100 + s) for s in range(20)]
print("   method   mean RMSE  median  max     mean 95%-coverage")
for n in [50, 200, 1000]:
    runs = [particle_filter(y, n, 500 + s, "always") for s, (x, y) in enumerate(data)]
    errs = [rmse(r["mean"], x) for r, (x, y) in zip(runs, data)]
    cov = [cover(x, r["lo"], r["hi"]) for r, (x, y) in zip(runs, data)]
    print("   N=%-5d  %6.2f    %6.2f  %6.2f   %.2f" % (n, np.mean(errs), np.median(errs), np.max(errs), np.mean(cov)))
eruns = [ekf(y) for x, y in data]
eerr = [rmse(r[0], x) for r, (x, y) in zip(eruns, data)]
ecov = [cover(x, r[1], r[2]) for r, (x, y) in zip(eruns, data)]
print("   EKF      %6.2f    %6.2f  %6.2f   %.2f" % (np.mean(eerr), np.median(eerr), np.max(eerr), np.mean(ecov)))

The program prints:

1) Hand check: four normalized weights
   ESS = 1/sum(w^2) = 2.7397
   systematic resampling with u1=0.1: points [0.1  0.35 0.6  0.85] -> parents [0 0 1 2] -> copies [2 1 1 0]

2) One synthetic run (seed 1), T=50, N=500
   method            RMSE   95%-interval coverage
   bootstrap (SIR)     4.53   0.92
   adaptive ESS<N/2    4.18   0.90
   SIS, no resample    8.04   0.14
   EKF                 4.72   0.84

3) Weight degeneracy without resampling (ESS out of N=500)
   k= 1  SIS ESS   23.87   bootstrap ESS before resampling   23.9
   k= 2  SIS ESS   11.40   bootstrap ESS before resampling  172.7
   k= 5  SIS ESS    1.53   bootstrap ESS before resampling  156.5
   k=10  SIS ESS    1.00   bootstrap ESS before resampling  127.1
   k=50  SIS ESS    1.00   bootstrap ESS before resampling  391.5
   adaptive filter resampled at 40 of 50 steps

4) Sign ambiguity: y = x^2/20 cannot tell x from -x
   step k=42: true x=-8.71, weight on x>0: 0.515, posterior mean 0.88
   bimodal steps (weight on each sign >= 0.2): 27 of 50

5) Distinct particle values after resampling (bootstrap, N=500)
   min 23, median 197, max 463

6) Monte Carlo spread: 20 synthetic data sets x 1 filter run each
   method   mean RMSE  median  max     mean 95%-coverage
   N=50       6.01      5.51   10.07   0.81
   N=200      4.78      4.79    7.11   0.92
   N=1000     4.82      4.91    6.96   0.94
   EKF       19.51     14.77  104.79   0.53

Part 1 repeats the hand check from the theory section (parents are counted from zero). The copies (2, 1, 1, 0) are close to the expected counts Nw=(2,1.2,0.6,0.2)Nw=(2, 1.2, 0.6, 0.2).

Part 2 is one synthetic data set with 500 particles. The bootstrap filter resamples at every step. Its RMSE (root mean squared error) is 4.53, and its 95% intervals contain the truth at 0.92 of the steps. The adaptive filter, which resamples only when the ESS drops below N/2N/2, gets 4.18 and 0.90. SIS without resampling is far worse: RMSE 8.04 and coverage 0.14. On this particular data set the EKF happens not to diverge (4.72 and 0.84). Part 6 shows that this was luck.

Part 3 shows weight degeneracy. Without resampling, the ESS falls from 23.87 at k=1k=1 to 11.40 at k=2k=2, 1.53 at k=5k=5 and 1.00 at k=10k=10 and k=50k=50. From step 10 on, one particle carries all the weight. The bootstrap filter’s ESS, measured before each resampling, stays between 127.1 and 391.5 at the later printed steps. It never accumulates degeneracy, because the weights are reset every step. Even at k=1k=1 only about 24 of 500 particles matter: the wide prior and the first measurement overlap poorly, one of Gordon’s three factors. The adaptive filter resampled at 40 of 50 steps.

Part 4 shows why the RMSE stays large even for a good filter. Because y=x2/20y=x^2/20, the measurement cannot tell xx from −x-x. At k=42k=42 the true state is −8.71. The filter puts 0.515 of its weight on x>0x>0, and the posterior mean is 0.88. That mean sits between the two clumps, where neither the truth nor much probability lies. In 27 of 50 steps each sign carries at least 0.2 of the weight. Gordon and colleagues likewise found a bimodal (two-peaked) posterior at k=21k=21 in their run. Bimodal posterior Arulampalam and co-authors call RMSE “not exceptionally meaningful” for such a multimodal problem. RMSE

Part 5 measures impoverishment. Right after resampling, the 500 particles had between 23 and 463 distinct values, with a median of 197. At the worst step, more than 95% of the particles were copies of others.

Part 6 repeats the comparison on 20 synthetic data sets, with one filter run each. Mean RMSE is 6.01 with N=50N=50, 4.78 with N=200N=200 and 4.82 with N=1000N=1000. The worst data sets give 10.07, 7.11 and 6.96. Mean coverage rises from 0.81 to 0.92 to 0.94. So going from 200 to 1000 particles does not reduce the RMSE. The error floor here is the two-clump posterior itself, not Monte Carlo noise. More particles describe that posterior better, so the intervals become more honest, but the mean does not become a better guess.

The EKF on the same 20 data sets has mean RMSE 19.51, median 14.77 and a worst case of 104.79. Its nominal 95% intervals cover the truth only 0.53 of the time. This matches the qualitative picture in Gordon and colleagues’ paper, where the EKF’s 95% region contained the true state only about 30% of the time in their run. EKF coverage

When particles are not worth it

This section lists cases where particle filters fail, and cases where they are simply not needed.

A Gaussian filter is often enough. In Särkkä’s pendulum example, a bootstrap filter with 10 000 particles had RMSE 0.12. That equals the EKF, and other Gaussian filters reached 0.11. The belief was close to Gaussian, so the particle filter bought nothing but cost. Example 7.1 Arulampalam and co-authors state that when the assumptions of the Kalman filter or a grid filter hold, no other algorithm can outperform them. Conclusions

But sometimes particles are essential. In Särkkä’s clutter example, half the measurements were random clutter (false returns). A bootstrap filter with 10 000 particles and a clutter indicator in the state reached RMSE 0.16. A Gaussian filter (a Gauss–Hermite Kalman filter) with no clutter model reached 3.60, and one with inflated noise 0.82. Example 7.2 Multimodal beliefs, as in Part 4, are the other classic case.

Particles cannot appear from nothing. Resampling only copies existing particles. If no particle starts near the truth, the filter cannot recover. Labbe shows this, and also observes that a very accurate sensor can make a particle filter worse: few particles land where the narrow likelihood is large. More particles, or starting the particles near a rough initial guess, helps. Sensor errors and inadequate samples For robots that may be picked up and moved, robot localization discusses adding random particles, a fix whose justification its sources dispute.

Static parameters are hard. With zero or tiny process noise, impoverishment quickly collapses the cloud. Särkkä says particle filtering of static parameters is hard. Static parameters Arulampalam and co-authors note that with zero process noise a particle filter is not entirely appropriate. Footnote 5

ESS is not accuracy. ESS describes how even the weights are, not whether the particles are in the right place. ESS computed after resampling is always NN, because the weights were just reset. Even before resampling, a cloud of near-identical particles far from the truth can have even weights.

Long histories and many dimensions. Path degeneracy limits whole-trajectory estimates, and error constants grow with the state dimension (see the theory section). Rao–Blackwellisation is one way to keep the sampled part small.

This example is a toy. It uses one synthetic scalar model, fixed seeds and 20 data sets. The numbers illustrate degeneracy, bimodality and occasional EKF divergence. They are not performance figures for any real system.

Exercises

These exercises cover degeneracy, a hand calculation, a counterexample, method choice and a diagnostic trap.

  1. Why does SIS without resampling fail on long sequences even with a reasonable proposal? Why does resampling help without solving everything?

    Answer: Each weight is a product of per-step factors, and the variance of the weights grows over time (Arulampalam and co-authors, citing Doucet; Doucet and Johansen show exponential growth in a toy case). Soon one particle carries all the weight: in the example the SIS ESS is 1.00 from k=10k=10. Resampling resets the weights, so effort goes to the current state. But it adds Monte Carlo variance and duplicates particles (as few as 23 distinct values out of 500 in the example). Stored paths also coalesce, so earlier states end up represented by few ancestors or one.

  2. Five particles have unnormalised weights 4, 2, 1, 1, 0 (the last one got zero likelihood). (a) Normalise and compute the ESS. (b) Do systematic resampling with u1=0.05u_1=0.05 and N=5N=5. (c) With an N/2N/2 threshold, would an adaptive filter resample?

    Answer: (a) The sum is 8, so w=(0.5,0.25,0.125,0.125,0)w=(0.5, 0.25, 0.125, 0.125, 0). ∑w2=0.25+0.0625+0.015625+0.015625=0.34375\sum w^2=0.25+0.0625+0.015625+0.015625=0.34375, so the ESS is 1/0.34375≈2.9091/0.34375\approx2.909. (b) Pointers 0.05, 0.25, 0.45, 0.65, 0.85; running totals 0.5, 0.75, 0.875, 1.0, 1.0. Pointers 0.05, 0.25 and 0.45 pick particle 1, 0.65 picks particle 2 and 0.85 picks particle 3 (particles numbered 1 to 5). Copies: (3, 1, 1, 0, 0). The expected counts Nw=(2.5,1.25,0.625,0.625,0)Nw=(2.5, 1.25, 0.625, 0.625, 0); systematic resampling gives each particle the expected count rounded down or up. (c) The threshold is 2.5. Since 2.909 is above it, the filter would not resample yet.

  3. A colleague claims: “With enough particles a particle filter always beats an EKF, and its posterior mean is the right point estimate.” Give counterexamples.

    Answer: (i) In Särkkä’s pendulum example a 10 000-particle bootstrap filter had RMSE 0.12, equal to the EKF, while other Gaussian filters had 0.11. When the belief is near-Gaussian, particles add only cost. (ii) In our example, going from N=200N=200 to N=1000N=1000 did not lower the RMSE (4.78 to 4.82). The posterior itself is bimodal, and its mean (0.88 at k=42k=42, with the truth at −8.71) lies between the modes. More particles approximate that posterior better; they do not make the mean a good estimate. (iii) More particles cannot repair a wrong model, or a cloud that never covered the truth (Labbe). The reverse claim is false too: the EKF did fail badly on some data sets (worst RMSE 104.79, coverage 0.53).

  4. Choose a method and justify it: (a) tracking with 50% clutter measurements; (b) a mildly nonlinear 2-D tracking problem with Gaussian noise and a tight compute budget; (c) a model with a discrete switching mode and linear-Gaussian dynamics given the mode; (d) estimating a constant unknown parameter online with a particle filter.

    Answer: (a) A particle filter with a clutter indicator in the state; in Särkkä’s Example 7.2 it reached RMSE 0.16 against 3.60 and 0.82 for Gaussian filters. (b) Start with an EKF or another Gaussian filter; the pendulum result shows a particle filter may not help. (c) A Rao–Blackwellised particle filter: sample the mode and run a Kalman filter for the linear part of each particle. (d) Problematic: with no process noise the cloud impoverishes and collapses (Särkkä; Arulampalam and co-authors). Prefer other methods, or add artificial dynamics knowingly, which changes the model.

  5. A report says: “Our particle filter had ESS = N after every step, so it is working perfectly.” What is missing?

    Answer: ESS measured right after resampling is always NN, because the weights were reset; it must be computed before resampling, as the example does in Part 3. Even then, a high ESS only says the weights are even. Near-identical copies, or a whole cloud in the wrong place, can have high ESS (see robot localization for a cloud stuck far from a kidnapped robot). Doucet and Johansen motivate ESS through the variance of importance-sampling estimates, so it is a diagnostic for weight degeneracy, not a measure of accuracy.

History and further reading

This section sketches where the idea came from and where to read next. The modern particle filter is usually dated to Gordon, Salmond and Smith (1993); Doucet and Johansen’s tutorial is subtitled “fifteen years later” and refers to the methods’ introduction in 1993. Introduction Gordon and colleagues motivated their update step as a weighted bootstrap, following Smith and Gelfand (1992). Weighted bootstrap

Monte Carlo filtering itself is older. Dellaert and co-authors write that such methods were invented in the seventies, citing Handschin (1970), and later rediscovered in target tracking, statistics and computer vision. History We have not read Handschin’s paper or the parallel work published under names such as the Monte Carlo filter and condensation, so we report these only as cited.

In robotics, Dellaert, Fox, Burgard and Thrun applied the bootstrap filter to estimating a robot’s pose in a known map and called it Monte Carlo localization; see robot localization. Monte Carlo localization Rao–Blackwellised particle filters are also used in SLAM; we did not read those papers.

For further study, Doucet and Johansen’s tutorial covers SMC theory and particle smoothing in depth (we read only the parts listed in the source notes). Chapter 7 of Särkkä’s book gives the algorithms compactly, with worked examples. Labbe’s open notebook chapter builds a particle filter step by step in Python. The forward recursion of discrete hidden Markov models in speech recognition and Markov chains are closely related background.

Make a prediction, then check

Four particles have normalised weights 0.5, 0.3, 0.15, 0.05. What is their effective sample size, and how many copies does each particle get under systematic resampling with u₁ = 0.1?

Choose one answer

Learning objectives

  • Write the Bayes filter in weighted-particle form, derive the SIS weight recursion and the bootstrap filter, and compute an effective sample size and one systematic resampling by hand.
  • Explain the causes of and remedies for weight degeneracy, sample impoverishment and path degeneracy, and judge when a particle filter is worth its cost and when a Gaussian filter is enough.

Prerequisites & connections

Explore related knowledge →

References

  1. Novel approach to nonlinear/non-Gaussian Bayesian state estimation — scoped
    N. J. Gordon; D. J. Salmond; A. F. M. Smith · 1993
  2. A Tutorial on Particle Filters for Online Nonlinear/Non-Gaussian Bayesian Tracking — scoped
    M. Sanjeev Arulampalam; Simon Maskell; Neil Gordon; Tim Clapp · 2002
  3. A Tutorial on Particle Filtering and Smoothing: Fifteen Years Later — scoped
    Arnaud Doucet; Adam M. Johansen · 2008
  4. Bayesian Filtering and Smoothing — scoped
    Simo Särkkä · 2013
  5. Kalman and Bayesian Filters in Python
    Roger R. Labbe · 2024
  6. Monte Carlo Localization for Mobile Robots — scoped
    Frank Dellaert; Dieter Fox; Wolfram Burgard; Sebastian Thrun · 1999

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Claude · 2026-12-03 · Independent AI check (Claude subagent, not the author; not a human or expert review). Research was done by a separate research subagent (facts.md) and the prose by a writer subagent; style-only edits suggested by the Gemini app were applied to the opening sections before this check, and all 8 logged edits for this topic (gemini-edits-016a.json) were compared old-versus-new and kept because none changed a fact, hedge or attribution. Ran example.py with the pinned interpreter (numpy 1.26.4): output is byte-identical to example.stdout.txt, and the python block in en.mdx and zh.mdx is byte-identical to example.py; every number quoted in the prose was compared with that output. Re-derived the ESS hand check (1/0.365), the systematic-resampling copies (2,1,1,0), and exercise 2 (ESS 2.909, copies (3,1,1,0,0), no resampling at threshold 2.5). Checked that display equations, h2 anchors and citation IDs match between languages and compared zh and en paragraph by paragraph. Re-downloaded and re-read with pdftotext: Gordon et al. 1993 pp. 107-113 (no closed form/gross distortion and divergence, N(0,2) prior, ~30% EKF coverage, N=500, bimodal at k=21, roughening, 'somewhat ad hoc', N=4000, ~8 grid points per coordinate, EKF divergence); Arulampalam et al. 2002 p. 178 (the 'sequential MC (SMC) approach is known variously as' list), p. 179 (weight variance can only increase, citing [12]), p. 183 ('not exceptionally meaningful'), §VI-G/VII; Doucet-Johansen pp. 4-5 (particle methods a subset of SMC), pp. 11-13 (2x10^23, systematic most widely used, not guaranteed best), p. 15 (N_T = N/2), pp. 17-19 (10^4, 19 orders of magnitude, overly favourable, constants growing polynomially/exponentially with dimension, mixing conditions); Särkkä ch. 7 pp. 117, 123 (degeneracy prevented applications; stratified optimal in variance citing Kitagawa), 125 (extreme care, Student's t), 127-129 (Examples 7.1-7.2 RMSE values); Dellaert et al. 1999 p. 1 (invented in the seventies, Handschin). Not re-checked: the Labbe notebook (claims taken from facts.md and the writer's locator), Särkkä §7.5 beyond the opening, and Arulampalam's equations (illegible in the copy; the article cites no equation from it).

  • Example rerun with the pinned interpreter (numpy 1.26.4) matches example.stdout.txt byte for byte; code blocks in both languages equal example.py; every quoted number matches the output.
  • Re-derived the ESS hand check, the systematic-resampling copies and exercise 2; all correct, and the data.json quiz answer is correct.
  • Re-downloaded and checked the cited passages of Gordon 1993, Arulampalam 2002, Doucet–Johansen, Särkkä ch. 7 and Dellaert 1999; attributions and numbers are supported.
  • zh and en compared paragraph by paragraph: claims, equations, numbers, exercises and answers match; the Gemini style edits changed no fact or hedge.

Source locations checked:

  • Novel approach to nonlinear/non-Gaussian Bayesian state estimation — scoped · pdftotext of the 7-page scan (Wayback copy of fs.isy.liu.se course material; live URL 404 on 2026-12-03). p. 107: abstract, §1 (no closed form for nonlinear/non-Gaussian; EKF gross distortion/divergence; grid methods costly; samples instead of function; weighted bootstrap after Smith & Gelfand), §2 eq. 1, received 27 Apr / revised 8 Oct 1992. p. 108: eqs. 2–7, §3.1 algorithm (prediction, normalised likelihood weights, resample N times, initialise from prior), §3.2 justification (asymptotic), start §3.3. p. 109: requirements (a)–(c), resampling via uniform draws, parallel implementation, N depends on dimension/overlap/time steps, collapse with no system noise, §4.1 eqs. 9–10. p. 110: prior N(0,2), EKF 95% region ~30%, bootstrap N=500, bimodal posterior at k=21, §4.2 model. pp. 111–112: bearings-only results, EKF divergence after k=13, roughening (K=0.2), prior editing, N=4000, ~8 grid points per coordinate. p. 113: conclusions. OCR of equations is noisy; eqs. 9–10 cross-checked against the text description (variances 10.0 and 1.0). NOT read: references beyond the list itself.
  • A Tutorial on Particle Filters for Online Nonlinear/Non-Gaussian Bayesian Tracking — scoped · pdftotext of the 15-page IEEE version on cs.ubc.ca/~murphyk. Most equations are missing in the extraction. Prose read: §I p. 174 (abstract/intro); §V-A pp. 178–180 (SIS, alternative names, degeneracy and weight-variance remark citing [12], Neff eqs. 50–51 by name only, optimal importance density, prior as proposal 'most common', resampling when Neff below threshold, systematic resampling preferred and O(N), sample impoverishment, collapse with very small process noise, footnotes 5–6, resample-move); §V-B pp. 181–183 (SIR assumptions, inefficient/sensitive to outliers, ASIR, RPF and its lack of asymptotic guarantee); §VI pp. 183–186 (RMSE not very meaningful for multimodal problem, EKF overconfident, grid vs PF, 50 particles, choice of importance density crucial); §VII p. 186. NOT read: §II–IV details (pp. 175–178), Appendix equations, Table I values (not legible).
  • A Tutorial on Particle Filtering and Smoothing: Fifteen Years Later — scoped · pdftotext -layout of doucet_johansen_tutorialPF2011.pdf v1.1 (printed pages). p. 1 abstract and §1.1 (introduced 1993 [22]; no local linearisation; computationally expensive). pp. 2–5 §2.1–2.2 eqs. 1–11. p. 8 §3.1 (O(1/N) variance regardless of dimension; two problems). pp. 9–10 §3.2 eqs. 21–27. pp. 10–12 §3.3 SIS eqs. 28–30, optimal incremental proposal, toy example (σ²=1.2, n=1000, N≈2×10^23). pp. 13–14 §3.4 resampling, systematic/residual/multinomial, systematic most widely used, extra variance. pp. 14–16 §3.5 generic SMC, ESS definition, N_T = N/2, adaptive resampling, degeneracy/impoverishment discussion. pp. 16–18 §3.6 CLT, linear growth, 'N≈10^4 ... 19 orders of magnitude', 'overly favourable', constants grow with dimension. pp. 18–19 §3.7 summary (path degeneracy). p. 19 §4 (recommend ESS threshold + systematic). pp. 20–21 §4.1 eqs. 39–40, SIR/SMC for filtering, EKF/UKF proposals. pp. 21–22 §4.1.1 SV example text (SIS N=1000 collapses). pp. 26–27 §4.3 limitations; §4.4 first paragraph. NOT read: §4.2 APF details, §4.5–4.6, §5 smoothing, §6, figures beyond captions.
  • Bayesian Filtering and Smoothing — scoped · pdftotext of cup_book_online_20131111.pdf, chapter 7 (printed pp. 116–130). p. 116 chapter intro (multimodal, discrete components) and §7.1; p. 117 O(N^-1/2) 'at least in theory'; pp. 117–120 §7.2 eqs. 7.3–7.13, Alg. 7.1; pp. 120–123 §7.3 eqs. 7.14–7.26, Alg. 7.2; p. 123 degeneracy 'prevented practical applications for many years', Alg. 7.3, stratified optimal in variance (Kitagawa 1996), SIR usually called the particle filter; p. 124 every-nth-step resampling unbiased, n_eff eq. 7.27, example threshold N/10, Alg. 7.4; p. 125 eq. 7.33 optimal importance distribution, EKF/UKF proposals 'extreme care'; p. 126 bootstrap filter Alg. 7.5, ASIR, sample impoverishment and remedies; p. 127 static parameters hard, Example 7.1 (RMSE 0.12 PF vs 0.12 EKF vs 0.11 others), Fig. 7.3; pp. 128–129 Example 7.2 (50% clutter in [−2, 2]; PF 0.16, GHKF 3.60 and 0.82), Fig. 7.4; pp. 129–130 §7.5 opening, eqs. 7.36–7.37. NOT read: Alg. 7.6 and rest of §7.5, §7.6 exercises.
  • Kalman and Bayesian Filters in Python · raw 12-Particle-Filters.ipynb at commit 04b2bea802321086effbd99402fc13c893d11110 (latest commit before 2026-09-04, dated 2024-07-15); README.md 'License' section at the same commit (text CC BY 4.0, software MIT). Read all markdown cells: Motivation; Monte Carlo Sampling; Generic Particle Filter Algorithm; Probability distributions via Monte Carlo; The Particle Filter (Predict, Update, Computing the State Estimate, Particle Resampling incl. effective N and N/2 starting threshold); SIR Filter – A Complete Example; Effect of Sensor Errors on the Filter; Filter Degeneracy From Inadequate Samples; Importance Sampling; Resampling Methods (multinomial, residual, stratified, systematic, choosing); Summary. NOT read: code cells, outputs, other chapters. Some statements in the chapter are loose (see facts.md pitfalls) and are not used as evidence.
  • Monte Carlo Localization for Mobile Robots — scoped · Used here only for one historical pointer (PDF p. 1: Monte Carlo methods 'invented in the seventies', citing Handschin 1970, rediscovered in target tracking, statistics and computer vision) and for MCL as an application. Full read recorded in the localization data.json.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.