The Metropolis-Hastings algorithm is a Markov chain Monte Carlo method that draws samples from a probability distribution known only up to a normalizing constant, by repeatedly proposing a new state and accepting or rejecting it with a carefully chosen probability. Among probabilistic models, it is the general-purpose workhorse for sampling posterior distributions in Bayesian inference when direct sampling or exact integration is impossible.
The method extends the original Metropolis algorithm of 1953, which assumed symmetric proposals, to arbitrary proposal distributions through a correction introduced by W. K. Hastings in 1970. Gibbs sampling, Hamiltonian Monte Carlo and many modern samplers are special cases or refinements of the same accept-reject idea.
How the Metropolis-Hastings algorithm works
The algorithm builds a Markov chain whose stationary distribution is the target distribution p(x). It needs only an unnormalized density, which is exactly what Bayesian inference provides: the product of likelihood and prior, without the intractable marginal likelihood.
- Start from an initial state x and choose a proposal distribution q(x’ | x).
- Draw a candidate x’ from q(x’ | x).
- Compute the acceptance ratio r = [p(x’) q(x | x’)] / [p(x) q(x’ | x)].
- Accept x’ with probability min(1, r); otherwise keep x as the next sample.
- Repeat for many iterations and record the sequence of states.
Because the unknown normalizing constant appears in both numerator and denominator, it cancels in the ratio. The proposal correction term q(x | x’) / q(x’ | x) is the Hastings correction; it vanishes when the proposal is symmetric, which recovers the plain Metropolis algorithm.
Correctness rests on detailed balance: the probability flow from x to x’ equals the flow back. Combined with irreducibility and aperiodicity, this guarantees that the chain converges to the target distribution regardless of the starting point, although the speed of convergence is not guaranteed.
A rejected proposal is not wasted information: the chain records the current state again, and these repeated values are essential for correct weighting. Discarding rejections, or keeping only distinct states, biases every estimate computed from the chain. Successive samples are also correlated by construction, so the output is a dependent sequence rather than a set of independent draws, and posterior means, variances and quantiles are computed as averages over the retained iterations.
Proposal distributions and their variants
The choice of proposal distribution determines how efficiently the chain explores the target. A proposal that is too narrow accepts almost everything but moves slowly; a proposal that is too wide is rejected most of the time.
| Variant | Proposal | Typical use |
|---|---|---|
| Random-walk Metropolis | Gaussian centered on the current state | General continuous posteriors |
| Independence sampler | Fixed distribution ignoring the current state | When a good approximation of the target exists |
| Gibbs sampling | Exact conditional of one variable | Models with tractable conditionals |
| MALA | Gradient-informed Langevin step | Smooth, differentiable targets |
| Adaptive Metropolis | Covariance learned from past samples | Correlated parameters |
Gibbs sampling is a Metropolis-Hastings scheme whose acceptance probability is always one, because each proposal is drawn from an exact full conditional. Adaptive schemes must stop or diminish adaptation over time, otherwise the chain can lose its convergence guarantee.
Tuning the acceptance rate and step size
For random-walk proposals, the step size controls the trade-off between acceptance and movement. Theoretical results for high-dimensional Gaussian targets suggest an optimal acceptance rate of about 0.234, while one-dimensional problems favor rates near 0.44.
The table below summarizes the diagnostic signals that indicate whether a step size needs adjustment.
| Observed symptom | Likely cause | Adjustment |
|---|---|---|
| Acceptance above 0.8 | Steps too small | Increase proposal scale |
| Acceptance below 0.1 | Steps too large | Decrease proposal scale |
| Strong autocorrelation | Poor mixing or correlated parameters | Reparameterize or adapt covariance |
| Chains disagree | Not yet converged or multimodal target | Run longer, use multiple starts |
| Trace stuck in one region | Separated modes | Use tempering or a different sampler |
Practitioners discard an initial burn-in or warm-up period and judge convergence with several independent chains. Standard diagnostics are the R-hat statistic, which should be close to 1.00, and the effective sample size, which measures how many independent draws the correlated chain is worth.
Comparison with other inference methods
Metropolis-Hastings is simple and universal but often slower than specialized samplers or approximate methods. The right choice depends on dimensionality, differentiability and the accuracy required.
| Method | Strength | Limitation |
|---|---|---|
| Metropolis-Hastings | Needs only an unnormalized density | Slow mixing in high dimensions |
| Gibbs sampling | No tuning, no rejections | Requires tractable conditionals |
| Hamiltonian Monte Carlo | Efficient in many dimensions | Needs gradients, continuous variables |
| Importance sampling | Independent weighted samples | Weights degenerate in high dimensions |
| Variational inference | Fast optimization at scale | Biased approximation of the posterior |
Random-walk proposals scale poorly: the number of iterations needed to explore a target grows roughly in proportion to the dimension, whereas Hamiltonian Monte Carlo scales more favorably. This is why probabilistic programming systems default to gradient-based samplers such as the No-U-Turn Sampler for continuous models.
Practical use, limitations and common mistakes
Metropolis-Hastings remains the method of choice for discrete or non-differentiable targets, for models with expensive or black-box likelihoods, and as a building block inside larger samplers such as Metropolis-within-Gibbs. Its weaknesses are well known to practitioners.
- Multimodal targets: the chain can stay in one mode and miss others entirely.
- Strong correlations: isotropic proposals zigzag slowly along narrow ridges.
- Too few iterations: a chain that looks stable may simply be stuck.
- Working outside log space: computing densities directly causes numerical underflow.
- Forgetting the Hastings correction with asymmetric proposals, which biases results.
Careful implementations compute the acceptance test as log u < log r with u drawn uniformly, transform constrained parameters to an unconstrained scale, and always report convergence diagnostics alongside the estimates.
Thinning, which keeps only every k-th sample, reduces storage but not error for a fixed amount of computation, so it is justified mainly by memory limits. When a likelihood is expensive, the cost per iteration dominates, and a smarter proposal that needs fewer iterations usually pays off more than faster code.
In simple terms
Imagine exploring a dark hilly landscape where you want to spend more time on higher ground. You cannot see the whole map. You can only measure the height where you stand and at one spot you consider stepping to.
If the new spot is higher, you go there. If it is lower, you sometimes still go, more often when it is only a little lower. Over many steps, the places you visit form a faithful picture of the landscape. The Metropolis-Hastings algorithm does exactly this with probabilities. It explores a distribution nobody can calculate directly.
A practical example
An epidemiology team fits a Bayesian transmission model to weekly case counts in order to estimate the reproduction number and the reporting rate. The likelihood comes from a simulation-based model with no usable gradients, so the team chooses random-walk Metropolis-Hastings on the log scale of both parameters.
The first trial run accepts only 4% of proposals, so the analysts shrink the proposal scale and later adapt its covariance during warm-up. The final setup runs four chains of 20,000 iterations, discards the first 5,000 of each and reaches an acceptance rate near 0.3.
All R-hat values fall below 1.01 and the effective sample size exceeds 1,500 for each parameter. The team reports a credible interval for the reproduction number to public health officials, together with the diagnostics that show the sampler converged.