Skip to content
BIASED

Markov chain Monte Carlo

How to sample a distribution known only up to a constant: detailed balance, the Metropolis–Hastings algorithm and why the constant cancels, step size and burn-in, Gibbs sampling, autocorrelation and the effective sample size, and a recap of the whole course.

A density known up to a constant

The topic Monte Carlo methods turned an expectation into an average of independent samples, with an error of about σ/n\sigma/\sqrt n. Its samplers need either a formula for the inverse CDF or a proposal qq close to the target, and rejection and importance sampling both degrade quickly as the dimension grows. The topic ended with the hard case: a density known only up to a constant.

In Bayesian statistics this case is the rule. Take the coin with unknown bias θ\theta from the topic Bayesian inference: 7 heads in 10 tosses and a uniform prior. Bayes' formula gives the posterior as prior times likelihood, divided by the evidence:

p(θ)=p~(θ)Z,p~(θ)=θ7(1−θ)3,Z=∫01p~(θ) dθ.p(\theta) = \frac{\tilde p(\theta)}{Z}, \qquad \tilde p(\theta) = \theta^7 (1 - \theta)^3, \qquad Z = \int_0^1 \tilde p(\theta)\, d\theta .

Here ZZ happens to have a formula: the posterior is Beta⁡(8,4)\operatorname{Beta}(8, 4) with mean 2/32/3, and that lets us check every answer below. Replace the uniform prior by one without a conjugate partner, or the coin by a logistic regression with a hundred weights, and ZZ becomes an integral over a hundred dimensions that nobody can compute. The unnormalized density p~\tilde p stays cheap: one factor per observation.

What can we do with p~\tilde p alone? We can compare two points. The constant cancels in a ratio:

p(y)p(x)=p~(y)/Zp~(x)/Z=p~(y)p~(x).\frac{p(y)}{p(x)} = \frac{\tilde p(y)/Z}{\tilde p(x)/Z} = \frac{\tilde p(y)}{\tilde p(x)} .

We know how many times more probable one point is than another, but not how probable either of them is.

The topic Markov chains supplies the other half. By the ergodic theorem, one long run of an irreducible chain spends in each state a share of time equal to its stationary probability, and averages along the run converge to expectations under π\pi. Read backwards: if we build a chain whose stationary distribution is pp, running it produces samples from pp. This is Markov chain Monte Carlo (MCMC). The whole topic is about building such a chain from ratios of p~\tilde p.

Detailed balance

In the topic Markov chains the transition matrix was given, and we solved πP=π\pi P = \pi for π\pi. Now the problem runs the other way: π=p\pi = p is given, and we need a PP that keeps it. The equation πP=π\pi P = \pi has many solutions PP, and it is hard to aim at it directly. A simpler, local condition is enough. Write P(x→y)P(x \to y) for the probability of a step from xx to yy. The chain satisfies detailed balance with respect to pp if

p(x) P(x→y)=p(y) P(y→x)for all x,y.p(x)\, P(x \to y) = p(y)\, P(y \to x) \quad \text{for all } x, y .

Read p(x) P(x→y)p(x)\, P(x \to y) as a flow: in equilibrium, the probability that a step goes from xx to yy. Detailed balance says that between every pair of states the traffic is the same in both directions. Summing over xx and using that the moves out of yy sum to one:

∑xp(x) P(x→y)=∑xp(y) P(y→x)=p(y).\sum_x p(x)\, P(x \to y) = \sum_x p(y)\, P(y \to x) = p(y) .

The left side is (pP)y(pP)_y, so pP=ppP = p: the target is stationary. On a continuous state space P(x→y)P(x \to y) is a transition density and the sum becomes an integral, as promised in the topic Markov chains.

Detailed balance gives invariance and nothing more. The chain that never moves, P(x→x)=1P(x \to x) = 1, satisfies it for every pp, and it obviously samples nothing. Irreducibility and aperiodicity still have to be checked separately, and only then does the convergence theorem apply.

The condition is sufficient, not necessary. A chain that walks around three states on a circle, stepping forward with probability 0.90.9 and staying with probability 0.10.1, keeps the uniform distribution stationary, yet its traffic flows only one way. Most practical samplers use detailed balance anyway, because it is so easy to arrange.

The Metropolis–Hastings algorithm

The Metropolis–Hastings algorithm arranges detailed balance with a propose-and-check step. Besides p~\tilde p it needs a proposal distribution q(y∣x)q(y \mid x) that is easy to sample. From the current state xx:

  1. draw a candidate y∼q(⋅∣x)y \sim q(\cdot \mid x);
  2. accept it with probability
α(x,y)=min⁡(1, p~(y) q(x∣y)p~(x) q(y∣x));\alpha(x, y) = \min\Big(1,\ \frac{\tilde p(y)\, q(x \mid y)}{\tilde p(x)\, q(y \mid x)}\Big) ;
  1. if accepted, the next state is yy; otherwise the next state is xx again.

The unknown ZZ would appear in the numerator and the denominator, so it cancels and never has to be computed. In code one compares logarithms, log⁡U<log⁡p~(y)−log⁡p~(x)\log U < \log \tilde p(y) - \log \tilde p(x) with U∼U(0,1)U \sim U(0, 1), because a product of many likelihood factors underflows.

The most common proposal is a random step, y=x+sεy = x + s\varepsilon with ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1) and a step size ss. It is symmetric, q(y∣x)=q(x∣y)q(y \mid x) = q(x \mid y), so the proposal terms cancel too and

α(x,y)=min⁡(1, p~(y)p~(x)).\alpha(x, y) = \min\Big(1,\ \frac{\tilde p(y)}{\tilde p(x)}\Big) .

Steps uphill are always accepted, steps downhill only sometimes. This is random-walk Metropolis, the algorithm of Metropolis and colleagues from 1953; Hastings added the correction for asymmetric qq in 1970.

An example with p~(x)=e−x2/2\tilde p(x) = e^{-x^2/2}, a standard normal without its constant. From x=0x = 0 the candidate y=2y = 2 goes downhill and is accepted with probability α(0,2)=e−2≈0.135\alpha(0, 2) = e^{-2} \approx 0.135. From x=2x = 2 the candidate y=0y = 0 goes uphill, so α(2,0)=1\alpha(2, 0) = 1. The rare move out and the certain move back carry the same flow, because p~(2)=e−2 p~(0)\tilde p(2) = e^{-2}\, \tilde p(0): that is detailed balance at work.

Why the chain lands on p

Why does Metropolis–Hastings satisfy detailed balance? For y≠xy \ne x the chain moves from xx to yy only by proposing yy and accepting it, so P(x→y)=q(y∣x) α(x,y)P(x \to y) = q(y \mid x)\, \alpha(x, y). Multiply by p(x)p(x) and take the factor p(x) q(y∣x)p(x)\, q(y \mid x) inside the minimum:

p(x) q(y∣x) α(x,y)=min⁡(p(x) q(y∣x), p(y) q(x∣y)).p(x)\, q(y \mid x)\, \alpha(x, y) = \min\big(p(x)\, q(y \mid x),\ p(y)\, q(x \mid y)\big) .

The right side does not change when xx and yy swap places, so it also equals p(y) q(x∣y) α(y,x)p(y)\, q(x \mid y)\, \alpha(y, x). That is detailed balance. For y=xy = x the condition reads p(x)P(x→x)=p(x)P(x→x)p(x) P(x \to x) = p(x) P(x \to x) and holds trivially. So pp is stationary, rejections included.

On a finite state space the whole chain fits into a transition matrix. Take three states with p~=(1,2,3)\tilde p = (1, 2, 3), so p=(1/6,2/6,3/6)p = (1/6, 2/6, 3/6), and propose one of the two other states with probability 1/21/2 each. From state 1 every candidate is uphill and accepted. From state 2 the move to state 1 is accepted with probability 1/21/2, the move to state 3 always:

row 1: (0, 1/2, 1/2),row 2: (1/4, 1/4, 1/2).\text{row 1: } (0,\ 1/2,\ 1/2), \qquad \text{row 2: } (1/4,\ 1/4,\ 1/2).

The diagonal entry 1/41/4 is the probability that the proposal from state 2 is rejected. With the third row one checks pP=ppP = p exactly as in the topic Markov chains.

A rejection repeats the current state, and the repeat counts as a sample. Dropping repeats looks like harmless cleanup, but it changes the answer. The states where many proposals are rejected lose weight. In this chain state 3 rejects half of its proposals; among the moves alone it gets a share 3/83/8 instead of 1/21/2.

Step size and burn-in

Let us run random-walk Metropolis on the coin posterior p~(θ)=θ7(1−θ)3\tilde p(\theta) = \theta^7 (1 - \theta)^3. Two rules about the support come straight from the ratio. Start where p~(θ0)>0\tilde p(\theta_0) > 0, here θ0=0.5\theta_0 = 0.5. A candidate outside (0,1)(0, 1) has p~=0\tilde p = 0, so α=0\alpha = 0 and the chain never leaves the set where the target lives.

Every step size gives a valid chain with the same stationary distribution. The step size decides how fast it gets anywhere. Five runs of 20,000 steps for each of three step sizes:

step ss accepted chain averages of θ\theta
0.010.01 97% from 0.600.60 to 0.670.67
0.30.3 46% from 0.6640.664 to 0.6680.668
33 6% from 0.6660.666 to 0.6720.672

The true posterior mean is 2/32/3. With a tiny step almost everything is accepted, but the chain crawls and has not crossed the posterior in 20,000 steps. With a huge step most candidates land outside (0,1)(0, 1) or far in the tails, and the chain sits still for long stretches. A high acceptance rate is not a goal by itself. For random-walk Metropolis, theory suggests tuning the step to an acceptance rate of about 0.440.44 in one dimension and about 0.230.23 in many.

The start has a price too. The chain starts from a point, not from pp, so its first states are biased toward the start. A toy chain with every number known shows how long that lasts:

Xt+1=aXt+1−a2 εt,εt∼N(0,1),0<a<1.X_{t+1} = a X_t + \sqrt{1 - a^2}\, \varepsilon_t, \qquad \varepsilon_t \sim \mathcal N(0, 1), \quad 0 < a < 1 .

It keeps N(0,1)\mathcal N(0, 1) stationary, and taking expectations gives EXt=atx0\mathbb E X_t = a^t x_0. From x0=10x_0 = 10 with a=0.7a = 0.7, the bias drops below 0.010.01 after 20 steps. The early part of the run, the burn-in, is thrown away. No length suits every chain: the closer aa is to 11, the longer the chain remembers its start.

Gibbs sampling

Often the target lives on several coordinates, and the distribution of each coordinate given all the others is easy to sample. Gibbs sampling updates one coordinate at a time from that conditional distribution. It is Metropolis–Hastings whose proposal is the target's own conditional, and then the acceptance ratio is exactly 11: every update is accepted.

The bivariate normal from the topic The multivariate Gaussian shows how it moves. Let both coordinates have variance 11 and correlation ρ\rho. The conditionals are

X1∣X2=x2∼N(ρx2, 1−ρ2),X2∣X1=x1∼N(ρx1, 1−ρ2).X_1 \mid X_2 = x_2 \sim \mathcal N(\rho x_2,\ 1 - \rho^2), \qquad X_2 \mid X_1 = x_1 \sim \mathcal N(\rho x_1,\ 1 - \rho^2).

One sweep draws a new x1x_1 given x2x_2, then a new x2x_2 given that x1x_1. Every update moves along a coordinate axis. For strongly correlated coordinates the density is a narrow ellipse along the diagonal, and the conditional standard deviation 1−ρ2\sqrt{1 - \rho^2} is small: 0.440.44 for ρ=0.9\rho = 0.9, 0.140.14 for ρ=0.99\rho = 0.99. The chain climbs the diagonal in a zigzag of tiny steps.

Substituting one update into the other shows how slow that is. The successive values of x1x_1 form exactly the toy chain of the previous block, with a=ρ2a = \rho^2. For ρ=0.99\rho = 0.99 that is a=0.98a = 0.98: almost no forgetting from one sweep to the next. Reparametrizing to remove the correlation, or updating correlated coordinates together in a block, fixes it.

Gibbs sampling is the workhorse for models whose conditionals are conjugate, such as topic models and hierarchical Bayesian models. The course Bayesian Methods in Machine Learning builds such samplers.

The effective sample size

After burn-in the chain samples pp, but its states are still correlated. How much are nn of them worth? Let σ2=Var⁡pf(X)\sigma^2 = \operatorname{Var}_p f(X) and let ρk\rho_k be the correlation between f(Xt)f(X_t) and f(Xt+k)f(X_{t+k}), the autocorrelation at lag kk. Expanding the variance of the average into covariances, as in the topic Joint distributions and independence, gives for large nn

Var⁡(1n∑t=1nf(Xt))≈σ2τn,τ=1+2∑k≥1ρk.\operatorname{Var}\Big(\frac1n \sum_{t=1}^n f(X_t)\Big) \approx \frac{\sigma^2 \tau}{n}, \qquad \tau = 1 + 2 \sum_{k \ge 1} \rho_k .

The number τ\tau is the integrated autocorrelation time. The chain behaves like n/τn/\tau independent samples, its effective sample size:

ESS=nτ.\text{ESS} = \frac{n}{\tau} .

The Monte Carlo error bar becomes σ/ESS\sigma/\sqrt{\text{ESS}} instead of σ/n\sigma/\sqrt n. This is the cost of dependence between states that the topic Markov chains warned about. For the toy chain, ρk=ak\rho_k = a^k and the geometric series gives τ=(1+a)/(1−a)\tau = (1 + a)/(1 - a), so a=0.7a = 0.7 already makes every state worth less than a fifth of an independent sample.

The three coin chains from the table, 20,000 steps each, are worth roughly 30, 4,500 and 700 independent samples. The middle step size is about 150 times better than the tiny one, and its error bar is about 0.0020.002 instead of 0.0240.024.

One last failure no number from a single chain can show. Take a target with two separated modes, an equal mixture of two normals with standard deviation 0.60.6, centred at −3-3 and 33. A random walk with step 0.50.5 started at −3-3 spends all of 20,000 steps in the left mode. Its trace looks healthy and its ESS is fine, yet half of the probability is missing. The practical defence is to run several chains from dispersed starting points and compare them. If they disagree, as they would here, none of them has finished; the R^\hat R statistic formalizes this comparison of variance between chains and within them.

The course in review

MCMC closes the course, and it uses almost all of it. Look back at the question the course started with: how do we reason exactly about what we cannot predict, and how do we learn about the world from random data?

  • Reasoning exactly. Outcomes, events and Kolmogorov's axioms, conditional probability and Bayes' formula, random variables, expectations, joint distributions and the multivariate Gaussian. One toss of a coin is unpredictable, but its probabilities obey exact rules.
  • Averages become reliable. Inequalities, the law of large numbers and the central limit theorem. One draw is random; the average of many hardly is, and we know by how much it can stray.
  • Learning from data. Estimators, maximum likelihood, Bayesian inference, confidence intervals and tests turn a random sample into statements about the world, with an honest measure of uncertainty.
  • Computing what we cannot integrate. Markov chains, Monte Carlo and MCMC replace intractable sums and integrals by simulation, and the same limit theorems measure the error of the simulation.

Two later courses start where this one stops.

Bayesian Methods in Machine Learning applies these samplers to real models. Its topics Monte Carlo and Markov chains and Gibbs sampling and Metropolis–Hastings go deeper: asymmetric proposals, Gibbs sweeps for models with several unknown parameters, blocked and collapsed Gibbs. Next to sampling the course puts variational inference, which approximates a posterior by optimization instead.

Generative Models meets densities known only up to a constant in models of images. The gradient of log⁡p~\log \tilde p equals the gradient of log⁡p\log p and does not need ZZ either. The topic Sampling unnormalized densities: MALA and HMC uses it to push proposals uphill, and the topic Energy-based models trains models whose normalizing constant is never computed. The Machine Learning course, in turn, builds on the whole of this one.

This is the end of the course.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.