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.
| Component | Role | Practical note |
|---|---|---|
| Target density | Distribution to be sampled | Known only up to a constant |
| Proposal mechanism | Suggests the next candidate state | Shapes efficiency of exploration |
| Acceptance rule | Decides whether to move | Preserves the correct distribution |
| Warm-up phase | Lets the chain forget its start | Often also tunes step sizes |
| Retained draws | Samples used for estimates | Correlated, not independent |
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.
| Algorithm | Needs gradients | Strength | Weakness |
|---|---|---|---|
| Random-walk Metropolis | No | Simple and general | Very slow in high dimensions |
| Gibbs sampling | No | No tuning with conjugate models | Stalls when variables are correlated |
| Hamiltonian Monte Carlo | Yes | Efficient in many dimensions | Requires continuous parameters |
| No-U-Turn Sampler | Yes | Self-tuning trajectory length | Costly per iteration |
| Slice sampling | No | Adapts step size automatically | Can be slow for many variables |
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.
| Diagnostic | What it detects | Common threshold |
|---|---|---|
| R-hat statistic | Disagreement between chains | Below 1.01 |
| Effective sample size | Information content after autocorrelation | At least 400 for stable summaries |
| Trace plots | Trends, sticking or poor mixing | Chains overlap like noise |
| Divergent transitions | HMC failing in curved regions | Zero is the goal |
| Autocorrelation | Dependence between successive draws | Decays quickly with lag |
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.
| Aspect | MCMC | Variational inference |
|---|---|---|
| Accuracy | Exact in the limit | Biased by the chosen family |
| Speed | Slow for large data sets | Fast and scalable |
| Uncertainty estimates | Generally reliable | Often too narrow |
| Scaling to big data | Difficult without subsampling | Works with minibatches |
| Typical use | Scientific and statistical models | Deep generative models |
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.