Skip to content
LeetQuant
E02 Bayesian Statistics

E02 · Bayesian Statistics · Lesson 3 of 4

Markov Chain Monte Carlo

Sample posteriors you can only evaluate up to a constant with Metropolis–Hastings and Gibbs, then check the output: burn-in, autocorrelation, effective sample size and R-hat.

19 min

Objective

Outside conjugate models the posterior π(θ∣y)∝L(θ) π(θ)\pi(\theta \mid y) \propto L(\theta)\,\pi(\theta) is known only up to its normalising constant, and every quantity you want (a mean, a tail probability, a predictive) is an integral against it. Markov chain Monte Carlo builds a Markov chain whose stationary distribution is the posterior, runs it, and averages along the path. By the end of this lesson you should be able to derive the Metropolis–Hastings acceptance rule, write a working sampler, explain when Gibbs sampling mixes slowly, and judge from the output whether the answer can be trusted.

Metropolis–Hastings

From the current state xx:

  1. Propose x′∼q(x′∣x)x' \sim q(x' \mid x).
  2. Accept with probability
α(x,x′)=min⁡ ⁣(1,  π(x′) q(x∣x′)π(x) q(x′∣x)),\alpha(x, x') = \min\!\left(1,\; \frac{\pi(x')\, q(x \mid x')}{\pi(x)\, q(x' \mid x)}\right),

otherwise stay at xx (and record xx again).

The normalising constant of π\pi cancels in the ratio, which is the whole point. Why it works: the chain satisfies detailed balance. For x′≠xx' \ne x the probability flow from xx to x′x' is

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

which is symmetric in xx and x′x'. Detailed balance implies π\pi is stationary; if the chain can also reach every region (irreducible) and does not cycle (aperiodic), the ergodic theorem makes path averages converge to posterior expectations.

Special cases:

  • Random-walk Metropolis: x′=x+εx' = x + \varepsilon with symmetric ε\varepsilon, so qq cancels and α=min⁡(1,π(x′)/π(x))\alpha = \min(1, \pi(x')/\pi(x)). Uphill moves are always accepted, downhill moves sometimes.
  • Independence sampler: q(x′∣x)=g(x′)q(x' \mid x) = g(x') regardless of xx; the ratio becomes w(x′)/w(x)w(x')/w(x) with w=π/gw = \pi/g, so good proposals need gg to have heavier tails than π\pi.

Practical rules: work with log⁡π\log \pi to avoid underflow; for a positive or bounded parameter either reject proposals outside the support (as below) or sample on a transformed scale and include the Jacobian; tune the step so that the acceptance rate is roughly 0.44 in one dimension and 0.23 in many (Roberts, Gelman and Gilks). Too small a step accepts almost everything and crawls; too large rejects almost everything and sticks.

A sampler you can check against the exact answer

A strategy won 7 of 20 trades, with a Beta(2,2)\text{Beta}(2, 2) prior on the win rate. The exact posterior is Beta(9,15)\text{Beta}(9, 15): mean 0.3750.375, SD 0.09680.0968, P(p>0.5)=0.105P(p > 0.5) = 0.105. The sampler only ever evaluates the unnormalised log posterior, starts deliberately far away at p=0.95p = 0.95, and is run at four step sizes.

import math, random

random.seed(11)
k, n, a, b = 7, 20, 2, 2           # 7 wins in 20 trades, Beta(2, 2) prior

def log_post(p):                    # unnormalised log posterior
    if not 0 < p < 1:
        return -math.inf
    return (k + a - 1) * math.log(p) + (n - k + b - 1) * math.log(1 - p)

def metropolis(n_iter, step, p0=0.95):
    p, lp, chain, accepted = p0, log_post(p0), [], 0
    for _ in range(n_iter):
        q = p + random.gauss(0, step)                 # symmetric proposal
        lq = log_post(q)
        if math.log(random.random()) < lq - lp:       # accept with prob min(1, ratio)
            p, lp = q, lq
            accepted += 1
        chain.append(p)
    return chain, accepted / n_iter

def ess(x):                         # N / (1 + 2 * sum of autocorrelations)
    N, m = len(x), sum(x) / len(x)
    var = sum((v - m) ** 2 for v in x) / N
    s, lag = 0.0, 1
    while lag < N:
        rho = sum((x[i] - m) * (x[i + lag] - m) for i in range(N - lag)) / (N * var)
        if rho < 0.05:              # truncate once the autocorrelation dies out
            break
        s += rho
        lag += 1
    return N / (1 + 2 * s)

print("step  accept   ESS    mean     sd   P(p>0.5)")
for step in (0.01, 0.1, 0.3, 1.0):
    chain, acc = metropolis(21_000, step)
    d = chain[1_000:]                           # discard burn-in
    m = sum(d) / len(d)
    sd = (sum((v - m) ** 2 for v in d) / len(d)) ** 0.5
    tail = sum(v > 0.5 for v in d) / len(d)
    print(f"{step:<4}  {acc:6.2f}  {ess(d):5.0f}  {m:.4f}  {sd:.4f}  {tail:.3f}")
print(f"exact               {9 / 24:.4f}  {(9 * 15 / (24**2 * 25)) ** 0.5:.4f}  0.105")

Output:

step  accept   ESS    mean     sd   P(p>0.5)
0.01    0.97     48  0.3855  0.0856  0.091
0.1     0.70   2777  0.3743  0.0970  0.105
0.3     0.36   4494  0.3762  0.0965  0.112
1.0     0.12   1595  0.3736  0.0956  0.099
exact               0.3750  0.0968  0.105

Read the table as a diagnosis. With step 0.010.01 the chain accepts 97% of moves but barely moves: 20,000 draws are worth 48 independent ones and the SD is noticeably underestimated, because the chain has not explored the posterior. Step 0.30.3, accepting 36%, is the most efficient, with an ESS of about 4,500. At step 1.01.0 most proposals land outside (0,1)(0, 1) or deep in the tails and are rejected. The good runs agree with the exact answer to within Monte Carlo error: with ESS 4,494 the standard error of the mean is 0.0965/4494=0.00140.0965/\sqrt{4494} = 0.0014.

Gibbs sampling

If θ=(θ1,…,θd)\theta = (\theta_1, \dots, \theta_d) and each full conditional π(θi∣θ−i,y)\pi(\theta_i \mid \theta_{-i}, y) is easy to sample, update the components in turn by drawing from them. Each step is a Metropolis–Hastings move whose proposal is the full conditional itself, and the acceptance probability is exactly 1.

Gibbs is natural for semi-conjugate models. For normal returns with independent priors μ∼N(m0,s02)\mu \sim N(m_0, s_0^2) and σ2∼Inv-Gamma(a0,b0)\sigma^2 \sim \text{Inv-Gamma}(a_0, b_0) (not the NIG, so the joint posterior is not standard):

μ∣σ2,y∼N ⁣(m0/s02+nyˉ/σ21/s02+n/σ2,  11/s02+n/σ2),σ2∣μ,y∼Inv-Gamma ⁣(a0+n2,  b0+12∑i(yi−μ)2).\mu \mid \sigma^2, y \sim N\!\left(\frac{m_0/s_0^2 + n\bar y/\sigma^2}{1/s_0^2 + n/\sigma^2},\; \frac{1}{1/s_0^2 + n/\sigma^2}\right), \qquad \sigma^2 \mid \mu, y \sim \text{Inv-Gamma}\!\left(a_0 + \frac n2,\; b_0 + \frac12\sum_i (y_i - \mu)^2\right) .

Hierarchical models (previous lesson) are sampled the same way, alternating unit parameters, μ\mu and τ\tau.

Gibbs's weakness is correlated parameters: moving one coordinate at a time along a narrow diagonal ridge takes tiny steps.

Worked example

how slowly does Gibbs mix?

Run Gibbs on a standard bivariate normal with correlation ρ=0.9\rho = 0.9. Find the lag-1 autocorrelation of the xx chain and the effective sample size of 10,000 sweeps.

Show solution

The full conditionals are y∣x∼N(ρx,1−ρ2)y \mid x \sim N(\rho x, 1 - \rho^2) and x∣y∼N(ρy,1−ρ2)x \mid y \sim N(\rho y, 1 - \rho^2). One sweep from xtx_t:

y=ρxt+e1,xt+1=ρy+e2=ρ2xt+ρe1+e2.y = \rho x_t + e_1, \qquad x_{t+1} = \rho y + e_2 = \rho^2 x_t + \rho e_1 + e_2 .

So the xx chain is an AR(1) with coefficient ρ2=0.81\rho^2 = 0.81, and its lag-kk autocorrelation is ρ2k\rho^{2k}.

For an AR(1) chain with coefficient ϕ\phi, 1+2∑k≥1ϕk=(1+ϕ)/(1−ϕ)1 + 2\sum_{k \ge 1} \phi^k = (1 + \phi)/(1 - \phi), so

ESS=N 1−ϕ1+ϕ=10,000×0.191.81≈1,050.\text{ESS} = N\,\frac{1 - \phi}{1 + \phi} = 10{,}000 \times \frac{0.19}{1.81} \approx 1{,}050 .

Ten thousand sweeps are worth about a thousand independent draws. At ρ=0.99\rho = 0.99, ϕ=0.98\phi = 0.98 and the ESS falls to about 100. The cure is to reparametrise (sample rotated or standardised coordinates), update correlated parameters jointly, or switch to gradient-based samplers.

import random, statistics as st

random.seed(5)
rho, N = 0.9, 50_000
sd = (1 - rho**2) ** 0.5
x, y, xs = 3.0, 3.0, []
for _ in range(N):
    x = random.gauss(rho * y, sd)    # x | y ~ N(rho y, 1 - rho^2)
    y = random.gauss(rho * x, sd)    # y | x ~ N(rho x, 1 - rho^2)
    xs.append(x)

xs = xs[500:]
print(f"mean {st.mean(xs):.3f}  var {st.variance(xs):.3f}")
print(f"lag-1 autocorrelation of x: {st.correlation(xs[:-1], xs[1:]):.3f}")

This prints a mean of −0.004-0.004, a variance of 0.9860.986 and a lag-1 autocorrelation of 0.8080.808, matching ρ2=0.81\rho^2 = 0.81.

Is the output trustworthy?

Burn-in. The chain starts wherever you put it, and early draws reflect the start, not the posterior. Discard an initial segment (the sampler above started at 0.950.95 and discarded 1,000 draws). Burn-in is a guess you verify with the diagnostics below; it does not fix a chain that never converged.

Autocorrelation and effective sample size. MCMC draws are correlated, so the Monte Carlo variance of a path average is

Var⁡(θˉ)≈σ2N(1+2∑k≥1ρk),ESS=N1+2∑k≥1ρk.\operatorname{Var}(\bar\theta) \approx \frac{\sigma^2}{N}\Big(1 + 2\sum_{k \ge 1}\rho_k\Big), \qquad \text{ESS} = \frac{N}{1 + 2\sum_{k \ge 1}\rho_k} .

Report the Monte Carlo standard error σ/ESS\sigma/\sqrt{\text{ESS}}. In practice the sum is truncated once the estimated ρk\rho_k become noise (Geyer's initial-sequence rule is the standard choice; the code above uses a simple cut-off). Tail quantities have their own, usually smaller, ESS. Thinning (keeping every kk-th draw) saves memory but never increases the information in the chain.

R-hat. Run m≥4m \ge 4 chains from dispersed starting points, nn draws each after burn-in. With chain means θˉj\bar\theta_j, within-chain variances sj2s_j^2, W=1m∑jsj2W = \frac1m \sum_j s_j^2 and between-chain variance B=nm−1∑j(θˉj−θˉ)2B = \frac{n}{m - 1}\sum_j (\bar\theta_j - \bar\theta)^2,

var⁡^+=n−1n W+Bn,R^=var⁡^+W.\widehat{\operatorname{var}}^{+} = \frac{n - 1}{n}\, W + \frac{B}{n}, \qquad \hat R = \sqrt{\frac{\widehat{\operatorname{var}}^{+}}{W}} .

If the chains have mixed, they agree and R^≈1\hat R \approx 1. If they are stuck in different places, BB is large and R^>1\hat R > 1. Modern practice (Vehtari et al., 2021) splits each chain in half, so a chain that drifts is also caught, rank-normalises the draws so heavy tails do not hide problems, and requires R^<1.01\hat R < 1.01 together with a bulk and tail ESS of at least about 400.

Diagnostics can show failure but never prove success. Several chains stuck in the same wrong mode of a multimodal posterior give R^=1\hat R = 1. That is why starting points should be dispersed and why trace plots of every chain are still worth a look.

In production, people rarely hand-code Metropolis for more than a few parameters. Stan and PyMC use Hamiltonian Monte Carlo (the No-U-Turn sampler), which uses gradients of log⁡π\log\pi to make long, well-directed moves and copes much better with correlation and dimension. The diagnostics above apply unchanged, plus a check for divergent transitions.

Worked example

computing R-hat

Four chains of n=1,000n = 1{,}000 draws each have within-chain variance 0.040.04 (SD 0.20.2). In run A the chain means are 0.10,0.12,0.08,0.500.10, 0.12, 0.08, 0.50; in run B they are 0.10,0.12,0.08,0.140.10, 0.12, 0.08, 0.14. Compute R^\hat R for each.

Show solution

Run A. The grand mean is 0.200.20; deviations −0.10,−0.08,−0.12,0.30-0.10, -0.08, -0.12, 0.30 with squares summing to 0.12080.1208. The variance of the chain means is 0.1208/3=0.04030.1208/3 = 0.0403, so B=1000×0.0403=40.27B = 1000 \times 0.0403 = 40.27. Then

var⁡^+=0.999×0.04+40.27/1000=0.0400+0.0403=0.0802,R^=0.0802/0.04=1.42.\widehat{\operatorname{var}}^{+} = 0.999 \times 0.04 + 40.27/1000 = 0.0400 + 0.0403 = 0.0802, \qquad \hat R = \sqrt{0.0802/0.04} = 1.42 .

One chain is in a different place. Do not pool the draws; find out why (a second mode, a poor start, a step size that cannot cross a barrier).

Run B. Grand mean 0.110.11; deviations −0.01,0.01,−0.03,0.03-0.01, 0.01, -0.03, 0.03, squares sum 0.00200.0020, variance 0.0006670.000667, B=0.667B = 0.667. Then var⁡^+=0.03996+0.00067=0.04063\widehat{\operatorname{var}}^{+} = 0.03996 + 0.00067 = 0.04063 and R^=1.0157=1.008\hat R = \sqrt{1.0157} = 1.008, just under the 1.011.01 threshold.

Note that R^\hat R measures disagreement relative to the posterior width. The same spread of chain means would give a much larger R^\hat R if the within-chain SD were 0.10.1 instead of 0.20.2.

Knowledge check

The target is π(x)∝xe−x\pi(x) \propto x e^{-x} on x>0x > 0, and you use an independence sampler with proposal g(x′)=e−x′g(x') = e^{-x'} (an Exponential(1)). The chain is at x=2x = 2 and proposes x′=0.5x' = 0.5. What is the acceptance probability?

Knowledge check

A chain of 10,000 draws behaves like an AR(1) with lag-1 autocorrelation 0.8. Approximately what is its effective sample size?

Knowledge check

You run four chains from dispersed starts. Each looks stable on its own trace plot, but R-hat for a key parameter is 1.3. What is the right response?

Key takeaways

  • Metropolis–Hastings accepts with min⁡(1,π(x′)q(x∣x)/(π(x)q(x′∣x)))\min\big(1, \pi(x')q(x \mid x)/(\pi(x)q(x' \mid x))\big); the normaliser cancels, and detailed balance makes the posterior stationary.
  • Tune random-walk steps to an acceptance rate around 0.44 in one dimension and 0.23 in many; both tiny and huge steps waste draws.
  • Gibbs samples full conditionals with acceptance 1, and suits semi-conjugate and hierarchical models, but mixes slowly when parameters are correlated (the bivariate-normal chain is AR(1) with coefficient ρ2\rho^2).
  • ESS =N/(1+2∑ρk)= N/(1 + 2\sum\rho_k); report Monte Carlo standard errors σ/ESS\sigma/\sqrt{\text{ESS}}. Thinning does not add information.
  • Run at least four dispersed chains, discard burn-in, and require split, rank-normalised R^<1.01\hat R < 1.01 and adequate bulk and tail ESS. Passing diagnostics is necessary, not sufficient.
  • Validate any sampler on a model with a known answer first, as with the Beta posterior here.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).