Markov chain Monte Carlo

Also known as: MCMC

On this page 7

Markov chain Monte Carlo (MCMC) is a family of algorithms that draw samples from a probability distribution by constructing a Markov chain whose stationary distribution equals the target distribution. In probabilistic models, MCMC is the standard tool for approximating a posterior distribution in Bayesian inference when that distribution cannot be computed analytically.

The key insight is that MCMC needs the target density only up to a normalizing constant. Because the marginal likelihood in Bayes’ theorem is usually an intractable integral, this property makes MCMC applicable to a vast range of models, from hierarchical regression to latent variable models and Bayesian neural networks.

How MCMC constructs samples

MCMC generates a sequence of states in which each new state depends only on the current state, which is the defining Markov property. The transition rule is designed so that, after enough steps, the states are distributed according to the target, regardless of the starting point. This guarantee rests on two conditions: the chain must be ergodic, meaning it can reach every region of the space, and it must leave the target invariant, which is usually ensured through detailed balance.

Once the chain has converged, the collected states serve as a Monte Carlo estimate of any quantity of interest. Posterior means, variances, credible intervals and predictive probabilities are computed simply by averaging over the samples. The early portion of the chain, called burn-in or warm-up, is discarded because it still reflects the arbitrary starting point.

The following table names the core components of every MCMC run.

ComponentRolePractical note
Target densityDistribution to be sampledKnown only up to a constant
Proposal mechanismSuggests the next candidate stateShapes efficiency of exploration
Acceptance ruleDecides whether to movePreserves the correct distribution
Warm-up phaseLets the chain forget its startOften also tunes step sizes
Retained drawsSamples used for estimatesCorrelated, not independent
Core components of an MCMC run

Main MCMC algorithms

MCMC algorithms differ mainly in how they propose new states, and that choice determines how quickly they explore the distribution. The Metropolis-Hastings algorithm proposes a random move and accepts it with a probability based on the ratio of target densities. Gibbs sampling updates one variable at a time from its full conditional distribution, which is efficient when those conditionals have closed forms, as with conjugate priors.

Hamiltonian Monte Carlo (HMC) uses the gradient of the log density to simulate physical motion, allowing long, well-directed moves through high-dimensional spaces. The No-U-Turn Sampler (NUTS) automates the choice of trajectory length in HMC and is the default engine in modern probabilistic programming tools such as Stan and PyMC.

AlgorithmNeeds gradientsStrengthWeakness
Random-walk MetropolisNoSimple and generalVery slow in high dimensions
Gibbs samplingNoNo tuning with conjugate modelsStalls when variables are correlated
Hamiltonian Monte CarloYesEfficient in many dimensionsRequires continuous parameters
No-U-Turn SamplerYesSelf-tuning trajectory lengthCostly per iteration
Slice samplingNoAdapts step size automaticallyCan be slow for many variables
Comparison of common MCMC algorithms

A rough rule from practice is that random-walk methods need a number of steps that grows roughly linearly with dimension to stay efficient, while gradient-based methods scale considerably better. This difference explains why HMC variants dominate in models with hundreds or thousands of parameters.

Diagnosing convergence and sample quality

MCMC output is only trustworthy after convergence has been checked, because a chain that has not mixed produces confident but wrong estimates. No diagnostic can prove convergence; diagnostics can only reveal evidence of failure, so practitioners combine several of them.

Running four or more independent chains from dispersed starting points is standard practice, since disagreement between chains is the clearest warning sign. The table below lists the most widely used diagnostics and their usual thresholds.

DiagnosticWhat it detectsCommon threshold
R-hat statisticDisagreement between chainsBelow 1.01
Effective sample sizeInformation content after autocorrelationAt least 400 for stable summaries
Trace plotsTrends, sticking or poor mixingChains overlap like noise
Divergent transitionsHMC failing in curved regionsZero is the goal
AutocorrelationDependence between successive drawsDecays quickly with lag
Standard MCMC diagnostics

The effective sample size matters more than the raw number of draws. Ten thousand highly correlated samples may carry the information of only a few hundred independent ones, so reporting raw iteration counts alone can overstate precision.

MCMC compared with variational inference

MCMC and variational inference are the two main families of approximate Bayesian inference, and they trade accuracy for speed in opposite directions. MCMC is asymptotically exact: with enough iterations it recovers the true posterior. Variational inference instead fits a simpler distribution by maximizing the evidence lower bound, which is fast but systematically biased, typically underestimating posterior variance.

AspectMCMCVariational inference
AccuracyExact in the limitBiased by the chosen family
SpeedSlow for large data setsFast and scalable
Uncertainty estimatesGenerally reliableOften too narrow
Scaling to big dataDifficult without subsamplingWorks with minibatches
Typical useScientific and statistical modelsDeep generative models
MCMC versus variational inference

In practice, the choice follows the question. When well-calibrated uncertainty matters, as in clinical studies or risk models, MCMC is preferred. When the model must process millions of examples, variational methods or the Laplace approximation are usually the only feasible options.

Limitations and common pitfalls

MCMC is powerful but computationally expensive and easy to misuse. Most failures arise from the geometry of the posterior rather than from software errors.

  • Multimodal posteriors: a chain may remain trapped in one mode and never reveal others.
  • Funnel geometries: hierarchical models often need a non-centered parameterization to avoid divergences.
  • Discrete parameters: HMC cannot handle them directly, so they must be marginalized out or sampled separately.
  • Too short warm-up: poorly tuned step sizes lead to slow mixing and biased summaries.
  • Ignoring diagnostics: a single chain with no checks offers no protection against silent failure.

The idea in brief

Imagine exploring a dark landscape of hills. You cannot see the whole map. You can only feel how high the ground is where you stand. MCMC is a rule for wandering so that you spend more time on high ground and less in valleys.

After a long walk, your footprints form a map of the terrain. In statistics, the hills are the most plausible explanations of the data. Counting the footprints tells you how likely each explanation is.

A practical scenario

A public health team estimates infection rates across 120 counties, many of which report only a handful of cases. A simple per-county average would be unstable, so the analysts build a hierarchical Bayesian model in which county rates share information through a regional distribution.

They fit the model with the No-U-Turn Sampler, running four chains of 2,000 iterations each, with the first 1,000 used for warm-up. Initial runs show dozens of divergent transitions, so the team switches to a non-centered parameterization. The second run reports R-hat values below 1.01 and effective sample sizes above 1,000 for all key parameters.

The resulting posterior gives each county a rate with a credible interval. Small counties receive estimates pulled toward the regional mean, which prevents false alarms. Health officers use these intervals to allocate testing resources where uncertainty is genuinely high.