Markov chains and MCMC: Metropolis–Hastings, Gibbs and Hamiltonian Monte Carlo
Before this lesson: lesson 04 (joint and conditional distributions), lesson 05 (Gaussian conditionals), lesson 10 (posteriors known only up to a constant) and lesson 14 (Monte Carlo estimates, importance sampling and its effective sample size). From linear algebra: left and right eigenvectors (linear algebra 05). Time: about 90 minutes, plus the notebook.
Why this matters #
- Bayesian inference. Most posteriors have no closed form (lesson 10). Stan, PyMC and NumPyro sample them with Hamiltonian Monte Carlo (the NUTS variant). This is the standard way to fit hierarchical models, to calibrate the parameters of a physical model with uncertainty (a climate model component, a seismic source), and to get uncertainty for the last layer of a neural network.
- When importance sampling fails. Importance sampling (lesson 14) needs a proposal close to the target. In high dimension the weights collapse onto a few samples. MCMC makes small local moves instead, so it does not need a global proposal.
- Generative models. Energy-based and score-based models sample with Langevin dynamics, a gradient step plus Gaussian noise. This is the one-step version of HMC (generative models 06, generative models 09).
- Markov chains everywhere. PageRank is the stationary distribution of a random surfer. A policy in a Markov decision process turns it into a Markov chain (reinforcement learning 01). An n-gram language model is a Markov chain on words.
1. Predict first #
2. The picture #
A Markov chain moves probability mass. Write the distribution of the state as a row vector : entry is . The transition matrix has entries , so every row sums to 1. One step of the chain moves the mass: . Mass flows out of every state and into every state. The distribution stops changing when, at every state, the inflow equals the outflow. That distribution is the stationary distribution . (In this lesson is a distribution; the number appears only inside formulas such as .)
Press Step and watch the blue bars move toward the orange marks . The arrows are the transition probabilities, and the size of each circle is . The lower chart shows the distance to on a log scale; it falls like (dashed orange line). Edit the matrix or try the presets. Flip never converges (period 2), and Cycle has a stationary distribution but fails the detailed-balance check: its mass circulates in one direction.
MCMC reverses the usual question. Usually is given, and you look for . In MCMC, the target is given (up to a constant), and you design so that is stationary. Then you run the chain and estimate by the time average . The simplest design is random-walk Metropolis: from the current point , propose with . If the target is higher at , move. If it is lower, move only with probability ; otherwise stay at and record again. Uphill moves are always taken, downhill moves sometimes. The chain spends more time where the target is high, in exactly the right proportions (section 3 proves this).
Press Step a few times, then Run 1000. Each proposal is aqua if it is accepted and magenta if it is rejected. The blue histogram of the chain approaches the orange target. Move the step size : a tiny step is accepted almost always but crawls (see the trace); a huge step is almost always rejected and the trace has long flat parts. With the bimodal target and a small step, the chain stays in one mode for a long time.
Gibbs sampling moves along the axes. In two dimensions, Gibbs sampling draws from its conditional distribution given the current , then given the new . Each move is parallel to an axis, so the path is a staircase. If the target is a narrow diagonal ridge (strong correlation), the steps are short and the chain needs many sweeps to travel along the ridge.
Press Run 200 sweeps and watch the blue staircase inside the orange ellipses of the target. Then move toward 0.99: the steps get short, and the lag-1 autocorrelation of approaches . Turn on independent draws (violet) to see how far apart independent samples are. The readout converts the autocorrelation into sweeps per effectively independent sample.
HMC slides a puck on a landscape. Turn the target into a surface: the height at is . High probability means low height. Place a frictionless puck at the current point, give it a random kick (a momentum ), and let it slide for a while. It speeds up in the valleys and slows down on the slopes, so it follows the shape of the distribution and travels far in one iteration. The computer cannot solve the motion exactly, so it takes small leapfrog steps. A final accept/reject step removes the small error of these steps.
Press Step to draw a momentum and follow the violet leapfrog path. The end point is aqua if it is accepted and magenta if it is rejected. The readout shows the energy error . Increase the step size past about 0.45 on the correlated Gaussian: the path explodes (a divergence) and every proposal is rejected. Run 100 also runs random-walk Metropolis with the same number of gradient-or-density evaluations; compare the two effective sample sizes.
Random-walk Metropolis is at for the target . It proposes . What happens?
The acceptance probability is . Downhill moves are accepted sometimes, not never: otherwise the chain would only climb to the mode. On a rejection the current state is recorded again. Re-drawing until acceptance would change the kernel and bias the samples.
3. Definitions and main results #
Finite Markov chains #
A Markov chain on the states is a sequence with the Markov property:
The next state depends only on the current state. Every row of sums to 1. By the law of total probability, , that is , and so .
- A stationary distribution is a probability vector with . So is a left eigenvector of for the eigenvalue 1 (an eigenvector of ). Every finite chain has at least one. The eigenvalue 1 exists because (rows sum to 1), and the Perron–Frobenius theorem gives a left eigenvector with nonnegative entries.
- Irreducible: every state can reach every other state in some number of steps. Then is unique and every . The mean time to return to state is .
- Aperiodic: the period of state is the greatest common divisor of the times with . A chain is aperiodic if every period is 1. In an irreducible chain, one state with is enough.
Convergence theorem. If a finite chain is irreducible and aperiodic, then for every start . The error shrinks geometrically, roughly like , where is the second-largest absolute value among the eigenvalues of .
Ergodic theorem. If a finite chain is irreducible, then for every start and every function ,
This is the law of large numbers for Markov chains, and it is what MCMC uses: time averages along one path estimate expectations under . (It holds even for periodic chains, where itself does not converge.)
Two states, by hand. Let with .
- Write . Then .
- A fixed point satisfies , so . Hence .
- Subtract the fixed-point equation from step 1: .
- So the error is multiplied by at every step, from any start. The eigenvalues of are 1 and .
Why the conditions matter.
- The flip chain is irreducible with the unique . But it has period 2: started in state 1, alternates between 0 and 1 and never converges. Its eigenvalues are and , so .
- A reducible chain (two groups of states that never communicate) has one stationary distribution for each closed group, and every mixture of them. The long-run behaviour then depends on the start.
A chain has eigenvalues , and . About how many steps does it need to reduce the distance to by a factor of 1000?
The slowest mode decides: , and . A negative eigenvalue only makes that mode oscillate in sign; it still shrinks because . Periodicity needs an eigenvalue of modulus exactly 1 other than 1 itself.
Detailed balance #
Definition. A distribution satisfies detailed balance with if
In words: in the long run, the flow of probability from to equals the flow from to , for every pair. A chain with this property is called reversible: run backwards in time, it has the same law.
Theorem. Detailed balance implies stationarity: .
Proof. Fix a state .
- (definition of the product).
- By detailed balance, each term equals . So .
- Row of sums to 1, so .
Detailed balance is sufficient, not necessary. The Cycle preset in the first figure moves with probability 0.9 and stays with probability 0.1. Its stationary distribution is uniform, but all flow goes one way around the cycle, so . MCMC constructions still check detailed balance, because it is local: one pair of states at a time, without a sum over all states.
Metropolis–Hastings #
The target is . You can evaluate , but you do not know . For a posterior, and , the evidence (lesson 10). A proposal is any distribution you can sample from.
Algorithm (one step). From the current state :
- propose ;
- compute the acceptance probability
- with probability move to ; otherwise stay at , and record again.
In code, compare logs: accept if with . This avoids overflow and underflow.
Theorem (Metropolis–Hastings). The Metropolis–Hastings kernel satisfies detailed balance with . So is a stationary distribution of the chain.
Proof. We write the proof with densities; for a finite state space replace integrals by sums.
- For , the chain moves from to with density . On a rejection it stays at ; this adds a point mass at .
- Multiply by and move the factor inside the minimum:
The right side does not change if we swap and . So for . 3. The point mass at satisfies detailed balance trivially: both sides are the same term. 4. Integrate detailed balance over : , because the kernel from , including its rejection mass, has total probability 1. This is stationarity.
Only ratios appear. : the constant cancels. This is why MCMC works for posteriors. Stationarity alone does not give convergence: the chain must also be irreducible and aperiodic. With a Gaussian proposal on and a positive target, both hold (rejections give aperiodicity).
- Random-walk Metropolis. with . This proposal is symmetric, , so . A small step : almost every move is accepted, but the moves are tiny. A large : almost every move is rejected. For a 1-D target the acceptance rate is : 0.844, 0.442 and 0.205 for . In dimensions the best step scales like , with an acceptance rate near 0.234 (Roberts, Gelman and Gilks, 1997), and the chain needs about steps per independent sample.
- The Hastings correction is needed when the proposal is not symmetric. Example: for a positive parameter, the multiplicative walk has the correction (check yourself, question 4).
- Independence sampler. The proposal does not depend on . Then with the importance weight of lesson 14. As in importance sampling, needs heavier tails than .
You tune random-walk Metropolis on a 1-D target and reach an acceptance rate of 99%. What does this most likely mean?
As , , so almost every proposal is accepted, but each move is tiny. The useful measure is the effective sample size per step, not the acceptance rate. For a 1-D Gaussian the best step has an acceptance rate near 0.44.
Gibbs sampling #
Let . The full conditional of coordinate is , where is the vector of all other coordinates. Gibbs sampling updates one coordinate at a time with a draw from its full conditional. A sweep updates every coordinate once.
Theorem. One Gibbs update is a Metropolis–Hastings step with acceptance probability 1.
Proof. The proposal changes only coordinate : , with .
- Write . Then .
- In the same way, , using .
- The two products are equal, so the MH ratio is 1 and .
Each update leaves invariant, so a full sweep (one update after another) does too. A sweep in fixed order is in general not reversible, but it is still a valid sampler. Gibbs sampling is popular when the full conditionals have closed forms, as in conjugate hierarchical models, mixture models and topic models.
Why Gibbs is slow for correlated targets. Take standard Gaussian with correlation . By lesson 05, , and the same with the roles swapped.
- One sweep: , then , with independent standard normal noise .
- Substitute the second line of the previous sweep into the first: . So the chain of is an AR(1) process with coefficient .
- Its autocorrelation at lag is . The next section turns this into an effective sample size: .
The picture: Gibbs moves parallel to the axes, and in a narrow diagonal ridge each move has length of order . The fixes are to update correlated coordinates together (blocking) or to change the coordinates (reparametrisation), for example rotate them so that they are uncorrelated.
Hamiltonian Monte Carlo #
Momentum. Add an auxiliary variable , the momentum, with , independent of . The joint density is with the Hamiltonian (total energy)
is the potential energy and the kinetic energy. The -marginal of is : sample and drop . (Implementations often use a mass matrix : and kinetic energy . Here .)
Exact dynamics. Hamilton's equations are and . Their flow has three properties:
- it conserves (the derivative of along the flow is );
- it preserves volume in space (Liouville's theorem);
- it is reversible: flip the momentum at the end, run for the same time, and you return to the start.
Together these mean the flow leaves invariant. Because is conserved, one trajectory stays on one energy level. A fresh momentum at every iteration (a Gibbs step on ) moves the chain between levels.
Leapfrog. The exact flow is not available, so we discretise it. With step size , one leapfrog step is
Consecutive half steps in merge, so steps cost gradient evaluations.
- Volume preserving. Each of the three updates is a shear: it changes one block of variables by an amount that depends only on the other block. Its Jacobian matrix is block triangular with identity blocks on the diagonal, so its determinant is 1. The determinant of the composition is the product, also 1.
- Reversible. Start from the end point with the momentum flipped, , and run steps: you return to . The three updates undo each other in reverse order.
- Accurate. The energy error over a fixed time is , and it does not grow over long trajectories when is below a stability limit. Halving cuts the error by about 4. Above the limit (for a Gaussian, , twice the smallest standard deviation) the path explodes.
HMC (one iteration). Draw . Run leapfrog steps from to . Accept with probability
otherwise keep . This is a Metropolis–Hastings step on with the proposal . The momentum flip makes the proposal map its own inverse, so it is symmetric. Volume preservation means no Jacobian factor appears. Without the correction, the energy error would bias the samples.
Why HMC scales. Random-walk Metropolis needs about steps per independent sample in dimensions. HMC uses the gradient to make long, directed moves. For i.i.d. product targets the cost grows like leapfrog steps per sample, with the best acceptance rate near 0.65 (Beskos et al., 2013). The tuning parameters are , and . NUTS (the No-U-Turn Sampler, the default in Stan) chooses the trajectory length automatically, and tunes and during warm-up. A divergence is a trajectory whose energy error explodes. It warns that the chain cannot explore a region of high curvature, and the results may be biased.
Langevin dynamics, MALA and Brownian motion
HMC with a single leapfrog step () and a fresh momentum gives the update with . Write : . This is the Euler step of the Langevin diffusion , where is Brownian motion: the limit of a random walk whose steps scale like (lesson 06, the deeper block on random walks). The Langevin diffusion has as its stationary distribution. With a Metropolis–Hastings correction the update is MALA (Metropolis-adjusted Langevin algorithm). Without the correction, and with mini-batch gradients, it is SGLD (stochastic gradient Langevin dynamics). Score-based generative models run the same update with a learned score in place of the true one. SDEs and their stationary distributions are in ML for science 12; score-based diffusion samplers in generative models 09.
Diagnostics: effective sample size and split- #
MCMC draws are correlated, and the chain needs time to forget its start. Two numbers tell you whether to trust the output.
Effective sample size (ESS). Let the chain be stationary with variance and autocorrelation at lag (the correlation between and ). Under mild conditions the Markov chain central limit theorem gives
is the integrated autocorrelation time. The ESS is : your correlated draws give the same error as independent ones. The Monte Carlo standard error of the mean is .
For an AR(1) chain with coefficient : , so and . For , . For , : negatively correlated draws can beat independent ones.
Estimating . The sample autocorrelations at large lags are mostly noise, so the full sum is useless. Geyer's initial positive sequence adds pairs for while they are positive, and stops at the first . Then . (The removes the double-counted .)
Split-. Run chains of length from dispersed starts. Split each chain into halves, to get half-chains of length .
- = the mean of the within-chain sample variances.
- the sample variance of the half-chain means.
- and .
If all chains explore the same distribution, is small and . Chains stuck in different regions make large, so . The split also catches a chain that drifts: its two halves disagree, even when all chains drift the same way. Vehtari et al. (2021) recommend at least 4 chains, , and an ESS above 400 (in total over the chains) before you trust the estimates.
Choose a preset. Four random-walk Metropolis chains (four colours) start far apart. The first half of each chain is warm-up (shaded) and is dropped. Well mixed: the traces overlap like noise, , and the autocorrelations die fast. Too small step: the traces still remember their starts, and the autocorrelation decays slowly. Stuck in one mode: each chain looks fine alone, but the chains disagree, so is large. All in the same mode: the diagnostics pass, but half of the target is missing. Then make the chains longer: which problems go away?
What diagnostics cannot see. If all chains are stuck in the same mode of a multimodal target, they agree and . A region that no chain reaches (for example the narrow neck of a funnel-shaped posterior) does not show up in the ESS. So: run several chains from dispersed starts, check divergences for HMC, and compare with what you know about the model.
What to report. The sampler and its settings, the number of chains, the warm-up length and the number of kept draws, and ESS (bulk and tail) for every reported quantity, the number of divergences, and the Monte Carlo standard error of each estimate.
Rank-normalised , bulk and tail ESS
Classic uses means and variances, so it fails for heavy-tailed targets (infinite variance) and misses chains that differ only in their spread. Vehtari et al. (2021) first replace all draws by their normal scores: pool the draws of all chains, rank them, and map rank to , with the total number of draws. Split- on these scores is the bulk-. The same on the folded draws checks the spread (tails). The reported is the maximum of the two. Bulk ESS is the ESS of the normal scores; tail ESS is the smaller ESS of the indicators and . ArviZ, Stan and PyMC report these by default.
Four chains give split- for a parameter. What is the right reaction?
means the between-chain spread is large compared with the within-chain spread: the chains have not explored the same distribution. Dropping a chain hides the problem (that chain may have found a real mode). Thinning does not change the means of the halves, so it does not fix ; it only throws away draws.
Answers to section 1.
- Two thirds. With (dry to wet) and (wet to dry), . The chain is irreducible and aperiodic, so day 0 does not matter in the long run. Its influence decays like .
- About 100. The chain of is AR(1) with . So .
4. Worked example #
(a) The weather chain. , state 1 = dry, state 2 = wet.
- Stationary distribution: . Check the first entry of : . ✓
- Detailed balance: and . ✓ (Every two-state chain with is reversible: there is only one pair, and stationarity forces the two flows to be equal.)
- Speed: . Starting dry, . This gives , and for .
- Mean return times : 1.5 days back to a dry day, 3 days back to a wet day.
(b) The Metropolis kernel as a matrix. Target on states , so . Proposal: left or right neighbour, probability each; a move off the ends is rejected.
- From state 3 (): to state 2, , so . In the same way , and .
- From state 2 (): to state 3, , so ; to state 1, , so ; and .
- Detailed balance for the pair (2, 3): and . ✓
- The eigenvalues of this kernel are (section 5 checks them), so the error shrinks like .
(c) Three steps of random-walk Metropolis by hand. Target , start , step , noise and uniforms . Accept if .
| step | result | |||||
|---|---|---|---|---|---|---|
| 1 | 0 | 1.2 | 0.487 | 0.3 | accept: 1.2 | |
| 2 | 1.2 | 0.8 | 1 | 0.9 | accept: 0.8 | |
| 3 | 0.8 | 1.7 | 0.325 | 0.5 | reject: 0.8 |
The chain is . The rejected step records the current state again. Dropping repeated states would bias the chain toward regions where proposals are often accepted.
(d) One HMC iteration by hand. Target , so and . Start at with the momentum draw , step , one leapfrog step ().
- Energy at the start: .
- Half step in momentum: .
- Full step in position: .
- Half step in momentum: .
- Energy at the end: . The energy error is .
- Accept with probability .
The exact flow would conserve and give . The leapfrog error is small, so almost every proposal is accepted, and the accept/reject step removes the remaining bias.
(e) Split- catches a drift. One chain with draws . The halves are and , so .
- Within-half variances: and , so .
- Half means and ; their sample variance is , so .
- and .
Without the split there is only one chain, no between-chain variance and no warning.
In example (c), suppose the third uniform were instead of . What is the chain after three steps?
The third proposal has . Since , it is accepted even though the target is lower at 1.7. Every step records exactly one state, so the chain always has three entries.
5. In code #
NumPy checks the hand computations. The notebook for this lesson has these cells and the exercises.
import numpy as np
np.set_printoptions(precision=4, suppress=True)
# (a) weather chain: stationary distribution by a linear solve, and convergence
P = np.array([[0.8, 0.2], [0.4, 0.6]])
A = np.vstack([(P.T - np.eye(2))[:-1], np.ones(2)]) # pi (P - I) = 0, with one equation replaced by sum = 1
pi = np.linalg.solve(A, [0.0, 1.0])
print(pi, np.linalg.matrix_power(P, 5)[0]) # [0.6667 0.3333] [0.6701 0.3299]
print(np.sort(np.linalg.eigvals(P).real)) # [0.4 1. ]
# (b) the Metropolis kernel on 5 states is a matrix: check detailed balance
pt = np.array([1, 2, 4, 2, 1.0]) # unnormalised target
K = len(pt)
Pmh = np.zeros((K, K))
for i in range(K):
for j in (i - 1, i + 1):
if 0 <= j < K: # a move off the ends is rejected
Pmh[i, j] = 0.5 * min(1.0, pt[j] / pt[i])
Pmh[i, i] = 1.0 - Pmh[i].sum() # rejection mass stays at i
pi5 = pt / pt.sum()
flows = pi5[:, None] * Pmh # flows[i, j] = pi_i P_ij
print(np.allclose(flows, flows.T), np.allclose(pi5 @ Pmh, pi5)) # True True
print(np.sort(np.abs(np.linalg.eigvals(Pmh)))[::-1]) # [1. 0.75 0.5 0.25 0. ]
# (c) three random-walk Metropolis steps with fixed noise
log_t = lambda x: -0.5 * x**2
x, chain = 0.0, []
for z, u in zip([1.2, -0.4, 0.9], [0.3, 0.9, 0.5]):
xp = x + z
if np.log(u) < log_t(xp) - log_t(x): # log acceptance test
x = xp
chain.append(x)
print(np.round(chain, 2)) # [1.2 0.8 0.8]
# (d) one leapfrog step for U(x) = x^2/2, then the MH correction
x, p, eps = 0.0, 1.0, 0.5
H = lambda x, p: 0.5 * x**2 + 0.5 * p**2
H0 = H(x, p)
p = p - eps / 2 * x; x = x + eps * p; p = p - eps / 2 * x
print(x, p, H(x, p) - H0, np.exp(H0 - H(x, p))) # 0.5 0.875 0.0078125 0.9922...
# (e) split-R-hat of the drifting chain (0, 1, 2, 3)
halves = np.array([[0.0, 1.0], [2.0, 3.0]])
h = 2
W = halves.var(axis=1, ddof=1).mean()
B = h * halves.mean(axis=1).var(ddof=1)
print(W, B, np.sqrt(((h - 1) / h * W + B / h) / W)) # 0.5 4.0 2.1213...
A simulation checks the acceptance-rate formula of random-walk Metropolis and the AR(1) behaviour of Gibbs ():
import numpy as np
def rwm(log_p, x0, n, s, rng):
x, lp, out, acc = x0, log_p(x0), np.empty(n), 0
for t in range(n):
xp = x + s * rng.standard_normal()
lpp = log_p(xp)
if np.log(rng.random()) < lpp - lp:
x, lp, acc = xp, lpp, acc + 1
out[t] = x # a rejection records x again
return out, acc / n
rng = np.random.default_rng(0)
for s in (0.5, 2.4, 6.0):
chain, acc = rwm(lambda x: -0.5 * x**2, 0.0, 50_000, s, rng)
print(s, round(acc, 3), round(2 / np.pi * np.arctan(2 / s), 3))
# about: 0.5 0.842 0.844 | 2.4 0.445 0.442 | 6.0 0.203 0.205 (Monte Carlo error about ±0.004)
rho, n = 0.99, 200_000
x1, x2, xs = 0.0, 0.0, np.empty(n)
sd = np.sqrt(1 - rho**2)
z = rng.standard_normal((n, 2))
for t in range(n):
x1 = rho * x2 + sd * z[t, 0] # x1 | x2 ~ N(rho x2, 1 - rho^2)
x2 = rho * x1 + sd * z[t, 1] # x2 | x1, with the new x1
xs[t] = x1
print(round(np.corrcoef(xs[:-1], xs[1:])[0, 1], 3), rho**2) # about 0.979, and 0.9801
6. Where it shows up #
- Probabilistic programming. Stan, PyMC and NumPyro run NUTS by default: 4 chains, a warm-up that tunes and the mass matrix, then , bulk and tail ESS and the divergence count in the summary table. Typical uses: hierarchical models for A/B tests over many groups, epidemiological models, calibration of physical model parameters (climate model components, a seismic source inversion), pharmacokinetics.
- Gibbs sampling with conjugate conditionals. Latent Dirichlet allocation (topic models), Bayesian mixture models, Bayesian linear regression with a conjugate prior, and data augmentation for probit regression all have closed-form full conditionals.
- Langevin dynamics in deep learning. Energy-based models and score-based diffusion models generate samples with (annealed) Langevin steps; SGLD gives approximate posterior samples of neural network weights from mini-batch gradients (generative models 06).
- Markov chains as models. PageRank is the stationary distribution of a random surfer with random restarts (the restarts make the chain irreducible and aperiodic). A fixed policy turns an MDP into a Markov chain, and its stationary distribution weights the states in policy-gradient theorems (reinforcement learning 01). Hidden Markov models (speech, genomics) put a Markov chain under noisy observations.
- Statistical physics. The original Metropolis algorithm (1953) sampled the Boltzmann distribution of particle systems. The Ising model and molecular simulations still use Metropolis, Gibbs (heat-bath) and Hamiltonian (molecular dynamics) moves.
7. Common mistakes #
- Computing as a high power of . It fails for periodic chains and is slow when is close to 1. Solve with .
- Using a right eigenvector instead of a left one. always holds, so the right eigenvector for eigenvalue 1 is the constant vector. is the eigenvector of .
- "Detailed balance is necessary for stationarity." It is only sufficient (the cycle chain).
- Forgetting the Hastings correction for an asymmetric proposal, for example a random walk on for a positive parameter (the factor ).
- Not recording the current state after a rejection, or re-proposing until a move is accepted. The repeated values are part of the chain.
- Tuning for a very high acceptance rate. Near 100% acceptance usually means tiny steps and slow mixing.
- Adapting the step size forever. If the proposal keeps changing with the chain's history, the chain may no longer have as its stationary distribution. Adapt during warm-up only, then fix the settings.
- Thinning to "fix" autocorrelation. Keeping every -th draw throws information away. It only saves memory.
- Trusting one chain, or the old threshold . Run at least 4 chains from dispersed starts and use .
- Ignoring divergences in HMC. Even a few divergences mean that part of the posterior was not explored.
8. Check yourself #
- Find for without solving a
system.
Answer
The chain moves only to neighbours, so try detailed balance: gives , and gives . Normalise: . Detailed balance implies stationarity, so this is . - A chain has . Give , , and the number of steps until the
distance to is below 1% of its starting value.
Answer
, , so and . The error is multiplied by each step: for , so 6 steps. - A Metropolis–Hastings sampler uses the symmetric proposal on a target with for .
The chain is at and proposes . What happens, and what goes wrong if you "reflect" the proposal to
instead?
Answer
, so : the move is rejected and the chain records again. Reflecting is also a valid symmetric proposal (the density of at is symmetric in and for ), so it is not wrong. What is wrong is to reject and then re-propose until a positive value appears: that changes the kernel near 0 and biases the samples. - For a positive parameter you propose with . What is the Hastings correction?
Answer
Given , is log-normal: . The exponent is symmetric in and , so , and . Equivalently, run a symmetric random walk on with the target (the Jacobian of lesson 05). - Why does the HMC acceptance probability contain no Jacobian term, and why is a fresh momentum drawn at every
iteration?
Answer
The leapfrog map is volume preserving (a composition of shears with determinant 1), so the density of the proposed point changes only through . With the momentum flip the map is its own inverse, so the proposal is symmetric. A fresh momentum is needed because is (nearly) conserved along a trajectory: without it the chain stays on one energy level and cannot explore the whole target. - Four chains give and an ESS of 3000 for every parameter. Name one way the result can still be wrong.
Answer
All four chains can sit in the same mode of a multimodal posterior (they agree with each other), or all can miss a hard region such as the neck of a funnel. and ESS only see the regions the chains visited. For HMC, check divergences; run more chains from more dispersed starts.
What equation defines a stationary distribution of a finite Markov chain with transition matrix ?
with and ; is a left eigenvector of for the eigenvalue 1.
Which two conditions make a finite chain converge to a unique from every start, and how fast?
Irreducible and aperiodic; the error shrinks roughly like , the second-largest eigenvalue modulus.
State detailed balance and what it implies.
for all ; summing over gives , so is stationary.
Compute for .
with , : .
Write the Metropolis–Hastings acceptance probability.
; on a rejection the chain records again.
Why does Metropolis–Hastings not need the normalising constant ?
Only the ratio appears in the acceptance probability, and cancels in it.
Why is a Gibbs update accepted with probability 1?
With the proposal , both and equal , so the MH ratio is 1.
Why is Gibbs slow for a bivariate Gaussian with ?
Each coordinate is AR(1) with coefficient , so ESS$/n = (1 - \rho^2)/(1 + \rho^2) \approx 0.01$: about 100 sweeps per effective sample.
Name three properties of the leapfrog integrator that HMC needs.
It preserves volume (shears with determinant 1), it is reversible (flip the momentum and return), and its energy error is over a fixed time.
How is the effective sample size computed from autocorrelations?
ESS with , the sum truncated with Geyer's initial positive sequence.
9. Interview angle #
- "How do you sample from an unnormalised posterior?" — Metropolis–Hastings: the acceptance probability uses only , so cancels. Tune the step size, run several chains, check and ESS. In practice, use NUTS in Stan, PyMC or NumPyro.
- "Prove that Metropolis–Hastings samples the target." — Show detailed balance: is symmetric; summing gives stationarity; irreducibility and aperiodicity give convergence.
- "Gibbs, random-walk Metropolis or HMC?" — Gibbs when the full conditionals are easy (conjugate models), but it is slow for correlated coordinates. HMC for smooth, continuous, high-dimensional targets with gradients. Random-walk Metropolis for low dimension or when no gradient is available. Discrete parameters: Gibbs or marginalise them out.
- "Importance sampling or MCMC for a posterior?" — Importance sampling in low dimension with a good heavy-tailed proposal: independent draws and an estimate of the evidence . MCMC in high dimension, where importance weights collapse (lesson 14).
- "What is a good acceptance rate?" — About 0.44 for 1-D random-walk Metropolis, about 0.234 in high dimension, about 0.65 to 0.8 for HMC. A rate near 1 means tiny steps.
- "Your chains have . What do you do?" — Look at the trace plots, run longer, reparametrise (for example a non-centred parametrisation of a hierarchical model), use a better sampler, and check again. Do not drop chains.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
stationary_distributionby a linear solve and by an eigenvector of (not by ), tested on the weather chain, the periodic flip chain and a birth–death chain.metropolis_hastingswith the log acceptance test; the acceptance rate against and on a banana-shaped target.gibbs_bivariate_gaussianand the lag-1 autocorrelation of its chain, for several .leapfrog, tested for reversibility and the energy error; then a small HMC sampler on a correlated Gaussian.ess_autocorr(Geyer) andsplit_rhat, tested on AR(1) chains () and on chains that are stuck or drift.
11. Watch and read #
- Joseph Blitzstein and Jessica Hwang, Introduction to Probability (free online, 2nd ed.): ch. 11 (Markov chains: classification of states, stationary distributions, reversibility) and ch. 12 (Markov chain Monte Carlo: Metropolis–Hastings and Gibbs).
- Art Owen, Monte Carlo theory, methods and examples (free chapters): ch. 11 (Markov chains, detailed balance, Metropolis–Hastings, burn-in and error estimates) and ch. 12 (Gibbs sampling and correlated components).
- Michael Betancourt, A Conceptual Introduction to Hamiltonian Monte Carlo (2017): §3 (phase space and Hamilton's equations) and §5 (symplectic integrators, the Metropolis correction, divergences).
- Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter and Paul-Christian Bürkner, Rank-normalization, folding, and localization: an improved (2021): §2 (recommendations), §3 (split- and ESS with Geyer's truncation).
- Radford Neal, MCMC using Hamiltonian dynamics (2011): the classic tutorial on HMC, with the leapfrog proofs and tuning advice.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.