Skip to content

Metropolis–Hastings: a chain that settles on the posterior

Propose a move, accept it by a density ratio, repeat. Metropolis–Hastings needs the posterior only up to a constant. Learn the accept rule, why rejections count, and why a high acceptance rate can hide a chain that never moved.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Write the Metropolis–Hastings acceptance probability, including the proposal ratio
  • Explain why a rejected proposal repeats the current state in the chain
  • Tell acceptance (a tuning number) from mixing (exploration)
  • Run a random-walk Metropolis chain in Python and R

Read first

01

A chain instead of independent draws

Read

Rejection and importance sampling draw independently from a proposal. In more than a few dimensions no single proposal fits the posterior well. Markov chain Monte Carlo (MCMC) takes another route: a chain of states, each one a small random change of the last, built so that in the long run it visits each region in proportion to its posterior probability.

The price is that neighboring draws are correlated, and the chain has to run long enough to forget where it started. The payoff is that each step only needs local information, so it scales to thousands of parameters.

Reference · INF009 · Runs as a notebookMetropolis–Hastings (MH)Constructs a Markov chain with a chosen target stationary distribution by correcting proposal moves with an acceptance ratio.
02

The accept rule

Read

Metropolis–HastingsMetropolis–HastingsMCMC that proposes a move and accepts it with a probability set by the target's density ratio; a rejection repeats the current state. (MH) proposes yy from q(y∣x)q(y\mid x) and moves there with probability

α(x,y)=min⁡(1, p~(y) q(x∣y)p~(x) q(y∣x)).\alpha(x,y)=\min\left(1,\ \frac{\tilde p(y)\,q(x\mid y)}{\tilde p(x)\,q(y\mid x)}\right).

Otherwise it stays at xx, and xx is recorded again. The unknown normalizing constant cancels in the ratio, which is why MH works on unnormalized posteriors. For a symmetric proposal, like a normal step centered at xx, the qq terms cancel too; for an asymmetric one, leaving them out samples the wrong distribution.

Compare in log space (log of a uniform against the log ratio) so extreme densities don't overflow.

03

A short chain, two languages

Read

The reference's program runs 6,000 random-walk steps on a standard normal target, starting far out at 3, and drops the first 1,000 as warmup:

Python
import numpy as np
rng = np.random.default_rng(7); x = 3.0; draws = []; accepted = 0
for _ in range(6000):
    y = x + rng.normal(0, 0.8)                    # symmetric proposal
    loga = min(0.0, -0.5 * y * y + 0.5 * x * x)   # log acceptance ratio
    if np.log(rng.uniform()) < loga:
        x = y; accepted += 1
    draws.append(x)                               # a rejection repeats x
d = np.array(draws[1000:])
print("mean", d.mean(), "variance", d.var(), "acceptance", accepted / 6000)
R
set.seed(7); x <- 3; draws <- numeric(6000); accepted <- 0
for (i in seq_along(draws)) {
  y <- x + rnorm(1, 0, 0.8)                       # symmetric proposal
  loga <- min(0, -0.5 * y * y + 0.5 * x * x)      # log acceptance ratio
  if (log(runif(1)) < loga) { x <- y; accepted <- accepted + 1 }
  draws[i] <- x                                   # a rejection repeats x
}
d <- draws[1001:6000]
print(c(mean = mean(d), variance = mean((d - mean(d))^2), acceptance = accepted / 6000))

In CodeSplash's run of the Python version the mean is 0.045, the variance 0.972 (the target's are 0 and 1), and 76% of proposals were accepted. R's random stream differs, so its numbers differ a little: the same seed integer doesn't mean the same draws.

04

Rejections are part of the answer

Read

A common bug keeps only the accepted proposals. That list over-represents states the chain was leaving quickly and under-represents states where it stayed: in a region of high density, proposals are often rejected, and each rejection is the chain correctly "voting" for the current state again. Averages over accepted moves alone are biased.

The other classic bugs: forgetting the proposal ratio for an asymmetric qq (for example a log-normal step on a positive parameter), and comparing densities on the wrong scale after transforming a parameter without its Jacobian.

05

Predict: a tiny step

Predict

Predict first

You shrink the proposal's step size a hundredfold. The acceptance rate rises above 99%. What happened to the chain?

It mixes better: almost every proposal is acceptedIt barely explores: each accepted step moves almost nowhere
Reveal

It barely explores. Tiny steps are almost always accepted because the density hardly changes, so the chain creeps. Four such chains started apart stay apart; the reference's computation workflow sees exactly that, with R-hat far above 1 despite near-perfect acceptance.

06

Acceptance is not mixing

Read

Acceptance is a tuning number. Big steps are often rejected and the chain sits still; tiny steps are accepted and the chain crawls. Both mix badly. MixingMixing of a Markov chainHow fast a chain's draws forget where they started and cover the whole target. Poor mixing means highly correlated draws and a low ESS. means forgetting the start and covering the target, and it is judged with several chains started apart, the rank-normalized R-hatR-hat (rank-normalized)Compares the spread between chains with the spread within them; 1.01 or less means the chains agree., the effective sample sizeEffective sample size (MCMC)How many independent draws the correlated draws are worth. Bulk ESS covers the center; tail ESS covers intervals. and trace plots, never with the acceptance rate alone.

Thinning (keeping every tenth draw) doesn't fix poor mixing either; it only throws information away. Better proposals do: steps scaled to the posterior's shape, or gradients (Hamiltonian Monte Carlo, two lessons on).

Run four random-walk chains here: shrink the step until acceptance is near 100% and watch R-hat and ESS get worse, not better.

EExplorable · MCMC samplers: acceptance is not mixing

Do four chains of a sampler agree about the target, and does a high acceptance rate mean they will?

Target

The distribution the chains try to sample.

0.90

How strongly the Gaussian's two coordinates move together.

Sampler

Gibbs needs each coordinate's conditional distribution; only the Gaussian has them here.

0.50

Random-walk proposal scale, or HMC's leapfrog step.

10

HMC only: steps of the simulated trajectory per proposal.

1000

Draws in each of the four chains.

  • Chain 1, starts at (-3, -3)
  • Chain 2, starts at (3, 3)
  • Chain 3, starts at (-3, 3)
  • Chain 4, starts at (3, -3)
Acceptance rate
0.533
R-hat of x₁
1.029
Bulk ESS of x₁
72
ESS per draw
0.018
  • Puzzle: Find a sampler and step size with R-hat below 1.01 and a bulk ESS above 400.
  • Puzzle: Push the acceptance rate above 90% while R-hat stays above 1.05.
Random-walk Metropolis on the correlated Gaussian: 53% of proposals accepted, R-hat 1.029, bulk ESS 72 of 4000 draws. The four chains still disagree, so these draws don't describe the target yet. The acceptance rate alone says nothing about mixing.

Random-walk Metropolis on the correlated Gaussian: 53% of proposals accepted, R-hat 1.029, bulk ESS 72 of 4000 draws. The four chains still disagree, so these draws don't describe the target yet. The acceptance rate alone says nothing about mixing.

07

A sticky chain, by hand

Explore

This two-state chain is not MH, but it shows the same failure. Set both "stay" probabilities to 0.99 and run a short chain: the long-run share is fine, yet the simulated share wanders far from it because each state persists for so long.

AExplorable · A Markov chain playground

When tomorrow depends only on today, where does a process settle in the long run?

In the long run, what share of time does the chain spend in A?

0.50
How sure?
0.80
0.60
500
long-run 0.67

The strip shows the first steps: state A in one color, B in the other. Long runs of one color mean a sticky chain.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

08

Where it stands in CodeSplash

Read
09

Check your understanding

Checkpoint

Check yourself

Why can Metropolis–Hastings sample a posterior whose normalizing constant is unknown?

Show the answer

Answer: b

Only p~(y)/p~(x)\tilde p(y)/\tilde p(x) enters the rule. That is the main reason MCMC is the workhorse for posteriors.

Check yourself

A student's MH code appends a draw only when the proposal is accepted. What's wrong?

Show the answer

Answer: b

Repeated states are how MH spends more time in high-density regions. Without them the draws describe the jump chain, not the target.

Check yourself

You propose a positive scale parameter with a log-normal step centered on the current value. What must the acceptance ratio include?

Show the answer

Answer: b

The terms cancel only for symmetric proposals. An asymmetric step without its ratio samples the wrong distribution.

Check yourself

Four MH chains each accept 99% of proposals, but their trace plots sit in four separate bands. What do you report?

Show the answer

Answer: b

Very high acceptance usually means tiny steps. Separate bands from separated starts say the chains haven't forgotten where they began. Rescale the proposal (or switch samplers) and rerun.

10

Recap

Recap
  • MH accepts a proposal with probability min⁡(1,density ratio×proposal ratio)\min(1,\text{density ratio}\times\text{proposal ratio}); the constant cancels.
  • A rejection repeats the current state; never drop repeats.
  • Acceptance tunes the step size; mixing is judged with chains, R-hat, ESS and traces.
  • Same seed, different language, different draws.

Concepts in this lesson