45.03.05 · mathematical-statistics / 03-bayesian-inference

Markov Chain Monte Carlo: Metropolis-Hastings and Gibbs Sampling

shipped3 tiersLean: none

Anchor (Master): Robert-Casella 2004 Monte Carlo Statistical Methods 2e (Springer) Ch. 6-10 (Metropolis-Hastings theory, Gibbs sampling, convergence control); Meyn-Tweedie 2009 Markov Chains and Stochastic Stability 2e (Cambridge) Ch. 13, 17 (Harris recurrence, the ergodic theorem for general state spaces); Tierney 1994 Annals of Statistics 22, 1701-1762 (MCMC on general state spaces)

Intuition Beginner

Bayesian inference hands you a posterior distribution — a description of how plausible each possible value of an unknown quantity is, given the data. The trouble is that you can almost never write that distribution down cleanly. Bayes' rule gives you the shape of the posterior up to a missing scaling number, and computing that number means doing an integral over every possible parameter value at once. In one or two dimensions you might manage it; in the hundreds of dimensions that real models have, the integral is hopeless. So you are stuck holding a curve whose height you know only up to an unknown overall stretch.

Markov chain Monte Carlo is the escape. Instead of computing the distribution, you take a long random walk through the space of parameter values, arranged so that the walker lingers in regions where the posterior is high and hurries through regions where it is low. After enough steps, the places the walker has visited are spread out in exactly the same proportions as the posterior itself. You never needed the missing scaling number, because the walk only ever compares two heights — it asks "is this new spot more or less plausible than where I am now?" — and the unknown stretch cancels in the comparison.

Picture a politician touring islands of different populations, wanting to spend time on each island in proportion to how many people live there, but without ever being told the actual head counts. Each day they consider hopping to a neighbouring island. If it is more populous, they go. If it is less populous, they flip a biased coin and go only sometimes, with a chance set by the ratio of the two populations. Follow this rule for years and the fraction of nights spent on each island matches its share of the total population, even though no total was ever counted. That ratio-only rule is the heart of every method here.

The one-sentence takeaway: MCMC turns an impossible integral into a long guided random walk, because the long-run share of time the walk spends in each region equals the posterior probability of that region, and only ratios of probabilities are ever needed.

Visual Beginner

The picture below shows a walker exploring a two-humped target and the histogram it builds up over time.

The landscape is the target distribution, drawn at an unknown overall height. The walker spends most of its visits under the tall hump, fewer under the short hump, and rarely crosses the valley — so the histogram of where it has been (bottom) reproduces the landscape's shape (top). The bracket marks the early steps, called burn-in, that are thrown away because the walk had not yet reached the high-probability region.

Worked example Beginner

A coin has unknown success probability . You see heads in flips. With a flat prior, the posterior for is proportional to on the interval from to . We sample from it with a small Metropolis walk using a fixed random sequence, so you can follow every step.

Step 1. Start at . The target height there is .

Step 2. Propose a nearby value by adding a small jump; suppose the proposal is . The target height there is .

Step 3. Form the ratio of new height to current height: . The proposal is more plausible than where we are, so the ratio is above . The rule says: when the ratio is at least , always accept. Move to .

Step 4. From , propose . Its height is . The ratio is , which is below .

Step 5. When the ratio is below , accept only with probability equal to the ratio. Draw a uniform random number; say it is . Since , accept and move to . Had the random number been , we would have stayed at and recorded again.

What this tells us: the walk drifted from toward the region around , which is where peaks (its maximum is at ). Recording many such steps and making a histogram reproduces the posterior, and at no point did we compute the constant that makes integrate to — only ratios were used.

Check your understanding Beginner

Formal definition Intermediate+

The target is a probability distribution on a state space (for Bayesian work, is the posterior on a parameter space, known only up to the marginal likelihood ). Write for the (possibly unnormalised) target density against a reference measure. The aim is to compute expectations for test functions , using only evaluations of up to its unknown constant.

Definition (MCMC sampler). A Markov chain Monte Carlo sampler for is a Markov transition kernel on , in the sense of 37.05.01, whose stationary distribution is — that is, , meaning for every measurable . The chain run from any start is used to form the ergodic average , the MCMC estimator of .

Definition (reversibility / detailed balance). A kernel is reversible with respect to , or satisfies detailed balance, if

as measures on . Detailed balance implies -invariance: integrating over the first coordinate gives . It is the standard design tool because it is a pointwise symmetry one can enforce locally, established for Markov chains in 37.05.07.

Definition (Metropolis-Hastings kernel). Fix a proposal kernel with density . Given , draw a proposal and accept it with probability

setting on acceptance and on rejection. The resulting kernel is

a mixture of the accepted-move density and a point mass at of total rejection mass . Only the ratio enters , so the normalising constant never appears.

Two special cases. Random-walk Metropolis takes a symmetric proposal (for example , symmetric), so — the original Metropolis form. The independence sampler takes independent of , giving , which is efficient only when approximates well.

Definition (Gibbs sampler). Suppose and the full conditionals — the conditional target of component given all others — are available to sample. The Gibbs sampler updates components in turn, replacing by a draw from . The deterministic-scan cycle sweeps ; the random-scan version picks uniformly each step. Each component update is a Metropolis-Hastings step with proposal equal to the full conditional, whose acceptance probability is identically .

Counterexamples to common slips Intermediate+

  • Detailed balance is sufficient but not necessary for invariance. A directed cycle on three states with equal stationary weights is -invariant yet not reversible. MCMC uses detailed balance because it is constructive, not because invariance demands it.
  • A reversible chain need not be ergodic. If the proposal cannot reach part of the support — a random walk with steps too small to cross a deep valley in finite practical time, or zero proposal density on a region — the chain is -invariant but explores only one mode. Invariance is about the target; convergence additionally needs -irreducibility and aperiodicity.
  • The proposal ratio is not optional for asymmetric proposals. Dropping it (using the Metropolis form with an asymmetric ) produces a chain whose stationary law is not . The Hastings correction is exactly what restores detailed balance.
  • Gibbs updates change one block and condition on the current value of the rest. Conditioning on stale values from before the sweep began, rather than the most recently updated components, breaks invariance of the cycle scan.

Key theorem with proof Intermediate+

Theorem (Metropolis-Hastings invariance). Let be a target with density and a proposal kernel with . The Metropolis-Hastings kernel with acceptance probability is reversible with respect to , hence . The constant in does not affect .

Proof. It suffices to verify detailed balance for the off-diagonal (move) part of the kernel, since the rejection part is supported on the diagonal , where detailed balance holds automatically (both sides equal when ). For the move density of is against , and detailed balance requires

Fix with , and set , so . By symmetry of the ratio, . Consider the two cases.

If : the left side of is . The right side is since . Both sides equal .

If : the left side is . The right side is . Both sides equal .

So holds for all , and the kernel is reversible with respect to . Reversibility gives invariance, , as in the definition. Finally, replacing by for any constant leaves — a ratio of -values — unchanged, so depends on only through its shape; the unknown normaliser drops out entirely.

Bridge. This invariance proof builds toward the ergodic theorem that makes ergodic averages consistent, and it appears again in every sampler below, because the Gibbs sampler is the special case in which each proposal is a full conditional and holds with both acceptance probabilities equal to . The foundational reason the algorithm needs only ratios is structural: detailed balance is a statement about the symmetric measure , and a common rescaling of cancels on the two sides of . This is exactly the cancellation foreshadowed in the Beginner island picture, now made into an identity, and it generalises the reversible-chain construction of 37.05.07 from a finite state space to a general one. Putting these together, the design recipe for any MCMC sampler is to engineer detailed balance for the desired target and then invoke ergodicity; the central insight is that local reversibility, checked one pair at a time, certifies a global invariant law. The bridge to computation is that this invariant law is the posterior of 26.07.01, so a chain you can simulate replaces an integral you cannot evaluate.

Exercises Intermediate+

Advanced results Master

The invariance theorem gives a chain with the right stationary law; turning ergodic averages into consistent, asymptotically normal estimators requires the general-state-space ergodic theory, and tuning the sampler requires understanding its rate.

Theorem 1 (consistency of ergodic averages). Let be a -invariant transition kernel that is -irreducible and Harris recurrent. For every -integrable and every starting point,

This is the general-state-space analogue of the Markov-chain ergodic theorem of 37.05.07; Harris recurrence replaces positive recurrence as the hypothesis ensuring that the time-average is independent of the start. For Metropolis-Hastings chains with a proposal positive on the support of , -irreducibility and Harris recurrence are met under mild conditions (Tierney 1994 [Tierney 1994]), so the constructed sampler is automatically a valid estimator of posterior expectations.

Theorem 2 (MCMC central limit theorem and the spectral gap). Suppose is -reversible with a spectral gap (its self-adjoint operator has spectral radius below on mean-zero functions), and . Then

The asymptotic variance is the integrated autocovariance; for a reversible chain it equals on mean-zero , finite precisely when the gap is positive. The effective sample size with integrated autocorrelation time quantifies how many independent draws the correlated chain is worth.

Theorem 3 (geometric ergodicity and convergence rate). If is -reversible and there exist , , with the drift condition for a small set , then is geometrically ergodic: for some . Geometric ergodicity is what licences a finite burn-in and the MCMC central limit theorem for all with . Random-walk Metropolis on a target with exponentially decaying tails is geometrically ergodic; on heavy-tailed targets it can fail to be, and the ergodic average then converges with no Gaussian-rate guarantee.

Theorem 4 (optimal scaling of random-walk Metropolis). For a product target in dimension with proposal , standard, the efficient scaling is , and as the rescaled first coordinate converges to a Langevin diffusion whose speed is maximised at an acceptance rate of (Roberts-Gelman-Gilks 1997 [Roberts-Gelman-Gilks 1997]). The practical tuning heuristic — aim for roughly a quarter of proposals accepted — is the finite-dimensional shadow of this diffusion limit.

Synthesis. The foundational reason MCMC works is a clean separation of two problems that detailed balance and ergodicity solve in turn: invariance is engineered locally by the Metropolis-Hastings acceptance rule, and consistency is then inherited globally from the ergodic theorem, exactly as in the finite-chain theory of 37.05.07 now lifted to a continuum by Harris recurrence. This is the central insight of the subject — the same trajectory that explores the posterior also estimates expectations over it, so one simulation does the work of both sampling and integration. The asymptotic variance of Theorem 2 and the geometric rate of Theorem 3 are dual descriptions of a single quantity, the spectral gap: the gap controls how fast forgets its start and, identically, how small the integrated autocorrelation time of the estimator is. Putting these together with the optimal-scaling result of Theorem 4 gives the complete operational picture, where tuning the proposal is tuning the gap and the gap is what the acceptance heuristic silently optimises. The bridge from this machinery back to inference is that the invariant law is the Bayesian posterior of 26.07.01, and the ratio-only acceptance rule generalises the reversible-chain construction so that the intractable marginal likelihood never has to be computed; what looks like an integration problem is, on inspection, a simulation problem.

Full proof set Master

Proposition 1 (detailed balance implies invariance, general state space). If as measures on , then .

Proof. For measurable , integrate the symmetric measure over . The left side gives . The right side gives , since is a probability measure. Hence for all .

Proposition 2 (Metropolis-Hastings reversibility). The kernel of the Formal-definition section satisfies detailed balance for .

Proof. On the diagonal the rejection mass contributes symmetrically. Off-diagonal, the claim is for . With and , : if both sides equal ; if both sides equal . The two cases are the computation in the Key theorem. Reversibility plus Proposition 1 give invariance.

Proposition 3 (Gibbs as rejection-free Metropolis-Hastings, with invariance). A full-conditional update of component , with , is a Metropolis-Hastings step with acceptance probability , and it leaves invariant.

Proof. Take proposal for moves changing only coordinate . The acceptance ratio is

using and that share . So . Invariance follows from Proposition 2, or directly: the kernel has , the inner -integral being .

Proposition 4 (invariance of compositions and mixtures). If are each -invariant, then both the composition and any convex mixture are -invariant.

Proof. Composition: . Mixture: , since . The cycle-scan Gibbs sampler is the composition ; the random-scan version is the mixture . Both are -invariant by Proposition 3 plus this proposition.

Proposition 5 (normalising constant cancels). Replacing the target by for any leaves the Metropolis-Hastings kernel unchanged.

Proof. The kernel depends on only through . The substitution multiplies numerator and denominator of the inner ratio by , which cancels, so and hence are unchanged. In particular, knowing the posterior only up to its marginal likelihood is sufficient to run the sampler.

Proposition 6 (asymptotic variance for a reversible chain). For a -reversible with spectral gap and mean-zero , the limiting variance of is , which is nonnegative and finite.

Proof. By the spectral theorem for the self-adjoint operator on mean-zero , write over the spectrum (gap excludes the endpoints from the mean-zero part). Stationary lag covariances are with the spectral measure of . Summing the geometric series, . The integrand on and is bounded by under the gap, so is finite and nonnegative. The finite-state eigen-sum of Exercise 8 is the discrete case.

Connections Master

  • The Markov property and transition matrices of 37.05.01 supply the kernel formalism on which every sampler is built: an MCMC sampler is a transition kernel, and the Chapman-Kolmogorov composition there is what lets the cycle-scan Gibbs sampler be analysed as a product of component kernels. The -step convergence of that unit is the finite-state shadow of the geometric ergodicity used here to license burn-in.

  • The ergodic theorem and detailed balance of 37.05.07 are the direct parent: that unit proves, on a countable state space, both that detailed balance gives a stationary law and that time-averages converge to space-averages, and it already exhibits the Metropolis-Hastings acceptance ratio as the reversibility-design tool. The present unit specialises the construction to a target posterior and lifts the convergence statement to a general state space via Harris recurrence, so the algorithm estimates expectations rather than merely admitting a stationary law.

  • The Bayesian prior-posterior framework of 26.07.01 is what MCMC makes computational: the target here is precisely the posterior defined there, and the cancellation of the normalising constant is exactly what removes the intractable marginal likelihood from posterior summarisation, turning conjugate-only Bayesian analysis into a method usable on any model whose likelihood can be evaluated.

Historical & philosophical context Master

The algorithm originates in statistical physics. Metropolis, the Rosenbluths, and the Tellers introduced the symmetric-proposal accept/reject scheme in 1953 to compute equilibrium properties of interacting particles by sampling the Boltzmann distribution on the MANIAC computer [Metropolis 1953], formulating the rule as an acceptance probability depending only on the energy difference — the physical analogue of the target ratio. Hastings generalised the method to arbitrary, possibly asymmetric, proposals in 1970, supplying the correction factor that makes the construction work for any target and recasting it as a tool for general Monte Carlo computation rather than a physics-specific device [Hastings 1970].

The method entered statistics decisively through image analysis: Geman and Geman introduced the Gibbs sampler in 1984 for Bayesian restoration of images modelled by Gibbs random fields, naming it for the Gibbs distributions it sampled and exploiting the tractable full conditionals of Markov random fields [Geman 1984]. The recognition that the same machinery applied to general Bayesian posteriors, made widely known by Gelfand and Smith in 1990, set off the computational revolution that made hierarchical and high-dimensional Bayesian models practical. The general-state-space theory — -irreducibility, Harris recurrence, and the ergodic theorem and central limit theorem that justify the estimators — was systematised by Tierney in 1994 [Tierney 1994], building on the Markov-chain stability theory of Meyn and Tweedie.

Bibliography Master

@article{Metropolis1953,
  author  = {Metropolis, Nicholas and Rosenbluth, Arianna W. and Rosenbluth, Marshall N. and Teller, Augusta H. and Teller, Edward},
  title   = {Equation of State Calculations by Fast Computing Machines},
  journal = {Journal of Chemical Physics},
  volume  = {21},
  number  = {6},
  pages   = {1087--1092},
  year    = {1953}
}

@article{Hastings1970,
  author  = {Hastings, W. K.},
  title   = {Monte Carlo Sampling Methods Using Markov Chains and Their Applications},
  journal = {Biometrika},
  volume  = {57},
  number  = {1},
  pages   = {97--109},
  year    = {1970}
}

@article{GemanGeman1984,
  author  = {Geman, Stuart and Geman, Donald},
  title   = {Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images},
  journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
  volume  = {6},
  number  = {6},
  pages   = {721--741},
  year    = {1984}
}

@article{GelfandSmith1990,
  author  = {Gelfand, Alan E. and Smith, Adrian F. M.},
  title   = {Sampling-Based Approaches to Calculating Marginal Densities},
  journal = {Journal of the American Statistical Association},
  volume  = {85},
  number  = {410},
  pages   = {398--409},
  year    = {1990}
}

@article{Tierney1994,
  author  = {Tierney, Luke},
  title   = {Markov Chains for Exploring Posterior Distributions},
  journal = {Annals of Statistics},
  volume  = {22},
  number  = {4},
  pages   = {1701--1762},
  year    = {1994}
}

@article{RobertsGelmanGilks1997,
  author  = {Roberts, Gareth O. and Gelman, Andrew and Gilks, Walter R.},
  title   = {Weak Convergence and Optimal Scaling of Random Walk Metropolis Algorithms},
  journal = {Annals of Applied Probability},
  volume  = {7},
  number  = {1},
  pages   = {110--120},
  year    = {1997}
}

@book{RobertCasella2004,
  author    = {Robert, Christian P. and Casella, George},
  title     = {Monte Carlo Statistical Methods},
  edition   = {2},
  publisher = {Springer},
  year      = {2004}
}

@book{GelmanBDA2013,
  author    = {Gelman, Andrew and Carlin, John B. and Stern, Hal S. and Dunson, David B. and Vehtari, Aki and Rubin, Donald B.},
  title     = {Bayesian Data Analysis},
  edition   = {3},
  publisher = {CRC Press},
  year      = {2013}
}

@book{MeynTweedie2009,
  author    = {Meyn, Sean and Tweedie, Richard L.},
  title     = {Markov Chains and Stochastic Stability},
  edition   = {2},
  publisher = {Cambridge University Press},
  year      = {2009}
}