Search

Search papers and lessons

Metropolis Algorithm

Level 3 · 13 min read

A random-walk recipe whose long-run visit frequencies match a target distribution: propose a move, always accept uphill moves, and accept downhill ones with the density ratio's chance.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Linear algebra
  • Sampling
  • Stochastic processes
  • Discrete math
  • Sign in to see your progress

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 ff over a distribution π\pi, but drawing directly from π\pi 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 π\pi, and then reading samples off the chain.

−3−2−1012300.20.40.60.81proposed position xacceptance chance
  • acceptance chance when moving to x from x = 1
Starting at 1 with target exp(-x^2/2), a proposal to a position x is always accepted if it is at least as likely as the current spot, and accepted with chance exp(-(x^2-1)/2) otherwise.

Why the ratio is enough

The target often arrives in unnormalised form. You know π~(x)\tilde{\pi}(x), which is proportional to the true density π(x)=π~(x)/Z\pi(x) = \tilde{\pi}(x)/Z, but you do not know ZZ. Metropolis acceptance uses only the ratio π(x′)/π(x)\pi(x')/\pi(x), and in that ratio the unknown ZZ cancels. This is the feature that made the method useful in physics, where ZZ 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 ZZ is the evidence.

The math

The setting

Let π\pi be a target probability distribution over a state space X\mathcal{X}, written as a density π(x)\pi(x) for continuous xx or as a probability vector for discrete states. We are allowed to evaluate π~(x)=c π(x)\tilde{\pi}(x) = c\,\pi(x) for some unknown constant c>0c > 0, and we want a Markov chain X0,X1,X2,…X_0, X_1, X_2, \dots whose long-run behaviour matches π\pi.

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.

Definition: Metropolis transition rule

Let Q(x→x′)Q(x \to x') be a proposal distribution, the chance of suggesting x′x' when at xx, and assume it is symmetric: Q(x→x′)=Q(x′→x)Q(x \to x') = Q(x' \to x). Given the current state xx, draw a proposal x′∼Q(x→⋅)x' \sim Q(x \to \cdot) and accept it with probability

α(x→x′)=min⁡ ⁣(1,π~(x′)π~(x)).\alpha(x \to x') = \min\!\left(1, \frac{\tilde{\pi}(x')}{\tilde{\pi}(x)}\right).

If accepted, set Xt+1=x′X_{t+1} = x'. If rejected, set Xt+1=xX_{t+1} = x. The transition kernel for x′≠xx' \neq x is K(x→x′)=Q(x→x′) α(x→x′)K(x \to x') = Q(x \to x')\,\alpha(x \to x').

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 π\pi

The key fact is Detailed Balance. A chain satisfies detailed balance with respect to π\pi when

π(x) K(x→x′)=π(x′) K(x′→x)\pi(x)\, K(x \to x') = \pi(x')\, K(x' \to x)

for all xx and x′x'. We check it for x≠x′x \neq x'. Without loss of generality suppose π(x′)≥π(x)\pi(x') \geq \pi(x). Then α(x→x′)=1\alpha(x \to x') = 1 and α(x′→x)=π(x)/π(x′)\alpha(x' \to x) = \pi(x)/\pi(x'). The two sides are

π(x) Q(x→x′)⋅1andπ(x′) Q(x′→x) π(x)π(x′).\pi(x)\, Q(x \to x')\cdot 1 \quad\text{and}\quad \pi(x')\, Q(x' \to x)\,\frac{\pi(x)}{\pi(x')}.

Using symmetry Q(x→x′)=Q(x′→x)Q(x \to x') = Q(x' \to x), the second expression is π(x) Q(x→x′)\pi(x)\,Q(x \to x'). Both sides match. The case π(x′)<π(x)\pi(x') < \pi(x) is the same with the roles swapped. The diagonal x=x′x = x' is trivially balanced.

Detailed balance implies stationarity. Integrating (or summing) both sides of the balance equation over xx gives ∫π(x)K(x→x′) dx=π(x′)\int \pi(x)K(x \to x')\,dx = \pi(x'), which says π\pi is unchanged by one step of the chain. If the chain is also irreducible and aperiodic, the ergodic theorem says the time average of f(Xt)f(X_t) converges to Eπ[f(X)]\mathbb{E}_\pi[f(X)]. 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 π~(x)\tilde{\pi}(x) and the constant disappears:

π~(x′)π~(x)=c π(x′)c π(x)=π(x′)π(x).\frac{\tilde{\pi}(x')}{\tilde{\pi}(x)} = \frac{c\,\pi(x')}{c\,\pi(x)} = \frac{\pi(x')}{\pi(x)}.

So the chain behaves identically whether you feed it π~\tilde{\pi} or π\pi. This is the whole reason the method is practical.

A random-walk version

The most common choice is a Gaussian random walk. Propose x′=x+εx' = x + \varepsilon with ε∼N(0,s2)\varepsilon \sim \mathcal{N}(0, s^2), where ss is a step size. The proposal is symmetric because ε\varepsilon and −ε-\varepsilon have the same distribution. The step size ss controls the trade-off discussed below.

Algorithm
Metropolis with a Gaussian random walk
  1. Choose a starting value x0x_0 and a step size ss. Set t=0t = 0.
  2. Draw ε∼N(0,s2)\varepsilon \sim \mathcal{N}(0, s^2) and set x′=Xt+εx' = X_t + \varepsilon.
  3. Compute r=π~(x′)/π~(Xt)r = \tilde{\pi}(x') / \tilde{\pi}(X_t).
  4. Draw u∼Uniform(0,1)u \sim \text{Uniform}(0, 1). If u<min⁡(1,r)u \lt \min(1, r), set Xt+1=x′X_{t+1} = x'; otherwise set Xt+1=XtX_{t+1} = X_t.
  5. Increase tt 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

Example
A three-state chain worked by hand

Take three states {1,2,3}\{1, 2, 3\} and a target π=(0.2, 0.3, 0.5)\pi = (0.2,\ 0.3,\ 0.5). The proposal picks one of the two other states uniformly, so Q(i→j)=1/2Q(i \to j) = 1/2 for every pair i≠ji \neq j, and this is symmetric.

  1. Acceptance from state 1: moving to 2 has ratio 0.3/0.2=1.50.3/0.2 = 1.5, so α=1\alpha = 1. Moving to 3 has ratio 0.5/0.2=2.50.5/0.2 = 2.5, so α=1\alpha = 1. Therefore P12=1/2P_{12} = 1/2, P13=1/2P_{13} = 1/2, and P11=0P_{11} = 0.
  2. Acceptance from state 2: moving to 1 has ratio 0.2/0.3=2/30.2/0.3 = 2/3, so P21=12⋅23=13P_{21} = \tfrac12 \cdot \tfrac23 = \tfrac13. Moving to 3 has ratio 0.5/0.3>10.5/0.3 \gt 1, so P23=12P_{23} = \tfrac12. The stay probability is P22=1−13−12=16P_{22} = 1 - \tfrac13 - \tfrac12 = \tfrac16.
  3. Acceptance from state 3: moving to 1 has ratio 0.2/0.5=0.40.2/0.5 = 0.4, so P31=12⋅0.4=0.2P_{31} = \tfrac12 \cdot 0.4 = 0.2. Moving to 2 has ratio 0.3/0.5=0.60.3/0.5 = 0.6, so P32=12⋅0.6=0.3P_{32} = \tfrac12 \cdot 0.6 = 0.3. The stay probability is P33=1−0.2−0.3=0.5P_{33} = 1 - 0.2 - 0.3 = 0.5.
  4. Check detailed balance on the pair (1,2)(1, 2): π1P12=0.2×0.5=0.10\pi_1 P_{12} = 0.2 \times 0.5 = 0.10 and π2P21=0.3×13=0.10\pi_2 P_{21} = 0.3 \times \tfrac13 = 0.10. Equal.
  5. Check the pair (2,3)(2, 3): π2P23=0.3×0.5=0.15\pi_2 P_{23} = 0.3 \times 0.5 = 0.15 and π3P32=0.5×0.3=0.15\pi_3 P_{32} = 0.5 \times 0.3 = 0.15. Equal.
  6. Check stationarity at state 1: (πP)1=π1P11+π2P21+π3P31=0+0.1+0.1=0.2=π1(\pi P)_1 = \pi_1 P_{11} + \pi_2 P_{21} + \pi_3 P_{31} = 0 + 0.1 + 0.1 = 0.2 = \pi_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 π\pi directly. The point is that the same acceptance logic scales to a continuous space where no such solve exists.

Example
One step of a random walk on an unnormalised Gaussian

Let the unnormalised target be π~(x)=exp⁡(−x2/2)\tilde{\pi}(x) = \exp(-x^2/2), which is a standard Gaussian up to a constant that we pretend not to know. Use the random-walk proposal with step s=1s = 1. The current state is Xt=1.0X_t = 1.0.

  1. Draw a proposal ε=0.5\varepsilon = 0.5, giving x′=1.5x' = 1.5.
  2. Compute π~(1.5)=exp⁡(−1.52/2)=exp⁡(−1.125)\tilde{\pi}(1.5) = \exp(-1.5^2/2) = \exp(-1.125) and π~(1.0)=exp⁡(−0.5)\tilde{\pi}(1.0) = \exp(-0.5).
  3. The ratio is r=exp⁡(−1.125+0.5)=exp⁡(−0.625)≈0.535r = \exp(-1.125 + 0.5) = \exp(-0.625) \approx 0.535.
  4. The acceptance probability is min⁡(1,0.535)=0.535\min(1, 0.535) = 0.535.
  5. Draw u=0.31u = 0.31. Since 0.31<0.5350.31 \lt 0.535, accept. The new state is Xt+1=1.5X_{t+1} = 1.5.
  6. Now try a second proposal from Xt+1=1.5X_{t+1} = 1.5 with ε=−2.2\varepsilon = -2.2, giving x′=−0.7x' = -0.7. The ratio is exp⁡(−(0.49−2.25)/2)=exp⁡(0.88)>1\exp(-(0.49 - 2.25)/2) = \exp(0.88) \gt 1, so α=1\alpha = 1 and the move is accepted without a random draw.
  7. Suppose instead the chain is at Xt=0.5X_t = 0.5 and proposes x′=−0.8x' = -0.8. The ratio is exp⁡(−(0.64−0.25)/2)=exp⁡(−0.195)≈0.823\exp(-(0.64 - 0.25)/2) = \exp(-0.195) \approx 0.823. If u=0.90u = 0.90, then 0.90>0.8230.90 \gt 0.823 and the chain stays at 0.50.5. The rejected move still contributes a sample equal to 0.50.5.

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 2π\sqrt{2\pi} never entered any of the arithmetic.

Example
Choosing the step size

Suppose a random walk has step s=0.1s = 0.1 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 0.10.1 per step, so to cross a region of width 4 it needs on the order of (4/0.1)2=1600(4/0.1)^2 = 1600 steps. Now take s=10s = 10. 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 π~\tilde{\pi}. Its weaknesses come from the random walk.

SituationProblemBetter choice
Step size too largeMost proposals are rejected and the chain stallsTune ss so the acceptance rate is roughly 20 to 50 percent in low dimensions
Step size too smallThe chain moves in tiny steps and is highly autocorrelatedIncrease ss, or use a proposal informed by the target
Several separated modesThe chain can get stuck in one mode for a very long timeTempering, parallel chains from different starts, or a larger-jump proposal
High dimensionThe acceptance rate collapses unless the step shrinks with dimensionHamiltonian Monte Carlo or other gradient-informed moves
Asymmetric proposalThe acceptance formula above is no longer correctUse the Metropolis–Hastings correction with a Hastings ratio
Need for independent drawsSuccessive samples are correlated, so effective sample size is smaller than the chain lengthThin 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 N/τN/\tau, where τ\tau 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 min⁡(1,π~(x′)/π~(x))\min(1, \tilde{\pi}(x')/\tilde{\pi}(x)), and when the ratio exceeds 1 the minimum is 1. Moves toward more probable states are always accepted.

QuestionComputation: the current state has π~(x)=0.8\tilde{\pi}(x) = 0.8 and a symmetric proposal suggests a state with π~(x′)=0.2\tilde{\pi}(x') = 0.2. What is the acceptance probability?Show answer

The ratio is 0.2/0.8=0.250.2/0.8 = 0.25, and the minimum of 1 and 0.25 is 0.250.25. The chain moves to the new state with chance 25 percent and stays at xx otherwise.

QuestionWhy does the algorithm not need to know the normalising constant ZZ of the target?Show answer

The acceptance rule depends only on the ratio π(x′)/π(x)\pi(x')/\pi(x). Both densities carry the same unknown constant, which divides out, so ZZ 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