Module contents
Lesson 15 of 27Advanced 110 min

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.

InteractiveParticle localization
  • Particles
  • Robot (truth)
  • Beacons
200
0.00
Measurement steps0
Distance from mean to truth1.30
Drive the robot with map arrows or buttons. Beacons measure noisy distances. Kidnap the robot and compare recovery with and without global injection. The magenta robot shows simulation truth, which a real system does not know.

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.

InteractiveOne distance, two positions
  • Weighted particles, smoothed density
  • EKF
2.0
Sign of prior mean
EKF mean1.96
Positive particle mass0.55
Observing ∣x∣|x| allows positive and negative positions. Change the sign of the prior mean and see which mode the EKF approaches. The particle curve is a smoothed density estimate, not the exact density.

Here the prior is N(±0.1,4)\Normal(\pm 0.1,4) and Y∣x∼N(∣x∣,0.32)Y\mid x\sim\Normal(|x|,0.3^2). The particle line uses 1200 prior samples with fixed seed, weighted by likelihood, and a Gaussian kernel of width 0.18. EKF differentiates ∣x∣|x| 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 π~(x)≥0\tilde\pi(x)\ge 0 be a density known up to its constant Z=∫π~(x) ⁣dxZ=\int\tilde\pi(x)\dd x, and qq a proposal covering the support of π~\tilde\pi. For Xi∼iidqX_i\overset{\mathrm{iid}}\sim q define wi=π~(Xi)/q(Xi)w_i=\tilde\pi(X_i)/q(X_i). By change of measure, Eq[w]=Z\E_q[w]=Z and Eq[wf]=ZEπ[f]\E_q[wf]=Z\E_\pi[f]. The self-normalized importance estimate is

μ^N=∑iwif(Xi)∑iwi,Z^N=1N∑iwi.\hat\mu_N=\frac{\sum_i w_i f(X_i)}{\sum_i w_i},\qquad \hat Z_N=\frac1N\sum_i w_i.

If Z>0Z>0 and relevant expectations are finite, the strong law applied to numerator and denominator yields almost sure convergence of μ^N\hat\mu_N to μ\mu. The ratio is generally biased at finite NN even if Z^N\hat Z_N is unbiased. With finite second moments and usual delta-method assumptions,

N(μ^N−μ)⇒N ⁣(0,Eq[w2(f−μ)2]Z2).\sqrt N(\hat\mu_N-\mu)\Rightarrow\Normal\!\left(0,\frac{\E_q[w^2(f-\mu)^2]}{Z^2}\right).

Variance also depends on ff, not only weights. A proposal ideal for one function may be poor for another. In finite arithmetic calculate ℓi=log⁡wi\ell_i=\log w_i, subtract max⁡iℓi\max_i\ell_i 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 AN=N−1∑iwif(Xi)A_N=N^{-1}\sum_iw_if(X_i) and BN=N−1∑iwiB_N=N^{-1}\sum_iw_i. Around (Zμ,Z)(Z\mu,Z), the differential of A/BA/B is ( ⁣dA−μ ⁣dB)/Z(\dd A-\mu\dd B)/Z. The linear term is therefore the mean of wi(f(Xi)−μ)/Zw_i(f(X_i)-\mu)/Z, 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

E[μ^N]−μ=−Eq[w2(f−μ)]NZ2+o(N−1).\E[\hat\mu_N]-\mu = -\frac{\E_q[w^2(f-\mu)]}{NZ^2}+o(N^{-1}).

Bias is not necessarily negative: it depends on correlation between weight and function. Required moments may also be infinite if qq has tails that are too light. Then neither the variance formula nor accuracy of order N−1/2N^{-1/2} is justified, even if the estimate appears stable in one run.

If all weights are equal, ESS is NN; 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: (∑iWi)2≤N∑iWi2(\sum_i W_i)^2\le N\sum_iW_i^2, and the lower from ∑iWi2≤(∑iWi)2=1\sum_iW_i^2\le(\sum_iW_i)^2=1. For example, four equal weights have ESS 4, whereas (1,0,0,0)(1,0,0,0) has ESS 1. If the threshold is N/2N/2, resampling occurs when concentration crosses that practical criterion, not because N/2N/2 is a universal mathematical boundary.

Sequential importance and genealogy

State XtX_t evolves according to ft(xt∣xt−1)f_t(x_t\mid x_{t-1}) and produces observed datum yty_t with density gt(yt∣xt)g_t(y_t\mid x_t). For the full trajectory, the proposal factors into q1(x1∣y1)∏t=2Tqt(xt∣x1:t−1,y1:t)q_1(x_1\mid y_1)\prod_{t=2}^Tq_t(x_t\mid x_{1:t-1},y_{1:t}). The ratio between joint target density and proposal gives the sequential importance sampling update:

wt(i)=wt−1(i)ft(xt(i)∣xt−1(i))gt(yt∣xt(i))qt(xt(i)∣x1:t−1(i),y1:t).w_t^{(i)}=w_{t-1}^{(i)}\frac{f_t(x_t^{(i)}\mid x_{t-1}^{(i)})g_t(y_t\mid x_t^{(i)})}{q_t(x_t^{(i)}\mid x_{1:t-1}^{(i)},y_{1:t})}.

For t=1t=1 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.

InteractiveWeights and ancestors
Normalized weight
12
ESS after possible resampling1.1
Maximum weight0.951
Distinct initial ancestors150
Move through time and enable adaptive resampling. Weights become equal after resampling, but the number of distinct initial ancestors can decrease. The vertical axis adapts to the maximum weight.

The figure’s model is xt=0.95xt−1+ϵtx_t=0.95x_{t-1}+\epsilon_t, ϵt∼N(0,0.42)\epsilon_t\sim\Normal(0,0.4^2), and yt=xt+ηty_t=x_t+\eta_t, ηt∼N(0,0.72)\eta_t\sim\Normal(0,0.7^2). The prior is N(0,4)\Normal(0,4) 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 NWiNW_i for particle ii. Multinomial resampling takes NN independent indices from the categorical distribution. Stratified resampling takes a uniform draw in each interval [j/N,(j+1)/N)[j/N,(j+1)/N); systematic uses one initial uniform and an equally spaced grid. Residual resampling first assigns ⌊NWi⌋\lfloor NW_i\rfloor copies and distributes the remainder according to normalized residuals.

InteractiveVariance of copy counts
00.20.40.60.81Multinomial0.981Stratified0Systematic0Copy variance
0.50
1
Particle weight0.500
Expected copies2.000
Choose a particle and change the first weight. Bars show empirical variances over 1000 independent resamples per scheme with a fixed seed. Comparison depends on weights and their order.

The figure defines four weights as (a,0.5(1−a),0.3(1−a),0.2(1−a))(a,0.5(1-a),0.3(1-a),0.2(1-a)). The three methods preserve expected copy count, but their dependencies differ. Multinomial count variance is exactly NWi(1−Wi)NW_i(1-W_i). 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 a=0.5a=0.5, 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 (4,0.5)(4,0.5) 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, qt=ftq_t=f_t. By cancellation, the increment is simply gt(yt∣xt)g_t(y_t\mid x_t). 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 qt(xt∣xt−1,yt)∝ft(xt∣xt−1)gt(yt∣xt)q_t(x_t\mid x_{t-1},y_t)\propto f_t(x_t\mid x_{t-1})g_t(y_t\mid x_t) 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 p(yt∣xt−1)=∫ft(xt∣xt−1)gt(yt∣xt) ⁣dxtp(y_t\mid x_{t-1})=\int f_t(x_t\mid x_{t-1})g_t(y_t\mid x_t)\dd x_t. Substituting it into the importance ratio makes the increment independent of new sample xtx_t 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 p(xt∣y1:t−1)p(x_t\mid y_{1:t-1}) propagates the previous belief; the filtered p(xt∣y1:t)p(x_t\mid y_{1:t}) multiplies it by gt(yt∣xt)g_t(y_t\mid x_t) and normalizes. The filtered distribution answers where the state is now using only available data. The smoothed p(xs∣y1:T)p(x_s\mid y_{1:T}) for s<Ts<T 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 p(y1:T)p(y_{1:T}) under conditionally unbiased offspring resampling and integrability conditions. Its logarithm is generally not unbiased: Jensen gives E[log⁡Z^]≤log⁡Z\E[\log\hat Z]\le\log Z 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 ftgtf_t g_t. By induction, the expectation of that unnormalized measure matches the joint measure of (Xt,y1:t)(X_t,y_{1:t}). Evaluating it at the constant function 1 gives evidence. This proof does not claim each random factor is separately unbiased or independent.

Specifically, denote γtN(φ)=Z^t∑iWt(i)φ(Xt(i))\gamma_t^N(\varphi)=\hat Z_t\sum_iW_t^{(i)}\varphi(X_t^{(i)}) and Qtφ(x)=∫ft(x′∣x)gt(yt∣x′)φ(x′) ⁣dx′Q_t\varphi(x)=\int f_t(x'\mid x)g_t(y_t\mid x')\varphi(x')\dd x'. Conditional on the previous system, both no resampling and resampling with expected counts NWiNW_i give E[γtN(φ)∣Ft−1]=γt−1N(Qtφ)\E[\gamma_t^N(\varphi)\mid\mathcal F_{t-1}]=\gamma_{t-1}^N(Q_t\varphi). 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 r(θ′∣θ)r(\theta'\mid\theta) is the proposal and Z^′\hat Z' the new estimate, acceptance probability is the minimum of 1 and

Z^′ p(θ′) r(θ∣θ′)Z^ p(θ) r(θ′∣θ).\frac{\hat Z'\,p(\theta')\,r(\theta\mid\theta')}{\hat Z\,p(\theta)\,r(\theta'\mid\theta)}.

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 h1∼N(0,σ2/(1−ϕ2))h_1\sim\Normal(0,\sigma^2/(1-\phi^2)), ht=ϕht−1+σϵth_t=\phi h_{t-1}+\sigma\epsilon_t and Yt∣ht∼N(0,eht)Y_t\mid h_t\sim\Normal(0,e^{h_t}), for ∣ϕ∣<1|\phi|<1. 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.

[ ]Bootstrap filter from scratchBrowser
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 (−0.99,0.99)(-0.99,0.99) and a symmetric normal proposal. At the boundary it rejects the proposal; it retains the previous estimate when rejecting.

[ ]Minimal PMMHBrowser
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 x1∼N(0,1)x_1\sim\Normal(0,1), xt=0.8xt−1+N(0,0.52)x_t=0.8x_{t-1}+\Normal(0,0.5^2) and yt=xt+N(0,0.72)y_t=x_t+\Normal(0,0.7^2), Kalman gives an exact reference. Compare mean squared error of the final filtered mean across independent seeds. The N−1/2N^{-1/2} rate is an asymptotic statement under assumptions, not a guarantee that every pair of sizes improves in any finite experiment.

[ ]Particles versus KalmanBrowser
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.

[ ]Compare with particlesLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericWeight concentration
Calculate ESS for normalized weights (0.5,0.2,0.2,0.1)(0.5, 0.2, 0.2, 0.1).
QuizAlways resample?
With uniform weights and distinct particles, why can multinomial resampling at every step worsen an estimate?
QuizVery precise measurements
If observation is very precise relative to transition, what problem does bootstrap have and what proposal mitigates it?
ProofUnnormalized measure
Prove: The bootstrap likelihood estimator is unbiased with conditionally unbiased resampling.
0
Let γtN(φ)=Z^t∑iWt(i)φ(Xt(i))\gamma_t^N(\varphi)=\hat Z_t\sum_iW_t^{(i)}\varphi(X_t^{(i)}). Assume integrability and a correct initial prior.

Step 1 of 3. Which resampling property is needed?

CodeSystematic resampling
Implement 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 (u+j)/N(u+j)/N, with index zero for the first particle.
def systematic_resample(weights, u):
  pass
Shift+Enter to run
CodeStable self-normalized importance sampling
Implement snis(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):
  pass
Shift+Enter to run

Summary

Key idea
The particle filter represents belief as a weighted empirical measure. The proposal determines where hypotheses are sought; weights correct differences from the model, and resampling redistributes effort without creating new information.
  • 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.