Foundations to Frontier
Tests
A. Mathematical Foundations › A5 Statistics › Bayesian statistics

MCMC: Metropolis–Hastings and Gibbs Sampling

When a posterior has no closed form and too many dimensions for a grid or importance sampling, build a Markov chain whose stationary distribution is the posterior, run it, and average. Metropolis–Hastings needs only the unnormalized log-posterior and an accept/reject rule; Gibbs sampling cycles through exact conditional distributions. You will tune step sizes (acceptance 20–50%), diagnose convergence with R-hat and effective sample size, see why strong correlations and curved ridges slow random walks, and fit a Bayesian logistic regression for grasp success with honest uncertainty.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Exploring a dark landscape

Imagine exploring hilly countryside at night with only a torch. You want to spend time in places in proportion to how high they are. Rule: take a random step. If it’s uphill, go. If it’s downhill, go only sometimes, more rarely the steeper the drop. After a long walk, a record of where you’ve been is a map of the hills.

That’s Markov chain Monte Carlo (MCMC). The landscape is the posterior. You never need its full shape, only “how high is it here compared with there?”. The list of visited places is a set of samples you can average.

Wander the posterior: Metropolis and Gibbs
target: sampler:
acceptance rate 42.5% · ESS for x₁ after burn-in ≈ 16 of 1201 draws · x₁ mean 0.01 (true 0)
Blue shading: the target density. Orange: the chain, starting at the uncoloured dot. A tiny step is almost always accepted but crawls. A huge step is almost always rejected and sits still. Mixing is best near 20–50% acceptance. Gibbs moves along the axes, so a strongly correlated target forces tiny zig-zags. The banana's curved ridge defeats a fixed-size random walk, which motivates Hamiltonian Monte Carlo (next topic).
Why engineers care

MCMC is how Bayesian models with many parameters are fitted in practice: calibration of physics models, hierarchical reliability models, Bayesian logistic regression, and uncertainty in SLAM back-ends. Knowing how to tune it and when to distrust it is essential.

📝 Quick check (Level 0)
0/3 answered
  1. 1. MCMC produces…
  2. 2. A downhill step in Metropolis is…
  3. 3. To run Metropolis you need the posterior…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Metropolis–Hastings

From the current xx, propose x′∼q(⋅∣x)x'\sim q(\cdot\mid x), and accept with probability

α=min⁡(1,p(x′)q(x∣x′)p(x)q(x′∣x))\alpha = \min\Big(1, \frac{p(x')q(x\mid x')}{p(x)q(x'\mid x)}\Big)

Otherwise stay at xx. Repeat the current state when you reject: that matters for correctness. With a symmetric random-walk proposal x′=x+s zx' = x + s\,z, the qq terms cancel. Only ratios of pp appear, so the normalizing constant (the evidence) is never needed. Work with log-densities to avoid underflow.

Gibbs sampling

Update one block of variables at a time from its full conditional p(xj∣x−j)p(x_j\mid x_{-j}). Every move is accepted. It’s natural when conditionals are conjugate: for normal data, μ∣σ2\mu\mid\sigma^2 is normal and σ2∣μ\sigma^2\mid\mu is inverse-gamma. Gibbs is a special case of MH with acceptance probability 1.

Using the output

Discard a burn-in period, then average: E[f(θ)∣x]≈1S∑f(θ(s))\mathbb E[f(\theta)\mid x]\approx\frac1S\sum f(\theta^{(s)}). Quantiles of the draws give credible intervals, and pushing draws through a model gives predictive samples.

📝 Quick check (Level 1)
0/3 answered
  1. 1. p(new)/p(old) = 0.3 with a symmetric proposal: acceptance probability?
  2. 2. When an MH proposal is rejected, the chain…
  3. 3. Gibbs sampling updates variables from their…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 45 minUndergraduate students and practising engineers.

Tuning and the step-size trade-off

  • Too small a step: nearly every proposal is accepted, but the chain crawls, so autocorrelation is huge and the ESS tiny.
  • Too large: nearly every proposal is rejected, and the chain sits still.

For Gaussian-like targets in high dimensions, the optimal random-walk acceptance rate is about 0.234 (Roberts, Gelman and Gilks, 1997). Scale the proposal like the posterior covariance, which adaptive MH learns during warm-up (Haario et al., 2001).

Diagnostics

  • Trace plots: several chains from dispersed starts should overlap.
  • R̂ (Gelman–Rubin): compares between-chain and within-chain variance. Values near 1 indicate convergence, and the modern rule is R^<1.01\hat R<1.01 with rank normalization (Vehtari et al., 2021).
  • Effective sample size: ESS=S/(1+2∑kρk)\text{ESS} = S/(1 + 2\sum_k\rho_k). Report it, and the Monte Carlo SE σ/ESS\sigma/\sqrt{\text{ESS}}.

Diagnostics can only detect failure. A chain stuck in one mode of a multimodal posterior can look perfectly converged.

When MCMC struggles

  • Strong correlations: Gibbs takes tiny axis-aligned steps, with lag-1 autocorrelation about ρ2\rho^2. Reparameterize or update blocks jointly.
  • Curved ridges (bananas) and funnels (hierarchical models): a fixed-size random walk is either too big in the narrow parts or too small in the wide ones. Hamiltonian Monte Carlo uses gradients to follow the geometry (A5.2-8).
  • Multimodality: use tempering, multiple dispersed chains, or reparameterize.
🐍 Exercise 1: random-walk Metropolis, Gibbs and diagnostics
Sample the posterior of (μ, log σ) for normal data with random-walk Metropolis at three step sizes (4 chains each). Compare acceptance, ESS and R̂, and check the posterior mean. Then run a Gibbs sampler with semi-conjugate conditionals and confirm it agrees.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The asymptotically optimal acceptance rate for random-walk MH is about…
  2. 2. R̂ well above 1 means…
  3. 3. Gibbs on two variables with correlation 0.99 mixes…

Level 3: Advanced

★★★★☆ Advanced⏱ 40 minGraduate level, with full derivations and proofs.

Why Metropolis–Hastings is correct

The MH transition kernel is K(x→x′)=q(x′∣x)α(x,x′)K(x\to x') = q(x'\mid x)\alpha(x, x') for x′≠xx'\ne x. Then

p(x)q(x′∣x)α(x,x′)=min⁡(p(x)q(x′∣x), p(x′)q(x∣x′))p(x)q(x'\mid x)\alpha(x, x') = \min\big(p(x)q(x'\mid x),\ p(x')q(x\mid x')\big)

which is symmetric in x,x′x, x'. That’s detailed balance, so pp is stationary (A4.4-1). With irreducibility and aperiodicity (true for a random walk with positive density everywhere), the chain converges to pp from any start, and averages obey the ergodic theorem: 1S∑f(θ(s))→Epf\frac1S\sum f(\theta^{(s)})\to\mathbb E_pf almost surely. ∎

Why Gibbs is correct

One Gibbs update of xjx_j is an MH step with proposal p(xj∣x−j)p(x_j\mid x_{-j}). The acceptance ratio p(x′)p(xj∣x−j)p(x)p(xj′∣x−j)=p(x−j)p(x−j)=1\frac{p(x')p(x_j\mid x_{-j})}{p(x)p(x_j'\mid x_{-j})} = \frac{p(x_{-j})}{p(x_{-j})} = 1. Each update preserves pp, so their composition does too.

The Monte Carlo CLT for Markov chains

For geometrically ergodic chains, S(fˉ−Ef)→N(0,σf2(1+2∑ρk))\sqrt S(\bar f - \mathbb Ef)\to\mathcal N(0, \sigma_f^2(1 + 2\sum\rho_k)). That’s why the ESS and batch-means SEs (A5.1-2) are the right uncertainty for MCMC estimates.

Exercise 3.1: Show that the MH acceptance with a symmetric proposal is min(1, p(x’)/p(x))

With q(x∣x′)=q(x′∣x)q(x\mid x') = q(x'\mid x) the proposal terms cancel in the Hastings ratio, leaving min⁡(1,p(x′)/p(x))\min(1, p(x')/p(x)). That’s the original Metropolis rule (Metropolis et al., 1953).

📝 Quick check (Level 3)
0/3 answered
  1. 1. MH's correctness rests on…
  2. 2. Gibbs updates are MH steps with acceptance…
  3. 3. The MCMC standard error uses…

Level 4: Expert

★★★★★ Expert⏱ 45 minResearchers: original papers and open problems.

Grasp success as Bayesian logistic regression

Model the probability that a grasp succeeds as σ(w0+w1 force+w2 width)\sigma(w_0 + w_1\,\text{force} + w_2\,\text{width}), with 60 trials. The posterior over ww has no closed form, so random-walk MH with 4 chains gives R^<1.05\hat R<1.05. For a new situation (22 N on a 7.5 cm object) it reports a 90% band for the success probability, not a single number. A planner can use the band: it can require the lower bound to exceed a threshold before attempting a risky grasp, or choose informative trials where the band is widest (active learning). Probabilistic programming systems (Stan, PyMC, NumPyro) automate this with HMC.

🐍 Exercise 2 (research): Bayesian logistic regression for grasp success
Simulate 60 grasp trials with force and width. Run 4 random-walk MH chains on the logistic-regression posterior (normal prior), check R̂ and acceptance, and report the posterior predictive success probability with a 90% band for a new grasp.

MCMC in AI, robotics and aerospace

  • Probabilistic programming. Stan, PyMC and NumPyro make MCMC (mostly NUTS) a routine tool for calibration and hierarchical models (Carpenter et al., 2017).
  • Bayesian calibration of simulators. Kennedy–O’Hagan calibration of physics models (thermal, aerodynamic, battery) with discrepancy terms (Kennedy and O’Hagan, 2001).
  • SLAM uncertainty and multi-hypothesis data association have used MCMC over associations (Ranganathan, Menegatti and Dellaert, 2006).
  • Inverse problems in planetary science. Recovering interior structure or atmospheric profiles from remote measurements with MCMC over physical parameters.
  • Bayesian neural networks via stochastic-gradient MCMC (SGLD, SGHMC) for uncertainty in perception and control (Welling and Teh, 2011; Chen, Fox and Guestrin, 2014).

References

  1. N. Metropolis, A. Rosenbluth, M. Rosenbluth, A. Teller, E. Teller (1953). “Equation of state calculations by fast computing machines.” Journal of Chemical Physics, 21(6).
  2. W. K. Hastings (1970). “Monte Carlo sampling methods using Markov chains and their applications.” Biometrika, 57(1).
  3. S. Geman, D. Geman (1984). “Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images.” IEEE TPAMI, 6(6).
  4. A. Gelfand, A. Smith (1990). “Sampling-based approaches to calculating marginal densities.” JASA, 85(410).
  5. G. Roberts, A. Gelman, W. Gilks (1997). “Weak convergence and optimal scaling of random walk Metropolis algorithms.” Annals of Applied Probability, 7(1).
  6. H. Haario, E. Saksman, J. Tamminen (2001). “An adaptive Metropolis algorithm.” Bernoulli, 7(2).
  7. A. Gelman, D. Rubin (1992). “Inference from iterative simulation using multiple sequences.” Statistical Science, 7(4).
  8. A. Vehtari, A. Gelman, D. Simpson, B. Carpenter, P.-C. Bürkner (2021). “Rank-normalization, folding, and localization: an improved R-hat.” Bayesian Analysis, 16(2).
  9. B. Carpenter et al. (2017). “Stan: a probabilistic programming language.” Journal of Statistical Software, 76(1).
  10. M. Kennedy, A. O’Hagan (2001). “Bayesian calibration of computer models.” JRSS B, 63(3).