Probability and EstimationPart 4 of 5Intermediate · Updated December 1, 2026

Importance Sampling and Metropolis–Hastings

Monte Carlo simulation assumes that samples can be drawn from the distribution being averaged over. A Bayesian posterior is usually known only as likelihood times prior, with an unknown normalising constant, and cannot be sampled directly. This tutorial covers the two standard remedies: importance sampling and Metropolis–Hastings.

Sample from something else and correct for the difference

Bayes’ rule gives the posterior over parameters θ\theta as

π(θ)=π~(θ)Z,π~(θ)=p(D∣θ) p(θ),Z=∫π~(θ) dθ\pi(\theta) = \frac{\tilde\pi(\theta)}{Z}, \qquad \tilde\pi(\theta) = p(D \mid \theta)\, p(\theta), \qquad Z = \int \tilde\pi(\theta)\, \mathrm{d}\theta

Evaluating π~\tilde\pi at a point is usually cheap; the evidence ZZ is an integral over the whole parameter space. Most quantities of interest (means, variances, credible intervals, predictive probabilities) are expectations,

Eπ[f]=∫f(θ) π~(θ) dθ∫π~(θ) dθ\mathbb{E}_\pi[f] = \frac{\int f(\theta)\, \tilde\pi(\theta)\, \mathrm{d}\theta}{\int \tilde\pi(\theta)\, \mathrm{d}\theta}

A grid can compute both integrals in two or three dimensions but not beyond, and plain Monte Carlo needs draws from π\pi. Both methods below draw from a distribution that can be sampled and correct for the difference: importance sampling by weighting each draw once, Metropolis–Hastings by accepting or rejecting each move of a random walk.

Importance sampling with self-normalised weights

The importance sampling section of the Monte Carlo tutorial used weights w=p/qw = p/q, which require the normalised density. With only π~\tilde\pi available, the weights are computed unnormalised and divided by their sum:

xi∼q,wi=π~(xi)q(xi),E^π[f]=∑iwi f(xi)∑iwix_i \sim q, \qquad w_i = \frac{\tilde\pi(x_i)}{q(x_i)}, \qquad \hat{\mathbb{E}}_\pi[f] = \frac{\sum_i w_i\, f(x_i)}{\sum_i w_i}

ZZ appears in every wiw_i and cancels. This self-normalised estimator has a bias of order 1/N1/N, smaller than its 1/N1/\sqrt N noise, so it is consistent. Since Eq[π~/q]=Z\mathbb{E}_q[\tilde\pi/q] = Z, the mean weight Z^=1N∑iwi\hat Z = \frac{1}{N} \sum_i w_i is also an unbiased estimate of the evidence, which is needed for model comparison and which most MCMC methods do not provide.

Choosing q. The weights stay bounded only if qq matches the scale of π\pi and has heavier tails. A proposal narrower than π\pi rarely visits its edges; a much wider one places most draws where π\pi is negligible; one with lighter tails gives weights π/q\pi/q that grow without bound. A common recipe is the Laplace approximation, a Gaussian at the posterior mode with covariance from the curvature there, inflated slightly and given heavy tails, for example as a Student-tt.

Diagnosing it. The effective sample size uses only ratios of weights, so it applies unchanged:

Neff=(∑iwi)2∑iwi2,1≤Neff≤NN_{\text{eff}} = \frac{\left(\sum_i w_i\right)^2}{\sum_i w_i^2}, \qquad 1 \le N_{\text{eff}} \le N

It should be reported with the largest normalised weight max⁡iwi/∑jwj\max_i w_i / \sum_j w_j; if one draw in ten thousand carries 30% of the mass, the estimate is dominated by that draw.

When q≈πq \approx \pi, importance sampling is very efficient. The draws are independent, so there is no burn-in or autocorrelation; they can be evaluated in parallel; nothing needs tuning once qq is fixed; and Z^\hat Z is obtained at no extra cost.

Importance sampling efficiency decays exponentially with dimension

Consider the most favourable case: target π=N(0,Id)\pi = \mathcal{N}(0, I_d) and proposal q=N(0,s2Id)q = \mathcal{N}(0, s^2 I_d), correct in centre and shape and wrong only in scale. Both densities factorise over coordinates, so the weight is a product of dd independent one-dimensional weights. In one dimension, with weights normalised so that Eq[w]=1\mathbb{E}_q[w] = 1,

Eq[w2]=∫π(x)2q(x) dx=s22s2−1\mathbb{E}_q[w^2] = \int \frac{\pi(x)^2}{q(x)}\, \mathrm{d}x = \frac{s^2}{\sqrt{2s^2 - 1}}

which is finite only for s2>1/2s^2 > 1/2. For large NN, Neff/N→1/Eq[w2]N_{\text{eff}}/N \to 1/\mathbb{E}_q[w^2], and over dd coordinates the second moments multiply:

NeffN≈ρ(s)d,ρ(s)=2s2−1s2≤1\frac{N_{\text{eff}}}{N} \approx \rho(s)^d, \qquad \rho(s) = \frac{\sqrt{2s^2 - 1}}{s^2} \le 1

with equality only at s=1s = 1. Any mismatch gives ρ<1\rho < 1 and an exponential decay. A proposal 20% too wide, s=1.2s = 1.2, gives ρ≈0.952\rho \approx 0.952, a loss of under 5% per dimension:

dimensionNeff/NN_{\text{eff}}/N at s=1.2s = 1.2at s=1.5s = 1.5
195%83%
1061%16%
508.6%0.01%
1000.74%10−810^{-8}

At d=100d = 100 the s=1.2s = 1.2 proposal needs about 130 draws per effective sample, and the s=1.5s = 1.5 proposal about a hundred million. An offset centre has the same effect: for q=N(δ,1)q = \mathcal{N}(\delta, 1) against N(0,1)\mathcal{N}(0, 1), Eq[w2]=eδ2\mathbb{E}_q[w^2] = e^{\delta^2}, so an offset δ\delta in every coordinate gives Neff/N≈e−dδ2N_{\text{eff}}/N \approx e^{-d\delta^2}. In practice scale, centre and shape are all slightly wrong in every direction, and the factors compound.

The underlying reason is that in high dimension almost all of a distribution’s mass lies in a thin shell, the typical set, and two distributions that differ slightly in every coordinate have typical sets that barely overlap. Draws from qq‘s shell rarely land in π\pi‘s, and the few that do take nearly all the weight.

Metropolis–Hastings builds a random walk whose long-run distribution is the posterior

Metropolis–Hastings gives up independent draws. It constructs a Markov chain x0,x1,x2,…x_0, x_1, x_2, \dots whose stationary distribution is π\pi, so that after enough steps its states are correlated draws from π\pi. Each step:

  1. From the current state xx, propose x′∼q(⋅∣x)x' \sim q(\cdot \mid x).
  2. Accept x′x' with probability α(x,x′)\alpha(x, x'), given below.
  3. Otherwise stay at xx and record xx again.
α(x,x′)=min⁡ ⁣(1,  π~(x′) q(x∣x′)π~(x) q(x′∣x))\alpha(x, x') = \min\!\left(1,\; \frac{\tilde\pi(x')\, q(x \mid x')}{\tilde\pi(x)\, q(x' \mid x)}\right)

ZZ cancels in the ratio, so only π~\tilde\pi is needed. Recording the current state again on rejection is required: dropping the repeats biases the chain away from high-density regions, where rejections are most frequent.

Why π is stationary. For x′≠xx' \neq x the transition density is P(x→x′)=q(x′∣x) α(x,x′)P(x \to x') = q(x' \mid x)\, \alpha(x, x'), so

π(x) P(x→x′)=1Zmin⁡ ⁣(π~(x) q(x′∣x),  π~(x′) q(x∣x′))\pi(x)\, P(x \to x') = \frac{1}{Z}\min\!\big(\tilde\pi(x)\, q(x' \mid x),\; \tilde\pi(x')\, q(x \mid x')\big)

The right-hand side is symmetric in xx and x′x', which is detailed balance: π(x)P(x→x′)=π(x′)P(x′→x)\pi(x) P(x \to x') = \pi(x') P(x' \to x). Integrating over xx shows that a chain distributed as π\pi remains so after one step. If the chain can reach every region where π>0\pi > 0 and is not periodic, it converges to π\pi from any start, and averages along it converge to Eπ[f]\mathbb{E}_\pi[f].

Random-walk Metropolis. The most common proposal is x′=x+σεx' = x + \sigma \varepsilon with ε∼N(0,I)\varepsilon \sim \mathcal{N}(0, I). It is symmetric, so the qq terms cancel: an uphill move is always accepted and a downhill move is accepted with probability π~(x′)/π~(x)\tilde\pi(x')/\tilde\pi(x). The step size σ\sigma is the only parameter. In practice log⁡π~\log \tilde\pi is computed, for numerical stability.

Local moves make the cost polynomial in dimension

Because the moves are local, a chain in the typical set stays there and does not have to find it by chance. The cost appears in the step size instead: for a smooth dd-dimensional target the step must shrink as σ∝d−1/2\sigma \propto d^{-1/2} to keep a reasonable acceptance rate, and the chain then needs on the order of dd steps to cross the target. The cost per effectively independent sample therefore grows as O(d)\mathcal{O}(d). On the isotropic Gaussian at the optimal step 2.38/d2.38/\sqrt d, ESS/N≈0.33/d\text{ESS}/N \approx 0.33/d, or 0.33% at d=100d = 100: five orders of magnitude above the s=1.5s = 1.5 importance sampler, though still below the s=1.2s = 1.2 one (0.74%). The two curves cross near d≈120d \approx 120, beyond which the gap grows exponentially.

The price is correlation between consecutive states. The integrated autocorrelation time

τ=1+2∑k=1∞ρk,ESS=Nτ\tau = 1 + 2\sum_{k=1}^{\infty} \rho_k, \qquad \text{ESS} = \frac{N}{\tau}

where ρk\rho_k is the autocorrelation of f(xt)f(x_t) at lag kk, gives the number of steps per independent sample. The empirical ρk\rho_k are noisy at large lags, so they are summed in adjacent pairs up to the first negative pair (Geyer’s initial positive sequence).

  • Burn-in. The early steps reflect the starting point rather than π\pi and are discarded.
  • Tuning. A step that is too small is almost always accepted but moves slowly; one that is too large is almost always rejected. Both give large τ\tau. For roughly Gaussian targets the optimal acceptance rate is about 0.44 in one dimension and about 0.234 in high dimension; adaptive schemes tune σ\sigma, and a proposal covariance, during burn-in.
  • Shape. An isotropic step on a correlated or curved target must be as small as the narrowest direction. Matching the proposal covariance to the posterior’s, or reparameterising until the posterior is roughly round, often matters most.

The d−1/2d^{-1/2} step scaling belongs to the random walk, not to Markov chains in general. Hamiltonian Monte Carlo uses the gradient of log⁡π~\log\tilde\pi to propose long moves along the target’s contours that are still accepted with high probability; its cost per independent sample grows roughly as d1/4d^{1/4} gradient evaluations. Where gradients are available, for instance through automatic differentiation, it is the default in modern probabilistic programming tools, with the same accept/reject step keeping it exact.

Example: the two samplers on two- and high-dimensional targets

Figure 1 runs both samplers on the same targets. In two dimensions, importance sampling degrades when ss moves far from 1 and Metropolis–Hastings degrades when its step is very small or very large; on the curved banana target both struggle, because neither proposal resembles it. The bottom panel shows the dimension dependence derived above.

Random numbers
N = 800Neff 239 (30%)Heaviest draw carries 0.7% of the weightẐ 2.70 vs true Z 2.74Ê[x₁, x₂] (0.07, 0.03) vs (0, 0)
IS at d = 100: 9.7e-7%MH at d = 100 (theory): 0.3%Simulating MH chains…
Figure 1.Importance sampling and random-walk Metropolis–Hastings on a 2-D target known only up to a constant. IS mode: each dot is a draw from q = N(0, s²I), sized and shaded by its normalised weight; Ẑ tracks the true normalising constant only while N_eff remains large. MH mode: the chain starts in the tail (circled) and the shaded burn-in is discarded; a small step accepts nearly every proposal but moves slowly, a large step is mostly rejected and the trace shows long flat runs, and an acceptance rate between about a third and a half gives the highest ESS. On the banana target, no single isotropic q fits both arms and the tip, and MH's fixed step moves slowly along the curve. Bottom panel: on a d-dimensional standard Gaussian, IS's N_eff/N from the formula above, and MH's ESS/N simulated at the optimal step 2.38/√d, with the 0.33/d asymptote dashed.

Assumptions and where each method fails

Importance sampling suits problems with a good available proposal: low or moderate dimension, a nearly Gaussian posterior, a cheap Laplace or variational approximation, or a need for ZZ. It also suits expensive densities on parallel hardware. It fails when qq is a guess in more than a few dozen dimensions, and the failure is often silent: a collapsed estimate can look stable between runs because the same region dominates each time.

Metropolis–Hastings suits posteriors of unknown shape, substantial dimension, or no good global approximation, and needs only log⁡π~\log\tilde\pi. Its costs are sequential steps, correlated output, burn-in, tuning, and no direct estimate of ZZ. The methods also combine: an MCMC run can supply samples to fit an importance proposal, and an importance proposal can serve as the independence proposal in a Metropolis–Hastings step.

Summary

  • Both methods need only the unnormalised posterior π~\tilde\pi; the evidence ZZ cancels.
  • Importance sampling gives independent draws and an estimate of ZZ, but its effective sample size decays as ρd\rho^d for any proposal mismatch.
  • Random-walk Metropolis–Hastings gives correlated draws at a cost of order dd per independent sample; its effective sample size follows from the autocorrelation time.
  • Gradient-based Hamiltonian Monte Carlo reduces that cost further when gradients are available.

The next tutorial turns from estimating a posterior to acting on one.

References

  • Metropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H., & Teller, E. (1953). Equation of state calculations by fast computing machines. The Journal of Chemical Physics, 21(6), 1087–1092. doi:10.1063/1.1699114
  • Hastings, W. K. (1970). Monte Carlo sampling methods using Markov chains and their applications. Biometrika, 57(1), 97–109. doi:10.1093/biomet/57.1.97
  • Roberts, G. O., Gelman, A., & Gilks, W. R. (1997). Weak convergence and optimal scaling of random walk Metropolis algorithms. The Annals of Applied Probability, 7(1), 110–120. doi:10.1214/aoap/1034625254
  • Geyer, C. J. (1992). Practical Markov chain Monte Carlo. Statistical Science, 7(4), 473–483. doi:10.1214/ss/1177011137
  • Neal, R. M. (2011). MCMC using Hamiltonian dynamics. In S. Brooks, A. Gelman, G. L. Jones, & X.-L. Meng (Eds.), Handbook of Markov Chain Monte Carlo. CRC Press. arXiv:1206.1901