Objective
Outside conjugate models the posterior 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 :
- Propose .
- Accept with probability
otherwise stay at (and record again).
The normalising constant of cancels in the ratio, which is the whole point. Why it works: the chain satisfies detailed balance. For the probability flow from to is
which is symmetric in and . Detailed balance implies 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: with symmetric , so cancels and . Uphill moves are always accepted, downhill moves sometimes.
- Independence sampler: regardless of ; the ratio becomes with , so good proposals need to have heavier tails than .
Practical rules: work with 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 prior on the win rate. The exact posterior is : mean , SD , . The sampler only ever evaluates the unnormalised log posterior, starts deliberately far away at , 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 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 , accepting 36%, is the most efficient, with an ESS of about 4,500. At step most proposals land outside 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 .
Gibbs sampling
If and each full conditional 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 and (not the NIG, so the joint posterior is not standard):
Hierarchical models (previous lesson) are sampled the same way, alternating unit parameters, and .
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 . Find the lag-1 autocorrelation of the chain and the effective sample size of 10,000 sweeps.
Show solutionHide solution
The full conditionals are and . One sweep from :
So the chain is an AR(1) with coefficient , and its lag- autocorrelation is .
For an AR(1) chain with coefficient , , so
Ten thousand sweeps are worth about a thousand independent draws. At , 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 , a variance of and a lag-1 autocorrelation of , matching .
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 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
Report the Monte Carlo standard error . In practice the sum is truncated once the estimated 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 -th draw) saves memory but never increases the information in the chain.
R-hat. Run chains from dispersed starting points, draws each after burn-in. With chain means , within-chain variances , and between-chain variance ,
If the chains have mixed, they agree and . If they are stuck in different places, is large and . 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 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 . 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 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 draws each have within-chain variance (SD ). In run A the chain means are ; in run B they are . Compute for each.
Show solutionHide solution
Run A. The grand mean is ; deviations with squares summing to . The variance of the chain means is , so . Then
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 ; deviations , squares sum , variance , . Then and , just under the threshold.
Note that measures disagreement relative to the posterior width. The same spread of chain means would give a much larger if the within-chain SD were instead of .
Knowledge check
The target is on , and you use an independence sampler with proposal (an Exponential(1)). The chain is at and proposes . 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 ; 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 ).
- ESS ; report Monte Carlo standard errors . Thinning does not add information.
- Run at least four dispersed chains, discard burn-in, and require split, rank-normalised 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).