Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Markov chain Monte Carlo

ProblemDraw samples from a probability density known only up to a constant factor, typically a Bayesian posterior, to estimate expectations, quantiles and uncertainties
Devised byNicholas Metropolis, Arianna and Marshall Rosenbluth, Augusta and Edward Teller (1953); W. Keith Hastings (1970); Stuart and Donald Geman (1984), Gibbs sampling; Gareth Roberts, Andrew Gelman and Walter Gilks (1997), optimal scaling; Heikki Haario, Eero Saksman and Johanna Tamminen (2001), adaptive proposals
AccuracyErrors of averages fall like , where is the integrated autocorrelation time of the chain
CostOne evaluation of the log-density per step
Read firstSampling from probability distributions
APImetropolis_hastings, MetropolisOptions, MarkovChain

Overview

In Bayesian statistics the object of interest is the posterior density , which is easy to evaluate up to its normalising constant, but whose normalisation is an integral over all the parameters: intractable beyond a few dimensions. The same problem arises in statistical physics, where the Boltzmann distribution has an unknown partition function. Markov chain Monte Carlo (MCMC) sidesteps the constant: it constructs a random walk whose long-run distribution is the target, using only ratios of densities, and estimates expectations by averages along the walk.

The price is correlation. Successive states of the chain are dependent, so steps carry the information of fewer independent samples, and the art of MCMC is to make the chain mix quickly.

Where it is used

Markov chain Monte Carlo makes Bayesian inference practical.

  • Bayesian statistics. Sampling the posterior of a model’s parameters in epidemiology, astronomy, genetics and engineering, with credible intervals.
  • Statistical physics. The Metropolis algorithm, from which MCMC grew, simulates the Ising model and fluids.
  • Machine learning. Sampling from complicated distributions in probabilistic models.
  • Inverse problems. Estimating parameters of a physical model with uncertainty from noisy data.

History

Nicholas Metropolis, Arianna Rosenbluth, Marshall Rosenbluth, Augusta Teller and Edward Teller (1953) introduced the algorithm at Los Alamos to compute the equation of state of a system of interacting particles on the MANIAC computer; Arianna Rosenbluth wrote the program. W. Keith Hastings (1970) generalised it to asymmetric proposals. Stuart and Donald Geman (1984) introduced Gibbs sampling for image restoration, and Alan Gelfand and Adrian Smith (1990) showed statisticians how to compute Bayesian posteriors with it, which transformed applied statistics. Gareth Roberts, Andrew Gelman and Walter Gilks (1997) proved that random-walk proposals mix best at an acceptance rate of about 0.234 in high dimensions, and Haario, Saksman and Tamminen (2001) began the theory of adaptive MCMC. Hamiltonian Monte Carlo (Duane et al., 1987) and its tuned variant NUTS (Hoffman and Gelman, 2014) power modern systems such as Stan.

The idea

The Metropolis-Hastings algorithm

The task is to draw samples from a target density that is known only up to a constant factor: we can evaluate a function proportional to at any point, but we cannot compute its normalising constant, invert its CDF or find an envelope for it. This is the usual situation in Bayesian statistics, where the posterior density is a product of a likelihood and a prior.

The idea of Markov chain Monte Carlo is to give up independence. Instead of independent samples, generate a sequence in which each state is obtained by a random move from the previous one (a Markov chain), with the moves arranged so that, in the long run, the chain visits each region in proportion to its probability under . Averages along the chain then approximate averages under .

One step. From the current state :

  1. propose a new state , drawn from a proposal density of our choosing;
  2. compute the acceptance probability

  1. with probability move to ; otherwise stay at , and record again as the next state of the chain.

Only the ratio appears, so the unknown normalising constant cancels. That is what makes the method applicable.

Why it works. A distribution is stationary for a chain if, once the state is distributed according to , it remains so after a step. A sufficient condition is detailed balance: for every pair of states, the flow of probability from to equals the flow back,

where is the probability density of moving from to . If every such exchange is in balance, no region gains or loses probability overall. The acceptance rule is designed to make this hold. Suppose the unbalanced flow from to is the larger of the two. Then the ratio in is below 1, so moves in that direction are thinned out by exactly the factor needed, while moves in the opposite direction are always accepted (). Both flows then equal .

So is the stationary distribution, and under mild conditions (the chain must be able to reach every region) the distribution of the state converges to from any starting point.

The random-walk version. The library implements the simplest proposal: add Gaussian noise to the current state, with standard normal and a step size for each coordinate. This proposal is symmetric, , so cancels and

A move to a more probable state is always accepted; a move to a less probable one is accepted with probability equal to the ratio of the densities. Two implementation points: the library works with log-densities, comparing with , which avoids overflow and underflow; and a log-density of marks points outside the support, which are always rejected.

Burn-in, thinning and the proposal scale

Three practical matters decide whether a chain is useful.

Burn-in. The chain starts wherever it is put, possibly in a region of negligible probability, and its early states reflect the starting point, not the target. They are discarded as burn-in.

Thinning. Successive states are correlated, since each is a small move from the last, or no move at all. Keeping only every -th state (thinning) reduces the correlation between the states kept and saves storage. It does not improve the estimates: the discarded states also carried information.

The proposal scale. The step size decides how fast the chain explores, and it can be wrong in either direction. If it is too small, almost every proposal is accepted, but each move is tiny and the chain crawls. If it is too large, almost every proposal lands far out in the tails and is rejected, and the chain stays stuck at one point for long stretches. On a standard normal target, started from :

Figure 9.4. Traces of three chains.

The autocorrelation of a chain is the correlation between states steps apart. For an efficient chain it falls quickly to zero as grows; for a crawling or a sticking chain it stays high for hundreds of steps:

Figure 9.5. Autocorrelation.

Effective sample size

How much is a correlated sample worth? For independent samples with variance , the variance of their average is . For a correlated chain it is larger,

where is the integrated autocorrelation time, the sum of the autocorrelations at all lags. Comparing the two formulas, correlated samples are worth as much as independent ones. That number is the effective sample size:

Table 9.10. Random-walk Metropolis: acceptance and autocorrelation against step size.

proposal stepacceptance rateautocorrelation time effective samples (of 50 000)sample mean (exact 0)
step 0.1 (too small)0.971400.8125-0.119
step 2.4 (about right)0.4424.212032-0.004
step 25 (too large)0.05126.41893+0.020
adapted from 0.1 during 5000 burn-in steps: 2.450.4354.212016+0.011

The well-tuned chain is a hundred times more efficient than the timid one.

A convenient way to tune the step size is through the acceptance rate, which is easy to observe. Theory for random-walk proposals gives an optimal acceptance rate of about 0.44 in one dimension and about 0.234 in many dimensions. The library adapts the scale towards these rates during burn-in (multiplying it every 100 steps by , where is the observed rate and the target), as the last row shows. After burn-in the scale is kept fixed: a chain whose rules keep changing in response to its own history is no longer a Markov chain, and the argument above would not apply.

Difficult targets

Random-walk proposals explore curved or strongly correlated densities slowly, because the step must be small enough for the narrowest direction. A banana-shaped density, and , is still sampled correctly, with thinning:

Figure 9.6. Banana-shaped density.

Multimodal densities are harder still: a random walk may never cross between modes. Gradient-based methods (Hamiltonian Monte Carlo), tempering and problem-specific proposals address these cases.

Algorithm

Input: the log-density , a starting state , the proposal scales , the number of burn-in steps, the number of samples wanted and the thinning interval.

  1. Start. Evaluate . It must be finite: a chain cannot start outside the support.
  2. Propose. Draw a vector of independent standard normals and form . Evaluate .
  3. Accept or reject. Draw a uniform . If , or , move to . Otherwise stay at . (The first test is implied by the second, and merely saves a logarithm.)
  4. Adapt, during burn-in only and only if requested: every 100 steps, compute the fraction of those steps that were accepted and multiply by .
  5. Record. After burn-in, store the current state every thin steps. A rejected proposal means the same state is stored again.
  6. Repeat from step 2 until enough states have been stored.

Each step costs one evaluation of the log-density.

Implementation

/// Samples from the density proportional to `exp(log_density(x))` by random-walk
/// Metropolis-Hastings: propose `x' = x + σ ⊙ z` with `z` standard normal, accept with
/// probability `min(1, p(x')/p(x))`. Only an unnormalised log-density is needed; returning
/// `−∞` marks points outside the support.
pub fn metropolis_hastings<F, U>(log_density: F, initial: Vec<f64>, options: MetropolisOptions, rng: &mut U) -> Result<MarkovChain, ErrorsJSL>
where
    F: Fn(&[f64]) -> f64,
    U: UniformGenerator,
{
    let d = initial.len();
    let unit_scale = vec![1.0; d];
    let proposal_scale = if options.proposal_scale.is_empty() { &unit_scale } else { &options.proposal_scale };
    if d == 0 || proposal_scale.len() != d || options.samples == 0 || options.thin == 0 {
        return Err(ErrorsJSL::InvalidInputRange("Need a non-empty start, a matching proposal scale, samples and thin >= 1."));
    }
    if proposal_scale.iter().any(|s| s.is_nan() || *s <= 0.0) {
        return Err(ErrorsJSL::InvalidInputRange("Proposal scales must be positive."));
    }
    let mut x = initial;
    let mut log_p = log_density(&x);
    if log_p.is_nan() || log_p == f64::NEG_INFINITY {
        return Err(ErrorsJSL::InvalidInputRange("The initial point must have positive density."));
    }
    let mut scale = proposal_scale.clone();
    let target = if d == 1 { 0.44 } else { 0.234 };
    let total = options.burn_in + options.samples * options.thin;
    let mut samples = Vec::with_capacity(options.samples);
    let (mut accepted, mut window_accepted) = (0usize, 0usize);
    let mut z = Vec::with_capacity(d + 1);
    for step in 0..total {
        z.clear();
        while z.len() < d {
            let (a, b) = gaussian_distribution_box_muller(rng, 0.0, 1.0);
            z.push(a);
            z.push(b);
        }
        let proposal: Vec<f64> = (0..d).map(|i| x[i] + scale[i] * z[i]).collect();
        let log_q = log_density(&proposal);
        let accept = log_q > f64::NEG_INFINITY && (log_q >= log_p || rng.next_f64().ln() < log_q - log_p);
        if accept {
            x = proposal;
            log_p = log_q;
            window_accepted += 1;
            if step >= options.burn_in {
                accepted += 1;
            }
        }
        if step < options.burn_in {
            if options.adapt_during_burn_in && (step + 1) % 100 == 0 {
                let rate = window_accepted as f64 / 100.0;
                let factor = ((rate - target) * 2.0).exp();
                scale.iter_mut().for_each(|s| *s *= factor);
                window_accepted = 0;
            }
        } else if (step - options.burn_in) % options.thin == options.thin - 1 {
            samples.push(x.clone());
        }
    }
    Ok(MarkovChain { samples, acceptance_rate: accepted as f64 / (options.samples * options.thin) as f64, proposal_scale: scale })
}
  • MarkovChain holds the samples, the post-burn-in acceptance rate and the final proposal scale, with mean and autocorrelation helpers.
  • Check convergence: run several chains from different starts and compare them, and look at traces and autocorrelations.

In practice

//! Bayesian inference by Markov chain Monte Carlo.
//!
//! Run with `cargo run -p lib_jsl_random --example random_mcmc`.

use lib_jsl_random::mcmc::{MetropolisOptions, metropolis_hastings};
use lib_jsl_random::uniform_generator::UniformRNG;

fn main() {
    // A dose-response experiment: at dose d, n animals, k responded. Model P(response) =
    // 1/(1 + e^{−(a + b d)}) with weak normal priors on a and b; sample the posterior of (a, b).
    let data = [(-0.86, 5, 0), (-0.30, 5, 1), (-0.05, 5, 3), (0.73, 5, 5)];
    let log_posterior = |p: &[f64]| {
        let (a, b) = (p[0], p[1]);
        let prior = -(a * a + b * b) / (2.0 * 100.0);
        let likelihood: f64 = data.iter().map(|&(d, n, k)| {
            let eta = a + b * d;
            // log p = −ln(1 + e^{−η}), log(1 − p) = −ln(1 + e^{η}), computed stably.
            let log_p = -(-eta).exp().ln_1p();
            let log_q = -eta.exp().ln_1p();
            k as f64 * log_p + (n - k) as f64 * log_q
        }).sum();
        prior + likelihood
    };
    let options = MetropolisOptions { proposal_scale: vec![1.0, 2.0], samples: 20_000, burn_in: 5_000, thin: 5, adapt_during_burn_in: true };
    let chain = metropolis_hastings(log_posterior, vec![0.0, 0.0], options, &mut UniformRNG::from_seed(1)).unwrap();
    let mean = chain.mean();
    println!("posterior means: a = {:.2}, b = {:.2}", mean[0], mean[1]);
    println!("acceptance rate {:.2}, lag-1 autocorrelation of a {:.2}", chain.acceptance_rate, chain.autocorrelation(0, 1));

    // The dose at which half respond, LD50 = −a/b, has a posterior too: summarise its quantiles.
    let mut ld50: Vec<f64> = chain.samples.iter().map(|s| -s[0] / s[1]).collect();
    ld50.sort_by(f64::total_cmp);
    let q = |p: f64| ld50[(p * (ld50.len() - 1) as f64) as usize];
    println!("LD50: median {:.3}, 95% interval [{:.3}, {:.3}]", q(0.5), q(0.025), q(0.975));
}

Strengths

  • Needs only an unnormalised log-density; simple and general.
  • Adaptive tuning of the step during burn-in.

Weaknesses

  • Correlated samples: the effective sample size can be far below the number of steps.
  • Random-walk proposals scale poorly with dimension and curvature, and cannot cross between separated modes.
  • Convergence is diagnosed, never guaranteed.

Exercises

  1. Prove that the Metropolis-Hastings transition satisfies detailed balance with respect to .
  2. For a random walk on with step , estimate the acceptance rate and for , and find the that minimises .
  3. Sample a mixture of two normals at and at with unit variance. How often does the chain switch modes?
  4. Implement a Gibbs sampler for a bivariate normal with correlation 0.99 and compare its autocorrelation time with random-walk Metropolis.
  5. Fit the dose-response model of the example by maximum likelihood and compare with the posterior means.
Hints and answers
  1. The Metropolis-Hastings kernel is . Then , which is symmetric in and : detailed balance.
  2. For a random walk on the acceptance rate is : about , and for , and . Small steps are accepted but move slowly and large steps are mostly rejected, so is smallest in between, near , the classical optimum in one dimension.
  3. With modes at the density at the midpoint is of the peak and a random walk crosses regularly. With modes at it is of the peak and a chain with moderate steps almost never crosses.
  4. For correlation Gibbs sampling has autocorrelation time about for : each coordinate moves only a fraction of the target’s width per step. A random walk Metropolis with an isotropic step suffers similarly (and worse if the step is not tuned).
  5. At the optimum the posterior means and the maximum-likelihood estimates should be close when the prior is weak and the data plentiful; large differences indicate an informative prior or a skewed posterior.

Further reading

  • N. Metropolis, A. W. Rosenbluth, M. N. Rosenbluth, A. H. Teller and E. Teller, “Equation of state calculations by fast computing machines”, Journal of Chemical Physics 21 (1953) 1087–1092.
  • W. K. Hastings, “Monte Carlo sampling methods using Markov chains and their applications”, Biometrika 57 (1970) 97–109.
  • G. O. Roberts, A. Gelman and W. R. Gilks, “Weak convergence and optimal scaling of random walk Metropolis algorithms”, Annals of Applied Probability 7 (1997) 110–120.
  • S. Brooks, A. Gelman, G. L. Jones and X.-L. Meng (eds.), Handbook of Markov Chain Monte Carlo, CRC Press, 2011.
  • A. Gelman et al., Bayesian Data Analysis, 3rd ed., CRC Press, 2013, chapters 11–12 (the bioassay example).