Simple Algorithm
Machine Learning · Convergence · 28 min

MCMC: Metropolis–Hastings & Gibbs

Random walks whose long-run distribution is the posterior.

Why should a random walk that sometimes refuses to move end up distributed exactly like your posterior? This lesson proves that it does, then turns to the harder questions: how fast the walk forgets where it started, how big its steps should be (the source of the famous 0.234), what Gibbs sampling really is, and why no diagnostic can promise that a chain has seen the whole distribution.

What you’ll learn

  • Prove that the Metropolis–Hastings kernel is reversible with respect to π\pi, and state the conditions under which ergodic averages converge and satisfy a central limit theorem.
  • Show that Gibbs updates are Metropolis–Hastings moves accepted with probability 1, and derive the Gibbs sampler's autocorrelation for a correlated Gaussian.
  • Prove a geometric convergence bound for the independence sampler by a minorization argument.
  • Derive the optimal scaling of random-walk Metropolis (acceptance about 0.234, proposal variance proportional to 1/d1/d) from its diffusion limit.
  • Relate mixing time to the spectral gap and to bottlenecks, and explain what R^\hat R and the effective sample size can and cannot detect.

Markov chains on general state spaces

Invariance alone does not make a chain converge: it must also be able to reach every region (π\pi-irreducible: from any start, every set of positive π\pi-probability is reached with positive probability) and must not cycle deterministically through disjoint regions (aperiodic). Then the standard theory applies (see Roberts & Rosenthal, 2004).

The factor τf=1+2∑kρk\tau_f=1+2\sum_k\rho_k is the integrated autocorrelation time: NN correlated samples estimate Eπf\E_\pi f as well as N/τfN/\tau_f independent ones, which is the effective sample size. A CLT can fail outright for a valid sampler. An independence sampler whose proposal has lighter tails than the target rejects so persistently in the tails that, for an exponential target with an exponential proposal of at least twice the rate, the identity function has no N\sqrt N central limit theorem at all: the chain is not geometrically ergodic, and its averages still converge, but not at the 1/N1/\sqrt N rate.

Metropolis–Hastings is correct, and the Metropolis choice is best

DerivationProof
  1. π(x) q(x,y) α(x,y)=min⁡(π(x)q(x,y), π(y)q(y,x))\pi(x)\,q(x,y)\,\alpha(x,y)=\min\big(\pi(x)q(x,y),\ \pi(y)q(y,x)\big)

    For x≠yx\ne y the kernel has density q(x,y)α(x,y)q(x,y)\alpha(x,y). Multiply by π(x)\pi(x) and push π(x)q(x,y)\pi(x)q(x,y) inside the minimum:

  2. π(dx)P(x,dy)=π(dy)P(y,dx)\pi(dx)P(x,dy)=\pi(dy)P(y,dx)

    The right side is symmetric in xx and yy, so the off-diagonal flows balance. The rejection part π(dx) r(x) δx(dy)\pi(dx)\,r(x)\,\delta_x(dy) lives on the diagonal x=yx=y, where it is trivially symmetric:

  3. ∫Xπ(dx)P(x,A)=∫Aπ(dy)∫XP(y,dx)=π(A)\int_{\mathcal X}\pi(dx)P(x,A)=\int_A\pi(dy)\int_{\mathcal X}P(y,dx)=\pi(A)

    Integrate over x∈Xx\in\mathcal X and use ∫P(y,dx)=1\int P(y,dx)=1. Irreducibility and aperiodicity hold under mild conditions, for instance for a Gaussian random walk on a target with a continuous positive density, so the convergence theorem applies:

Detailed balance does not single out this acceptance rule: Barker's rule π(y)q(y,x)π(x)q(x,y)+π(y)q(y,x)\frac{\pi(y)q(y,x)}{\pi(x)q(x,y)+\pi(y)q(y,x)} also satisfies it. Peskun (1973) showed, on finite state spaces, that among such rules the Metropolis–Hastings choice yields the smallest asymptotic variance for every function: it makes every off-diagonal transition probability as large as detailed balance allows, so the chain wastes the fewest steps standing still. Tierney (1998) extended this ordering of reversible kernels to general state spaces.

The proposal is where the art lies. Three classical choices:

  • Random walk: y=x+σzy=x+\sigma\mathbf z; symmetric, so α=min⁡(1,π(y)/π(x))\alpha=\min(1,\pi(y)/\pi(x)). Robust, but local.
  • Independence sampler: q(x,y)=g(y)q(x,y)=g(y), a fixed approximation of π\pi (say, a heavy-tailed fit at the mode). Then α=min⁡(1,w(y)w(x))\alpha=\min\big(1,\frac{w(y)}{w(x)}\big) with w=π/gw=\pi/g: a Markov-chain version of importance sampling.
  • Gradient-based: Langevin and Hamiltonian proposals use ∇log⁡π\nabla\log\pi (Hamiltonian Monte Carlo).
DerivationProof of the bound by minorization
  1. P(x,dy) ≥ 1M π(dy)for every xP(x,dy)\ \ge\ \frac1M\,\pi(dy)\qquad\text{for every }x

    For y≠xy\ne x the chain moves to yy with density g(y)min⁡(1,π(y)g(x)π(x)g(y))=min⁡(g(y), π(y)g(x)π(x))g(y)\min\big(1,\frac{\pi(y)g(x)}{\pi(x)g(y)}\big)=\min\big(g(y),\,\pi(y)\frac{g(x)}{\pi(x)}\big). Both arguments are at least π(y)/M\pi(y)/M, because g≥π/Mg\ge\pi/M everywhere:

  2. ∥Pn(x,⋅)−π∥TV ≤ Pr⁡(no joint jump in n steps)=(1−1M)n\norm{P^n(x,\cdot)-\pi}_{\mathrm{TV}}\ \le\ \Pr(\text{no joint jump in }n\text{ steps})=\Big(1-\frac1M\Big)^n

    So P=1Mπ+(1−1M)RP=\frac1M\pi+\big(1-\frac1M\big)R for some Markov kernel RR. Run a copy from xx and a copy started in π\pi, coupled so that at each step, with probability 1/M1/M, both jump to the same draw from π\pi. After that they move together, and the copy from π\pi stays distributed as π\pi. The coupling inequality bounds the distance by the probability of not having met:

Check your understanding

An independence sampler uses a proposal with sup⁡yπ(y)/g(y)=M=4\sup_y\pi(y)/g(y)=M=4. After 10 iterations, what does the theorem guarantee about the total-variation distance to π\pi, from any start?

  1. At most 0.250.25
  2. At most 4−10≈10−64^{-10}\approx10^{-6}
  3. At most about 0.0560.056
  4. Nothing, unless the chain started in π\pi
Show the answer

C. At most about 0.0560.056

(1−1/M)10=0.7510≈0.056(1-1/M)^{10}=0.75^{10}\approx0.056. The bound holds uniformly over starting points, which makes this chain uniformly ergodic. A poor proposal (large MM) makes the guaranteed rate 1−1/M1-1/M close to 1.

Gibbs sampling is Metropolis–Hastings

A Gibbs update of coordinate jj draws yj∼π(⋅∣x−j)y_j\sim\pi(\cdot\mid x_{-j}) and keeps y−j=x−jy_{-j}=x_{-j}. Introduced for image restoration with Gibbs random fields by Geman & Geman (1984), and brought into Bayesian statistics by Gelfand & Smith (1990), with data augmentation (Tanner & Wong, 1987) as a close relative, it is a special case of Metropolis–Hastings.

DerivationThe acceptance probability of a Gibbs move is 1
  1. π(y) q(y,x)π(x) q(x,y)=π(y−j) π(yj∣y−j)  π(xj∣y−j)π(x−j) π(xj∣x−j)  π(yj∣x−j)\frac{\pi(y)\,q(y,x)}{\pi(x)\,q(x,y)}=\frac{\pi(y_{-j})\,\pi(y_j\mid y_{-j})\;\pi(x_j\mid y_{-j})}{\pi(x_{-j})\,\pi(x_j\mid x_{-j})\;\pi(y_j\mid x_{-j})}

    The proposal density is q(x,y)=π(yj∣x−j)q(x,y)=\pi(y_j\mid x_{-j}), and the reverse move has q(y,x)=π(xj∣y−j)q(y,x)=\pi(x_j\mid y_{-j}). Factor π(x)=π(x−j)π(xj∣x−j)\pi(x)=\pi(x_{-j})\pi(x_j\mid x_{-j}), and likewise for yy:

  2. π(y) q(y,x)π(x) q(x,y)=1\frac{\pi(y)\,q(y,x)}{\pi(x)\,q(x,y)}=1

    Since y−j=x−jy_{-j}=x_{-j}, every factor cancels. Each update is reversible; a random-scan sampler (pick jj at random) is reversible too, while a systematic scan (j=1,…,dj=1,\dots,d in order) is a composition of reversible kernels: π\pi-invariant, but not reversible in general.

DerivationHow correlation slows Gibbs: the bivariate Gaussian
  1. xt+1=ρ yt+1−ρ2 ε′=ρ2xt+ρ1−ρ2 ε+1−ρ2 ε′x_{t+1}=\rho\,y_t+\sqrt{1-\rho^2}\,\varepsilon'=\rho^2x_t+\rho\sqrt{1-\rho^2}\,\varepsilon+\sqrt{1-\rho^2}\,\varepsilon'

    Take (x,y)(x,y) standard bivariate Gaussian with correlation ρ\rho. The full conditionals are x∣y∼N(ρy,1−ρ2)x\mid y\sim\mathcal N(\rho y,1-\rho^2) and y∣x∼N(ρx,1−ρ2)y\mid x\sim\mathcal N(\rho x,1-\rho^2). Composing one systematic sweep, with independent standard normals ε,ε′\varepsilon,\varepsilon':

  2. ESSN=1−ρ21+ρ2\frac{\mathrm{ESS}}N=\frac{1-\rho^2}{1+\rho^2}

    So the xx-chain is AR(1) with coefficient ρ2\rho^2 (its innovation variance 1−ρ41-\rho^4 keeps the stationary variance at 1). Its autocorrelations are ρ2k\rho^{2k}, and the effective sample size per sweep follows:

Predict before you look

With correlation ρ=0.99\rho=0.99, what percentage of Gibbs sweeps are effectively independent samples of xx?

Show the answer

1 %

(1−0.9801)/(1+0.9801)=0.0199/1.9801≈0.010(1-0.9801)/(1+0.9801)=0.0199/1.9801\approx0.010, about 1%. With ρ=0.9\rho=0.9 it is about 10.5%. Strong posterior correlation is why practitioners block correlated parameters (update them jointly), reparameterize to reduce correlation, or collapse (integrate parameters out analytically, as in the collapsed sampler for LDA).

Optimal scaling: where 0.234 comes from

DerivationProof sketch
  1. Wd=∑i=1d[log⁡f(xi+σzi)−log⁡f(xi)]≈ℓd∑izi(log⁡f)′(xi)+ℓ22d∑izi2(log⁡f)′′(xi)W_d=\sum_{i=1}^d\big[\log f(x_i+\sigma z_i)-\log f(x_i)\big]\approx\frac{\ell}{\sqrt d}\sum_iz_i(\log f)'(x_i)+\frac{\ell^2}{2d}\sum_iz_i^2(\log f)''(x_i)

    With step σ=ℓ/d\sigma=\ell/\sqrt d, the log acceptance ratio is a sum over coordinates. Taylor-expand each term to second order in σ\sigma:

  2. Wd ⇒ W∼N(−s22, s2),s=ℓIW_d\ \Rightarrow\ W\sim\mathcal N\big(-\tfrac{s^2}2,\ s^2\big),\qquad s=\ell\sqrt I

    In stationarity the first sum is asymptotically N(0,ℓ2I)\mathcal N(0,\ell^2I) by the central limit theorem. The second converges to ℓ22Ef[(log⁡f)′′]=−ℓ2I2\frac{\ell^2}2\E_f[(\log f)'']=-\frac{\ell^2I}2, using the integration-by-parts identity Ef[(log⁡f)′′]=−Ef[((log⁡f)′)2]\E_f[(\log f)'']=-\E_f[((\log f)')^2]:

  3. a(ℓ)=E[min⁡(1,eW)]=2Φ(−ℓI2)a(\ell)=\E\big[\min(1,e^W)\big]=2\Phi\big(-\tfrac{\ell\sqrt I}2\big)

    For this "mean equals minus half the variance" Gaussian, E[eW1{W<0}]=e−s2/2+s2/2 Pr⁡(N(s2/2,s2)<0)=Φ(−s/2)\E[e^W\mathbf 1\{W<0\}]=e^{-s^2/2+s^2/2}\,\Pr\big(\mathcal N(s^2/2,s^2)<0\big)=\Phi(-s/2), and Pr⁡(W≥0)=Φ(−s/2)\Pr(W\ge0)=\Phi(-s/2) as well. The acceptance rate is their sum:

  4. ℓ^=2uI≈2.38I,a(ℓ^)=2Φ(−1.19)≈0.234\hat\ell=\frac{2u}{\sqrt I}\approx\frac{2.38}{\sqrt I},\qquad a(\hat\ell)=2\Phi(-1.19)\approx0.234

    Each accepted step moves a coordinate by about σ2=ℓ2/d\sigma^2=\ell^2/d in squared distance, so dd steps achieve ℓ2a(ℓ)=h(ℓ)\ell^2a(\ell)=h(\ell), the diffusion's speed. With u=ℓI/2u=\ell\sqrt I/2, maximize u2Φ(−u)u^2\Phi(-u): the first-order condition 2Φ(−u)=u φ(u)2\Phi(-u)=u\,\varphi(u) gives u≈1.19u\approx1.19.

Predict before you look

The target is d=100d=100 independent standard normal coordinates (I=1I=1). What proposal standard deviation per coordinate does the theorem recommend?

Show the answer

0.238

ℓ^/d=2.38/10=0.238\hat\ell/\sqrt d=2.38/10=0.238. The proposal must shrink like d−1/2d^{-1/2}, so each coordinate diffuses a distance of order d−1/2d^{-1/2} per step, and exploring the target takes order dd iterations. For a Gaussian target with covariance Σ\Sigma, the matching rule is a proposal covariance (2.382/d) Σ(2.38^2/d)\,\Sigma.

SamplerTuning parameter must scale asOptimal acceptanceCost to explore
Random-walk Metropolisproposal variance ∝d−1\propto d^{-1}0.234order dd iterations
Langevin (MALA; Roberts & Rosenthal, 1998)proposal variance ∝d−1/3\propto d^{-1/3}0.574order d1/3d^{1/3} iterations
Hamiltonian Monte Carlo (Beskos et al., 2013)leapfrog step ∝d−1/4\propto d^{-1/4}, integration time fixed0.651order d1/4d^{1/4} leapfrog steps per proposal
Asymptotic results for i.i.d. product targets started in stationarity. They are guides, not laws: real posteriors are neither products nor started at equilibrium, but the ordering, and the practice of tuning by acceptance rate, carry over well.

Mixing, bottlenecks and what diagnostics miss

How long must a chain run? The mixing time tmix(ε)=min⁡{t:max⁡x∥Pt(x,⋅)−π∥TV≤ε}t_{\mathrm{mix}}(\varepsilon)=\min\{t:\max_x\norm{P^t(x,\cdot)-\pi}_{\mathrm{TV}}\le\varepsilon\} answers it in the worst case over starts. For a reversible, irreducible, aperiodic chain on a finite space with absolute spectral gap γ⋆\gamma_\star (one minus the largest eigenvalue modulus below 1) and relaxation time trel=1/γ⋆t_{\mathrm{rel}}=1/\gamma_\star, the spectral gap controls mixing up to logarithmic factors (Levin & Peres, 2017):

(trel−1)log⁡12ε ≤ tmix(ε) ≤ trellog⁡1ε πmin⁡.(t_{\mathrm{rel}}-1)\log\frac1{2\varepsilon}\ \le\ t_{\mathrm{mix}}(\varepsilon)\ \le\ t_{\mathrm{rel}}\log\frac1{\varepsilon\,\pi_{\min}}.

The gap in turn is controlled by geometry. The bottleneck ratio Φ⋆=min⁡π(S)≤1/2Q(S,Sc)/π(S)\Phi_\star=\min_{\pi(S)\le1/2}Q(S,S^c)/\pi(S), with Q(S,Sc)=∑x∈S,y∉Sπ(x)P(x,y)Q(S,S^c)=\sum_{x\in S,y\notin S}\pi(x)P(x,y) the equilibrium flow out of SS, satisfies Cheeger's inequality Φ⋆2/2≤γ≤2Φ⋆\Phi_\star^2/2\le\gamma\le2\Phi_\star for the spectral gap γ\gamma of a reversible chain (Jerrum & Sinclair, 1989; Lawler & Sokal, 1988).

Two well-separated modes are the canonical bottleneck: with SS one mode, the flow across the low-density valley is tiny, so γ≤2Φ⋆\gamma\le2\Phi_\star is tiny and tmix≥(12Φ⋆−1)log⁡12εt_{\mathrm{mix}}\ge(\frac1{2\Phi_\star}-1)\log\frac1{2\varepsilon} is enormous, whatever the local step size. A random walk must accept a sequence of moves into the valley, an event whose probability falls roughly exponentially with the valley's depth in log⁡π\log\pi.

Think first Four chains of length n=1000n=1000 each have within-chain variance 1 and means 00, 0.10.1, −0.1-0.1 and 2.02.0 (one chain found the other mode). Compute R^=(n−1nW+Bn)/W\hat R=\sqrt{\big(\frac{n-1}nW+\frac Bn\big)/W}, where B/nB/n is the variance of the four chain means. What if all four chains had stayed in the first mode, with means 00, 0.10.1, −0.1-0.1 and 0.050.05?

The chain means have sample variance ≈1.007\approx1.007, so B≈1007B\approx1007 and R^=0.999+1.007≈1.42\hat R=\sqrt{0.999+1.007}\approx1.42: far above the recommended 1.01, so the disagreement is flagged. With all four chains in one mode, R^≈1.003\hat R\approx1.003, comfortably "converged", although half of the posterior has never been seen. Diagnostics compare chains with each other; they cannot see mass that no chain has visited.

Remedies for multimodality change the target or the moves rather than the step size. Parallel tempering (replica exchange; Swendsen & Wang, 1986) runs chains on flattened versions πβ\pi^{\beta}, β<1\beta<1, and swaps states between temperatures, so the hot chains carry the cold one across valleys; it too can mix slowly, and Woodard, Schmidler & Huber (2009) give conditions for rapid and for torpid mixing. Starting many chains from dispersed points remains the most practical defense.

Key takeaways

  • Metropolis–Hastings is reversible because π(x)q(x,y)α(x,y)=min⁡(π(x)q(x,y),π(y)q(y,x))\pi(x)q(x,y)\alpha(x,y)=\min(\pi(x)q(x,y),\pi(y)q(y,x)) is symmetric; with irreducibility and aperiodicity, Pn(x,⋅)→πP^n(x,\cdot)\to\pi and ergodic averages converge. Reversible, geometrically ergodic chains satisfy a CLT with variance Var⁡π(f)(1+2∑kρk)\Var_\pi(f)(1+2\sum_k\rho_k).
  • Among acceptance rules satisfying detailed balance, the Metropolis–Hastings choice minimizes asymptotic variance (Peskun). The independence sampler converges at rate (1−1/M)n(1-1/M)^n when π≤Mg\pi\le Mg, and is not geometrically ergodic when π/g\pi/g is unbounded.
  • Gibbs updates are Metropolis–Hastings moves accepted with probability 1. On a correlated Gaussian the sweep autocorrelation is ρ2\rho^2, so ESS per sweep is (1−ρ2)/(1+ρ2)(1-\rho^2)/(1+\rho^2): blocking and reparameterization matter.
  • Random-walk Metropolis on dd-dimensional product targets needs proposal scale 2.38/Id2.38/\sqrt{Id}, acceptance about 0.234 and order dd iterations; MALA and HMC improve this to d1/3d^{1/3} and d1/4d^{1/4}.
  • Mixing is governed by the spectral gap, and bottlenecks (Cheeger) make multimodal targets mix exponentially slowly. R^\hat R and ESS detect disagreement and autocorrelation, never unvisited mass.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which property of the Metropolis–Hastings kernel guarantees that π\pi is its stationary distribution?

  1. The acceptance rate is between 20% and 50%
  2. The proposal is symmetric
  3. Detailed balance: π(x)q(x,y)α(x,y)=min⁡(π(x)q(x,y),π(y)q(y,x))\pi(x)q(x,y)\alpha(x,y)=\min\big(\pi(x)q(x,y),\pi(y)q(y,x)\big) is symmetric in xx and yy
  4. The chain is started from a draw of π\pi
Show the answer

C. Detailed balance: π(x)q(x,y)α(x,y)=min⁡(π(x)q(x,y),π(y)q(y,x))\pi(x)q(x,y)\alpha(x,y)=\min\big(\pi(x)q(x,y),\pi(y)q(y,x)\big) is symmetric in xx and yy

Reversibility with respect to π\pi integrates to invariance. Convergence to π\pi from other starts additionally needs irreducibility and aperiodicity.

Question 2

For an i.i.d. product target, the dimension goes from d=100d=100 to d=400d=400. How should the random-walk proposal standard deviation per coordinate change, and what happens to the number of iterations needed?

  1. Keep it fixed; the iterations stay the same
  2. Halve it; the iterations grow about fourfold
  3. Divide it by 4; the iterations grow about sixteenfold
  4. Halve it; the iterations stay the same
Show the answer

B. Halve it; the iterations grow about fourfold

The optimal scale is 2.38/Id2.38/\sqrt{Id}, so quadrupling dd halves it. The limiting diffusion runs on a time scale of dd iterations, so the cost of exploring grows linearly in dd.

Question 3

For a systematic-scan Gibbs sampler on a bivariate Gaussian with correlation ρ\rho, what is the lag-one autocorrelation of the xx-chain from sweep to sweep?

  1. ρ\rho
  2. 1−ρ21-\rho^2
  3. ρ/2\rho/2
  4. ρ2\rho^2
Show the answer

D. ρ2\rho^2

One sweep gives xt+1=ρ2xt+noisex_{t+1}=\rho^2x_t+\text{noise}: the update of yy multiplies by ρ\rho, and the update of xx given yy multiplies by ρ\rho again. The ESS per sweep is (1−ρ2)/(1+ρ2)(1-\rho^2)/(1+\rho^2).

Question 4

Four chains, all started in the same mode of a bimodal posterior, give R^=1.002\hat R=1.002 and a large ESS. What can you conclude?

  1. The chains agree with one another about the region they explored, which says nothing about modes none of them visited
  2. The posterior is unimodal
  3. The chains have converged to the full posterior
  4. The ESS proves that the samples are representative
Show the answer

A. The chains agree with one another about the region they explored, which says nothing about modes none of them visited

R^\hat R compares between-chain and within-chain variability; if every chain is trapped in the same mode, both measure only that mode. Dispersed starts, tempering or knowledge of the model are needed to detect the other mode.

Further reading

  • N. Metropolis, A. W. Rosenbluth, M. N. Rosenbluth, A. H. Teller & E. Teller, "Equation of state calculations by fast computing machines," Journal of Chemical Physics 21(6), 1087–1092 (1953).
  • W. K. Hastings, "Monte Carlo sampling methods using Markov chains and their applications," Biometrika 57(1), 97–109 (1970).
  • G. O. Roberts, A. Gelman & W. R. Gilks, "Weak convergence and optimal scaling of random walk Metropolis algorithms," Annals of Applied Probability 7(1), 110–120 (1997).
  • G. O. Roberts & J. S. Rosenthal, "General state space Markov chains and MCMC algorithms," Probability Surveys 1, 20–71 (2004).
  • D. A. Levin & Y. Peres, Markov Chains and Mixing Times, 2nd ed. (American Mathematical Society, 2017).