TL;DR
The Metropolis algorithm is a recipe for a random walk that spends time in each place in proportion to a target probability. At each step it proposes a random nearby move. If the move goes to a place the target likes more, it always takes it. If the move goes to a less likely place, it takes it only some of the time, with a chance equal to the ratio of the two target values. Running the walk for a long time gives samples from the target, and the normalising constant never has to be known.
Where you'll see it: in Bayesian inference when the posterior has no closed form, in statistical physics simulations of liquids and magnets, and as the engine behind most general-purpose MCMC software.
Intuition
A walker who checks the scenery
Imagine a hiker on a range of hills who wants to spend time at each spot in proportion to its height, so that high ground is visited more than low ground, but who cannot see the whole map. The hiker only knows, at the spot where they stand, how high it is and how high the spot next to them is. A simple rule works. Pick a random neighbouring spot. If it is higher, step there. If it is lower, flip a coin weighted by the height ratio: step there with that chance, otherwise stay put.
Why does this work? The walker is pulled toward high ground, but never fully stops going downhill. Lower spots are visited less often, but not never. Over a long walk the time spent on each spot settles into a fixed pattern, and that pattern is exactly the height profile the hiker wanted. The hiker never needed the total height summed over the range, only relative heights.
That is the problem the algorithm solves. In Monte Carlo work we want an average of some function over a distribution , but drawing directly from is often impossible. The probability of an observed dataset under a model, for instance, has an integral in its denominator that is intractable. The Metropolis algorithm sidesteps this by building a chain whose stationary distribution is , and then reading samples off the chain.
- acceptance chance when moving to x from x = 1
Why the ratio is enough
The target often arrives in unnormalised form. You know , which is proportional to the true density , but you do not know . Metropolis acceptance uses only the ratio , and in that ratio the unknown cancels. This is the feature that made the method useful in physics, where is the partition function of a system and is almost never computable, and it is the feature that makes it useful in Bayesian statistics, where is the evidence.
The math
The setting
Let be a target probability distribution over a state space , written as a density for continuous or as a probability vector for discrete states. We are allowed to evaluate for some unknown constant , and we want a Markov chain whose long-run behaviour matches .
A Markov chain is specified by a transition rule that says where the next state comes from. Here the rule is built from two pieces.
Let be a proposal distribution, the chance of suggesting when at , and assume it is symmetric: . Given the current state , draw a proposal and accept it with probability
If accepted, set . If rejected, set . The transition kernel for is .
Read the formula in words. The proposal is a random suggestion. The acceptance rule says: if the suggested place has at least as much target mass as the current place, accept. Otherwise accept with probability equal to the ratio. Rejection is not wasted effort. The chain stays put, and that stay counts as a sample.
Why it targets
The key fact is Detailed Balance. A chain satisfies detailed balance with respect to when
for all and . We check it for . Without loss of generality suppose . Then and . The two sides are
Using symmetry , the second expression is . Both sides match. The case is the same with the roles swapped. The diagonal is trivially balanced.
Detailed balance implies stationarity. Integrating (or summing) both sides of the balance equation over gives , which says is unchanged by one step of the chain. If the chain is also irreducible and aperiodic, the ergodic theorem says the time average of converges to . Those two conditions hold for a proposal that can reach every region of the space and that allows staying put, which the rejection step provides.
The normalising constant cancels
Divide the acceptance formula by and the constant disappears:
So the chain behaves identically whether you feed it or . This is the whole reason the method is practical.
A random-walk version
The most common choice is a Gaussian random walk. Propose with , where is a step size. The proposal is symmetric because and have the same distribution. The step size controls the trade-off discussed below.
- Choose a starting value and a step size . Set .
- Draw and set .
- Compute .
- Draw . If , set ; otherwise set .
- Increase and repeat from step 2 until you have enough samples. Discard an initial burn-in segment before averaging.
The procedure is easiest to see as a loop.
flowchart TD
A[Current state x] --> B[Propose x' from a symmetric proposal]
B --> C[Compute ratio of target values r]
C --> D{Draw u uniform on 0 to 1}
D -->|u below min of 1 and r| E[Move to x']
D -->|otherwise| F[Stay at x]
E --> A
F --> A
Worked examples
Take three states and a target . The proposal picks one of the two other states uniformly, so for every pair , and this is symmetric.
- Acceptance from state 1: moving to 2 has ratio , so . Moving to 3 has ratio , so . Therefore , , and .
- Acceptance from state 2: moving to 1 has ratio , so . Moving to 3 has ratio , so . The stay probability is .
- Acceptance from state 3: moving to 1 has ratio , so . Moving to 2 has ratio , so . The stay probability is .
- Check detailed balance on the pair : and . Equal.
- Check the pair : and . Equal.
- Check stationarity at state 1: . The same check holds for the other states.
Interpretation: the chain visits state 3 most, in proportion to its probability 0.5. The method never needed to know the proposal rule beyond symmetry, and the three acceptance rules are the only place the target enters. In a three-state example you could solve for directly. The point is that the same acceptance logic scales to a continuous space where no such solve exists.
Let the unnormalised target be , which is a standard Gaussian up to a constant that we pretend not to know. Use the random-walk proposal with step . The current state is .
- Draw a proposal , giving .
- Compute and .
- The ratio is .
- The acceptance probability is .
- Draw . Since , accept. The new state is .
- Now try a second proposal from with , giving . The ratio is , so and the move is accepted without a random draw.
- Suppose instead the chain is at and proposes . The ratio is . If , then and the chain stays at . The rejected move still contributes a sample equal to .
Interpretation: a move into a higher-density region is always taken, and a move into a lower-density region is taken with a chance that shrinks as the density drops. Over many steps the visit pattern concentrates around the centre of the Gaussian in the right proportions. The unknown normalising constant never entered any of the arithmetic.
Suppose a random walk has step on the same target. Nearly every proposal is close to the current point, so the density ratio is near 1 and almost every move is accepted. The chain moves, but only by about per step, so to cross a region of width 4 it needs on the order of steps. Now take . Almost every proposal lands in a region of tiny density, so most are rejected, and the chain stays put for long runs. Both extremes produce correct long-run averages, but they produce them slowly. A step size of order 1 to 2.4 is the standard starting point for a one-dimensional Gaussian target. These numbers are illustrative rules of thumb rather than results from a simulation.
Tradeoffs and failure modes
The Metropolis algorithm is simple, general, and needs only a way to evaluate . Its weaknesses come from the random walk.
| Situation | Problem | Better choice |
|---|---|---|
| Step size too large | Most proposals are rejected and the chain stalls | Tune so the acceptance rate is roughly 20 to 50 percent in low dimensions |
| Step size too small | The chain moves in tiny steps and is highly autocorrelated | Increase , or use a proposal informed by the target |
| Several separated modes | The chain can get stuck in one mode for a very long time | Tempering, parallel chains from different starts, or a larger-jump proposal |
| High dimension | The acceptance rate collapses unless the step shrinks with dimension | Hamiltonian Monte Carlo or other gradient-informed moves |
| Asymmetric proposal | The acceptance formula above is no longer correct | Use the Metropolis–Hastings correction with a Hastings ratio |
| Need for independent draws | Successive samples are correlated, so effective sample size is smaller than the chain length | Thin the chain, or run many chains and diagnose mixing |
A common failure is to trust a single short run. The chain's first samples depend on the starting point, so a burn-in period is discarded. Then autocorrelation means the samples are not independent, and the effective sample size is roughly , where is the integrated autocorrelation time. Always check trace plots and the autocorrelation of the output before believing an average.
History
In 1953 Nicholas Metropolis, Arianna and Marshall Rosenbluth, Augusta and Edward Teller published "Equation of State Calculations by Fast Computing Machines" in the Journal of Chemical Physics. They were modelling a gas of interacting molecules on an early electronic computer at Los Alamos, where direct evaluation of the sum over configurations was impossible. Their method proposed a small random displacement of one particle and accepted it according to the change in Boltzmann weight. It is the origin of the acceptance rule above, which is why the Boltzmann distribution is the natural target in that setting.
In 1970 W. K. Hastings, writing in Biometrika, generalised the rule to asymmetric proposals by adding a correction factor. The combined method is called Metropolis–Hastings, and it is the version most people mean when they say "Metropolis" today.
The method caught on for three reasons. It needs only ratios of the target. It applies to any state space, discrete or continuous. And it is easy to implement in a few lines. Statisticians adopted it for Bayesian posteriors in the late twentieth century, once computers were fast enough for long chains, and it became one of the workhorse algorithms behind modern probabilistic programming.
Check yourself
QuestionRecall: what is the acceptance probability for a proposal that moves to a state with higher target value than the current state?Show answer
It is 1. The formula is , and when the ratio exceeds 1 the minimum is 1. Moves toward more probable states are always accepted.
QuestionComputation: the current state has and a symmetric proposal suggests a state with . What is the acceptance probability?Show answer
The ratio is , and the minimum of 1 and 0.25 is . The chain moves to the new state with chance 25 percent and stays at otherwise.
QuestionWhy does the algorithm not need to know the normalising constant of the target?Show answer
The acceptance rule depends only on the ratio . Both densities carry the same unknown constant, which divides out, so never appears in the transition rule. This is what allows MCMC to work for posteriors and for physical partition functions.
QuestionApplied: a sampler for a posterior is accepting 95 percent of proposals with a tiny step size and its trace plot drifts slowly across the range. What is wrong and what would you change?Show answer
The high acceptance rate means the step is too small, so the chain moves little per step and is strongly autocorrelated. The fix is to increase the step size until the acceptance rate falls into a moderate range, typically 20 to 50 percent in low dimensions, and then check the autocorrelation of the output again. Increasing the step too far brings the opposite problem of frequent rejection.
Sources
- Metropolis, Rosenbluth, Rosenbluth, Teller, Teller (1953), "Equation of State Calculations by Fast Computing Machines", doi
- Hastings (1970), "Monte Carlo sampling methods using Markov chains and their applications", doi
- Metropolis–Hastings algorithm (Wikipedia)
- Bishop, Pattern Recognition and Machine Learning, §11.2