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.
- two-peak target
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 be the target distribution over a space of values . We usually want an expectation
for some function , such as a posterior mean when . The Monte Carlo method estimates this by averaging over samples from ; the difficulty is getting those samples. Often we can only evaluate , which is proportional to , so that with unknown. In Bayesian inference (Bayes' rule) is likelihood times prior, and is the evidence. MCMC needs only , because every acceptance decision depends on the ratio and cancels.
Markov chains with a chosen stationary distribution
A Markov chain moves from to according to a transition kernel , which for each is a density over that integrates to 1. If has distribution , then the next distribution is
A distribution is stationary for if running one step leaves it unchanged, that is for every .
The easiest way to guarantee this is detailed balance:
Detailed balance implies stationarity. Integrate both sides over . The right side becomes , 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 converges to from any starting point, and time averages converge:
Because successive samples are correlated, the variance of this estimate is roughly , where is the integrated autocorrelation time. The effective sample size is . A chain with large needs many more steps for the same accuracy, which is why diagnosing autocorrelation matters.
Metropolis-Hastings
Choose a proposal distribution , which is any distribution we can sample from. Given the current state , draw and accept it with probability
If the proposal is rejected, stay at . For the kernel is .
Detailed balance holds. Write . Then
The right side is symmetric under swapping and , so .
The special case of random-walk Metropolis uses a symmetric proposal, such as a normal centred on the current state with standard deviation . Then cancels and the acceptance rule becomes . The step size is the one knob you tune. If is too small, the walk moves slowly and its samples are highly correlated. If is too large, most proposals land in low-probability places and get rejected, so the walk again sits still.
Worked examples
Take three states with unnormalised target weights , , , so . From the current state, pick one of the other two states with probability each. The proposal is symmetric, so .
- From state 1 (weight 1): propose 2, accept with , so . Propose 3, accept with 1, so . Stay: .
- From state 2 (weight 2): propose 1, accept with , so . Propose 3, accept with 1, so . Stay: .
- From state 3 (weight 3): propose 1, accept with , so . Propose 2, accept with , so . Stay: .
- Check detailed balance on the pair (1, 2): and . They match.
- Start in state 1. After one step the distribution is . After two steps, , and .
- After three steps, , and . The rest is .
- The target is . After two steps, state 2 was too low. After three steps the error is about .
Interpretation: the chain never computed . It followed local rules that only compare two weights, and its distribution converged to the weights anyway.
You flip a coin 10 times and get 7 heads. With a uniform prior on the bias , the posterior is proportional to . That is a Beta(8, 4) distribution, with normalised density , but suppose we only have the unnormalised form . We run random-walk Metropolis with step , starting at , where .
- Propose . . The ratio to the current value is , which is at least 1, so accept. Now .
- From 0.7, propose . . The ratio is . Draw a uniform number . Since , reject. The walk stays at , and that repeat is recorded.
- From 0.7, propose . The ratio is . Draw . Since , accept. Now .
Interpretation: the normalising constant never appeared. Each decision compared two values of . 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 here were chosen for illustration. A real run draws them at random.
- posterior Beta(8, 4)
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.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Several well-separated peaks | The chain gets stuck near one peak and the weights are wrong | Parallel tempering, sequential Monte Carlo, or several chains started from spread-out points |
| Step size too small | The chain moves slowly and autocorrelation is high | Increase 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 large | Most proposals are rejected and the chain sits still | Decrease the step |
| High dimension, random-walk proposal | Acceptance collapses and exploration is slow | [[langevin-dynamics |
| Smooth target with computable gradients | Random walk wastes most of its steps | Hamiltonian Monte Carlo, or the No-U-Turn Sampler that Stan uses by default |
| Need fast approximate answers rather than exact ones | MCMC can take a long time to converge | [[variational-lower-bound |
| Simple model where direct or weighted sampling works | MCMC overhead and diagnostics add cost for no gain | Direct 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 . 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 is stationary.Show answer
Detailed balance says for all and : the probability flow from to equals the flow back. Integrating both sides over gives , which is the definition of a stationary distribution.
QuestionA symmetric proposal moves between two states A and B. The unnormalised weights are and . If the chain is at B and the proposal picks A with probability , what is the probability that the chain moves to A?Show answer
The acceptance probability is . The overall move probability is , or 0.2. Note that the constant in never mattered, only the ratio .
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 is unchanged if both values are multiplied by the same constant, so the unknown 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 and effective sample size before trusting any mean.
Sources
- Markov chain Monte Carlo (Wikipedia): https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo
- Metropolis-Hastings algorithm (Wikipedia): https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm
- Bishop, Pattern Recognition and Machine Learning, §11.2: https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/
- Metropolis, Rosenbluth, Rosenbluth, Teller, Teller, Equation of State Calculations by Fast Computing Machines (1953): https://doi.org/10.1063/1.1699114