Search

Search papers and lessons

Markov Chain Monte Carlo

Level 3 · 14 min read

Markov chain Monte Carlo draws samples from a distribution that is hard to sample directly by running a random walk whose long-run visit frequencies match that distribution.

On this page

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

TL;DR

Markov chain Monte Carlo (MCMC) draws samples from a probability distribution that is too hard to sample directly, often because you only know it up to a constant. It builds a random walk whose next step depends only on where it stands now. The rules are chosen so that, after a warm-up period, the walk spends time in each region in proportion to the target probability. Averages along the walk then estimate the quantities you care about.

Where you'll see it: in Bayesian statistics, where the posterior distribution over model parameters rarely has a formula you can sample from, and in statistical physics, where it estimates averages over enormous numbers of configurations.

Intuition

A hiker who samples by walking

Picture a foggy mountain range. You want to know how much time a walker spends at each place if the walker is more likely to linger in some spots than others. You cannot see the map. You can only compare the "height" (the target probability) of where you stand with the height of a nearby spot. The rule is simple. Always step to a nearby spot if it is higher. If it is lower, step there anyway with probability equal to the ratio of the two heights, and otherwise stay put. Run this for long enough and the fraction of time spent at each place matches the landscape, even though you never drew the whole map.

That is MCMC. The only thing it needs is the ability to compare two points.

Why the naive methods fail

Direct sampling works when you have a formula you can invert or a simple envelope to reject against. It breaks down as soon as the distribution has many dimensions, which is the normal situation for a Bayesian model with dozens of parameters. The normalising constant of such a distribution is an integral you cannot compute, and rejection sampling wastes almost every proposal in high dimensions. MCMC sidesteps both problems. Its acceptance rule uses only ratios of the target, and in those ratios the unknown constant cancels.

The price is that the walk is not a stack of independent draws. Each sample depends on the last one, and the walk may need a long time to explore the whole landscape.

−4−3−2−1012300.10.20.30.4xdensity
  • two-peak target
A target with two peaks. A walk that starts near one peak can take a very long time to find the other. That is the main practical danger of MCMC.

The loop, step by step

The standard algorithm, Metropolis-Hastings, repeats one small loop. The diagram below shows it.

flowchart TD
  A["Current state x"] --> B["Propose a new state x' near x"]
  B --> C["Compute the ratio of target values at x' and x"]
  C --> D{"Accept? Random number is below min of 1 and the ratio"}
  D -- yes --> E["Move to x'"]
  D -- no --> F["Stay at x"]
  E --> G["Record the current state as a sample"]
  F --> G
  G --> A

Note the step that often surprises beginners. When a proposal is rejected, the walk stays where it is, and that repeated position is still recorded as a sample. Dropping rejected steps would bias the result.

The math

What we want to compute

Let π(x)\pi(x) be the target distribution over a space of values xx. We usually want an expectation

Eπ[f(X)]=∫f(x) π(x) dx,\mathbb{E}_\pi[f(X)] = \int f(x)\, \pi(x)\, dx,

for some function ff, such as a posterior mean when f(x)=xf(x) = x. The Monte Carlo method estimates this by averaging ff over samples from π\pi; the difficulty is getting those samples. Often we can only evaluate π~(x)\tilde{\pi}(x), which is proportional to π(x)\pi(x), so that π(x)=π~(x)/Z\pi(x) = \tilde{\pi}(x)/Z with Z=∫π~(x) dxZ = \int \tilde{\pi}(x)\, dx unknown. In Bayesian inference (Bayes' rule) π~\tilde{\pi} is likelihood times prior, and ZZ is the evidence. MCMC needs only π~\tilde{\pi}, because every acceptance decision depends on the ratio π(x′)/π(x)=π~(x′)/π~(x)\pi(x')/\pi(x) = \tilde{\pi}(x')/\tilde{\pi}(x) and ZZ cancels.

Markov chains with a chosen stationary distribution

A Markov chain moves from xx to x′x' according to a transition kernel K(x→x′)K(x \to x'), which for each xx is a density over x′x' that integrates to 1. If XtX_t has distribution μt\mu_t, then the next distribution is

μt+1(x′)=∫μt(x) K(x→x′) dx.\mu_{t+1}(x') = \int \mu_t(x)\, K(x \to x')\, dx.

A distribution π\pi is stationary for KK if running one step leaves it unchanged, that is π(x′)=∫π(x) K(x→x′) dx\pi(x') = \int \pi(x)\, K(x \to x')\, dx for every x′x'.

The easiest way to guarantee this is detailed balance:

π(x) K(x→x′)=π(x′) K(x′→x)for all x,x′.\pi(x)\, K(x \to x') = \pi(x')\, K(x' \to x) \quad \text{for all } x, x'.

Detailed balance implies stationarity. Integrate both sides over xx. The right side becomes π(x′)∫K(x′→x) dx=π(x′)\pi(x') \int K(x' \to x)\, dx = \pi(x'), which is exactly the stationarity equation.

The ergodic theorem for Markov chains gives the two facts MCMC needs. If the chain is irreducible (every region can be reached from every other) and aperiodic (it does not cycle with a fixed period), then μt\mu_t converges to π\pi from any starting point, and time averages converge:

1N∑t=1Nf(Xt)  ⟶  Eπ[f(X)]as N→∞.\frac{1}{N}\sum_{t=1}^{N} f(X_t) \;\longrightarrow\; \mathbb{E}_\pi[f(X)] \quad \text{as } N \to \infty.

Because successive samples are correlated, the variance of this estimate is roughly Varπ(f) τ/N\mathrm{Var}_\pi(f)\,\tau / N, where τ\tau is the integrated autocorrelation time. The effective sample size is N/τN/\tau. A chain with large τ\tau needs many more steps for the same accuracy, which is why diagnosing autocorrelation matters.

Metropolis-Hastings

Choose a proposal distribution q(x′∣x)q(x' \mid x), which is any distribution we can sample from. Given the current state xx, draw x′∼q(⋅∣x)x' \sim q(\cdot \mid x) and accept it with probability

α(x,x′)=min⁡ ⁣(1,  π(x′) q(x∣x′)π(x) q(x′∣x)).\alpha(x, x') = \min\!\left(1,\; \frac{\pi(x')\, q(x \mid x')}{\pi(x)\, q(x' \mid x)}\right).

If the proposal is rejected, stay at xx. For x′≠xx' \neq x the kernel is K(x→x′)=q(x′∣x) α(x,x′)K(x \to x') = q(x' \mid x)\, \alpha(x, x').

Detailed balance holds. Write r=π(x′)q(x∣x′)/(π(x)q(x′∣x))r = \pi(x')q(x \mid x')/(\pi(x)q(x' \mid x)). Then

π(x) q(x′∣x) min⁡(1,r)=min⁡(π(x) q(x′∣x),  π(x′) q(x∣x′)).\pi(x)\, q(x' \mid x)\, \min(1, r) = \min\big(\pi(x)\, q(x' \mid x),\; \pi(x')\, q(x \mid x')\big).

The right side is symmetric under swapping xx and x′x', so π(x)K(x→x′)=π(x′)K(x′→x)\pi(x) K(x \to x') = \pi(x') K(x' \to x).

The special case of random-walk Metropolis uses a symmetric proposal, such as a normal centred on the current state with standard deviation ss. Then q(x∣x′)=q(x′∣x)q(x \mid x') = q(x' \mid x) cancels and the acceptance rule becomes α=min⁡(1,π(x′)/π(x))\alpha = \min(1, \pi(x')/\pi(x)). The step size ss is the one knob you tune. If ss is too small, the walk moves slowly and its samples are highly correlated. If ss is too large, most proposals land in low-probability places and get rejected, so the walk again sits still.

Worked examples

Example
Three states, by hand

Take three states with unnormalised target weights 11, 22, 33, so π=(1/6, 1/3, 1/2)\pi = (1/6,\ 1/3,\ 1/2). From the current state, pick one of the other two states with probability 1/21/2 each. The proposal is symmetric, so α=min⁡(1,π(new)/π(current))\alpha = \min(1, \pi(\text{new})/\pi(\text{current})).

  1. From state 1 (weight 1): propose 2, accept with min⁡(1,2/1)=1\min(1, 2/1) = 1, so K(1→2)=1/2K(1 \to 2) = 1/2. Propose 3, accept with 1, so K(1→3)=1/2K(1 \to 3) = 1/2. Stay: K(1→1)=0K(1 \to 1) = 0.
  2. From state 2 (weight 2): propose 1, accept with min⁡(1,1/2)=1/2\min(1, 1/2) = 1/2, so K(2→1)=1/4K(2 \to 1) = 1/4. Propose 3, accept with 1, so K(2→3)=1/2K(2 \to 3) = 1/2. Stay: K(2→2)=1/4K(2 \to 2) = 1/4.
  3. From state 3 (weight 3): propose 1, accept with 1/31/3, so K(3→1)=1/6K(3 \to 1) = 1/6. Propose 2, accept with 2/32/3, so K(3→2)=1/3K(3 \to 2) = 1/3. Stay: K(3→3)=1/2K(3 \to 3) = 1/2.
  4. Check detailed balance on the pair (1, 2): π1K(1→2)=(1/6)(1/2)=1/12\pi_1 K(1 \to 2) = (1/6)(1/2) = 1/12 and π2K(2→1)=(1/3)(1/4)=1/12\pi_2 K(2 \to 1) = (1/3)(1/4) = 1/12. They match.
  5. Start in state 1. After one step the distribution is (0, 1/2, 1/2)(0,\ 1/2,\ 1/2). After two steps, P(state 2)=(1/2)(1/4)+(1/2)(1/3)=7/24≈0.292P(\text{state }2) = (1/2)(1/4) + (1/2)(1/3) = 7/24 \approx 0.292, and P(state 1)=(1/2)(1/4)+(1/2)(1/6)=5/24P(\text{state }1) = (1/2)(1/4) + (1/2)(1/6) = 5/24.
  6. After three steps, P(state 1)=(7/24)(1/4)+(1/2)(1/6)=15/96≈0.156P(\text{state }1) = (7/24)(1/4) + (1/2)(1/6) = 15/96 \approx 0.156, and P(state 2)=(5/24)(1/2)+(7/24)(1/4)+(1/2)(1/3)=33/96≈0.344P(\text{state }2) = (5/24)(1/2) + (7/24)(1/4) + (1/2)(1/3) = 33/96 \approx 0.344. The rest is 1/21/2.
  7. The target is (0.167, 0.333, 0.500)(0.167,\ 0.333,\ 0.500). After two steps, state 2 was 0.0420.042 too low. After three steps the error is about 0.0100.010.

Interpretation: the chain never computed π\pi. It followed local rules that only compare two weights, and its distribution converged to the weights anyway.

Example
Estimating a coin's bias

You flip a coin 10 times and get 7 heads. With a uniform prior on the bias θ\theta, the posterior is proportional to θ7(1−θ)3\theta^7(1-\theta)^3. That is a Beta(8, 4) distribution, with normalised density 1320 θ7(1−θ)31320\,\theta^7(1-\theta)^3, but suppose we only have the unnormalised form π~(θ)=θ7(1−θ)3\tilde{\pi}(\theta) = \theta^7(1-\theta)^3. We run random-walk Metropolis with step s=0.2s = 0.2, starting at θ0=0.5\theta_0 = 0.5, where π~(0.5)=0.510≈0.000977\tilde{\pi}(0.5) = 0.5^{10} \approx 0.000977.

  1. Propose θ′=0.7\theta' = 0.7. π~(0.7)=0.77×0.33≈0.08235×0.027=0.002224\tilde{\pi}(0.7) = 0.7^7 \times 0.3^3 \approx 0.08235 \times 0.027 = 0.002224. The ratio to the current value is 0.002224/0.000977≈2.280.002224 / 0.000977 \approx 2.28, which is at least 1, so accept. Now θ1=0.7\theta_1 = 0.7.
  2. From 0.7, propose θ′=0.9\theta' = 0.9. π~(0.9)=0.97×0.13≈0.4783×0.001=0.000478\tilde{\pi}(0.9) = 0.9^7 \times 0.1^3 \approx 0.4783 \times 0.001 = 0.000478. The ratio is 0.000478/0.002224≈0.2150.000478 / 0.002224 \approx 0.215. Draw a uniform number u=0.43u = 0.43. Since 0.43>0.2150.43 \gt 0.215, reject. The walk stays at θ2=0.7\theta_2 = 0.7, and that repeat is recorded.
  3. From 0.7, propose θ′=0.5\theta' = 0.5. The ratio is 0.000977/0.002224≈0.4390.000977 / 0.002224 \approx 0.439. Draw u=0.12u = 0.12. Since 0.12<0.4390.12 \lt 0.439, accept. Now θ3=0.5\theta_3 = 0.5.

Interpretation: the normalising constant never appeared. Each decision compared two values of π~\tilde{\pi}. Run for many thousands of steps, the visits would bunch around 0.7, with spread matching the Beta(8, 4) shape plotted below. The draws uu here were chosen for illustration. A real run draws them at random.

00.20.40.60.810123θ (coin bias)density
  • posterior Beta(8, 4)
The posterior that the chain should reproduce. Its peak is at 0.7 with height about 2.94.

Tradeoffs and failure modes

Random-walk Metropolis is simple and general, but it is not always the right tool. The table lists the common problems.

SituationWhat goes wrongBetter choice
Several well-separated peaksThe chain gets stuck near one peak and the weights are wrongParallel tempering, sequential Monte Carlo, or several chains started from spread-out points
Step size too smallThe chain moves slowly and autocorrelation is highIncrease the step until the acceptance rate is moderate (a common rule of thumb is around 20 to 50 percent in low dimensions)
Step size too largeMost proposals are rejected and the chain sits stillDecrease the step
High dimension, random-walk proposalAcceptance collapses and exploration is slow[[langevin-dynamics
Smooth target with computable gradientsRandom walk wastes most of its stepsHamiltonian Monte Carlo, or the No-U-Turn Sampler that Stan uses by default
Need fast approximate answers rather than exact onesMCMC can take a long time to converge[[variational-lower-bound
Simple model where direct or weighted sampling worksMCMC overhead and diagnostics add cost for no gainDirect sampling, or Importance Sampling

Two cautions apply everywhere. First, the theory says the chain converges eventually, but never tells you when it has. Use trace plots, run several chains from different starts, and compare them with a statistic such as R^\hat{R}. Second, discard an initial burn-in period before averaging. Burn-in removes the influence of the arbitrary starting point, so the walk has time to forget where it began.

History

The Monte Carlo idea came out of work at Los Alamos in the 1940s, where Stanislaw Ulam and John von Neumann used random sampling to study neutron diffusion. In the early 1950s, Nicholas Metropolis, Arianna and Marshall Rosenbluth, and Augusta and Edward Teller used a random walk over configurations of a model gas and published the acceptance rule that bears Metropolis's name. Their goal was to compute the equation of state of a system whose configurations were far too many to enumerate.

In 1970, W. K. Hastings generalised the rule to asymmetric proposal distributions, which produced the Metropolis-Hastings form used today. Statisticians largely ignored these methods for decades because the computation was too heavy. In 1984, Stuart and Donald Geman applied a closely related Gibbs sampler to image restoration. In 1990, Alan Gelfand and Adrian Smith showed that such samplers could compute posterior summaries for ordinary Bayesian models. Combined with faster computers, that result started the wide adoption of MCMC in statistics. It caught on because it let people fit models that had no closed-form answer.

Check yourself

QuestionState the detailed balance condition and explain in one sentence why it guarantees that π\pi is stationary.Show answer

Detailed balance says π(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': the probability flow from xx to x′x' equals the flow back. Integrating both sides over xx gives ∫π(x)K(x→x′) dx=π(x′)∫K(x′→x) dx=π(x′)\int \pi(x)K(x \to x')\,dx = \pi(x')\int K(x' \to x)\,dx = \pi(x'), which is the definition of a stationary distribution.

QuestionA symmetric proposal moves between two states A and B. The unnormalised weights are w(A)=2w(A) = 2 and w(B)=5w(B) = 5. If the chain is at B and the proposal picks A with probability 1/21/2, what is the probability that the chain moves to A?Show answer

The acceptance probability is min⁡(1,w(A)/w(B))=min⁡(1,2/5)=2/5\min(1, w(A)/w(B)) = \min(1, 2/5) = 2/5. The overall move probability is (1/2)(2/5)=1/5(1/2)(2/5) = 1/5, or 0.2. Note that the constant in ww never mattered, only the ratio 2/52/5.

QuestionWhy does Metropolis-Hastings not need the normalising constant of the target, and why must the first part of the chain be discarded?Show answer

The acceptance ratio π(x′)/π(x)\pi(x')/\pi(x) is unchanged if both values are multiplied by the same constant, so the unknown ZZ cancels. The chain starts at an arbitrary point, and its distribution only converges to the target after it has run long enough to forget that start. Samples taken before that point over-represent the starting region, so they are discarded as burn-in.

QuestionYou run MCMC on a posterior with two modes. The trace plot of one chain stays near one mode for thousands of iterations, and two chains started at different points report different posterior means. What is happening, and what would you do?Show answer

The chains are not mixing: the walk cannot cross the low-probability valley between the modes, so each chain has only explored one region and the relative weight of the modes is wrong. Divergent estimates across chains are a diagnostic signal, not a fluke. Remedies include a larger or better-designed proposal, parallel tempering to help the chain cross between modes, reparameterising the model to reduce the separation, and checking R^\hat{R} and effective sample size before trusting any mean.

Sources