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 . Its samplers need either a formula for the inverse CDF or a proposal 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 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:
Here happens to have a formula: the posterior is with mean , 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 becomes an integral over a hundred dimensions that nobody can compute. The unnormalized density stays cheap: one factor per observation.
What can we do with alone? We can compare two points. The constant cancels in a ratio:
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 . Read backwards: if we build a chain whose stationary distribution is , running it produces samples from . This is Markov chain Monte Carlo (MCMC). The whole topic is about building such a chain from ratios of .
Detailed balance
In the topic Markov chains the transition matrix was given, and we solved for . Now the problem runs the other way: is given, and we need a that keeps it. The equation has many solutions , and it is hard to aim at it directly. A simpler, local condition is enough. Write for the probability of a step from to . The chain satisfies detailed balance with respect to if
Read as a flow: in equilibrium, the probability that a step goes from to . Detailed balance says that between every pair of states the traffic is the same in both directions. Summing over and using that the moves out of sum to one:
The left side is , so : the target is stationary. On a continuous state space 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, , satisfies it for every , 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 and staying with probability , 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 it needs a proposal distribution that is easy to sample. From the current state :
- draw a candidate ;
- accept it with probability
- if accepted, the next state is ; otherwise the next state is again.
The unknown would appear in the numerator and the denominator, so it cancels and never has to be computed. In code one compares logarithms, with , because a product of many likelihood factors underflows.
The most common proposal is a random step, with and a step size . It is symmetric, , so the proposal terms cancel too and
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 in 1970.
An example with , a standard normal without its constant. From the candidate goes downhill and is accepted with probability . From the candidate goes uphill, so . The rare move out and the certain move back carry the same flow, because : that is detailed balance at work.
Why the chain lands on p
Why does Metropolis–Hastings satisfy detailed balance? For the chain moves from to only by proposing and accepting it, so . Multiply by and take the factor inside the minimum:
The right side does not change when and swap places, so it also equals . That is detailed balance. For the condition reads and holds trivially. So is stationary, rejections included.
On a finite state space the whole chain fits into a transition matrix. Take three states with , so , and propose one of the two other states with probability each. From state 1 every candidate is uphill and accepted. From state 2 the move to state 1 is accepted with probability , the move to state 3 always:
The diagonal entry is the probability that the proposal from state 2 is rejected. With the third row one checks 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 instead of .
Step size and burn-in
Let us run random-walk Metropolis on the coin posterior . Two rules about the support come straight from the ratio. Start where , here . A candidate outside has , so 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 | accepted | chain averages of |
|---|---|---|
| 97% | from to | |
| 46% | from to | |
| 6% | from to |
The true posterior mean is . 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 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 in one dimension and about in many.
The start has a price too. The chain starts from a point, not from , so its first states are biased toward the start. A toy chain with every number known shows how long that lasts:
It keeps stationary, and taking expectations gives . From with , the bias drops below after 20 steps. The early part of the run, the burn-in, is thrown away. No length suits every chain: the closer is to , 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 : every update is accepted.
The bivariate normal from the topic The multivariate Gaussian shows how it moves. Let both coordinates have variance and correlation . The conditionals are
One sweep draws a new given , then a new given that . 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 is small: for , for . 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 form exactly the toy chain of the previous block, with . For that is : 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 , but its states are still correlated. How much are of them worth? Let and let be the correlation between and , the autocorrelation at lag . Expanding the variance of the average into covariances, as in the topic Joint distributions and independence, gives for large
The number is the integrated autocorrelation time. The chain behaves like independent samples, its effective sample size:
The Monte Carlo error bar becomes instead of . This is the cost of dependence between states that the topic Markov chains warned about. For the toy chain, and the geometric series gives , so 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 instead of .
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 , centred at and . A random walk with step started at 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 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 equals the gradient of and does not need 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.
Answers are saved on the server and tied to this browser until you sign in.