Elamur Research

An Introduction to MCMC for Machine Learning

Paper · 2003 · Christophe Andrieu, Nando de Freitas, Arnaud Doucet B et al.

Summary

A probability can be easy to evaluate at a particular point and still be hard to use. In Bayesian inference, for instance, a prior and a likelihood can tell us how plausible one set of unknowns is relative to another. Finding the average value of an unknown, or assigning probability to a whole range of values, may require integrating over more possibilities than a direct calculation can handle. Andrieu and colleagues explain how to replace such calculations with averages over simulated states. Their subject is Markov chain Monte Carlo, or MCMC, and its role in machine learning.

The central idea is to construct a random walk with a prescribed long-run distribution. The Metropolis–Hastings algorithm proposes a new state and decides whether to accept it using the relative plausibility of the two states and the probabilities of proposing the move in either direction. The calculation needs only relative target values, so an unknown normalizing constant cancels. The paper shows how the same framework accommodates updates to groups of variables, direct draws from conditional distributions, proposals guided by gradients, and moves between explanations with different numbers of parameters. It also explains how changing the target over time turns sampling into a search for a global optimum.

The demonstrations make the choice of proposal concrete. With a Gaussian proposal and a target with two peaks, the histogram from a run of 5000 iterations resembles the target. Other settings of the proposal scale show how the same algorithm can spend its time around just one peak or repeatedly reject large moves. A separate illustration uses simulated annealing on the same target to show how cooling redirects the search towards high points. These examples explain the behavior of the algorithms through known targets and visible comparisons.

The review also examines what it takes to establish convergence, why tuning a sampler from its own history can change the distribution it produces, and how to use Markov chain updates inside a particle filter as new observations arrive. Its practical argument is that a correct acceptance rule and a useful proposal solve different parts of the problem. The rule establishes the distribution the chain should preserve. The proposal determines how readily the chain can move through that distribution in a finite run.

Deep dive: An Introduction to MCMC for Machine Learning

A guide to how Markov chain Monte Carlo estimates difficult averages, explores competing explanations, and searches for global optima. · about 42 minutes to read

The problem and its context

When probabilities are easier to compare than to add up

In the Bayesian setting described by the authors, the data are observed and some quantities that could explain them are unknown. The prior describes the plausibility of those quantities before the data are considered. The likelihood measures how well a particular choice accounts for the observations. Their product gives a score for each possible choice. To turn these scores into a posterior probability distribution, one must divide by their total over the space of unknowns. In a continuous space that total is an integral, and evaluating it can be difficult even when the score at an individual point is straightforward.

Normalization is only one of the required calculations. A joint posterior may contain several unknowns whose values depend on one another. A reader interested in one of them wants the marginal distribution, which combines the probability associated with every value of the other unknowns. An expectation asks a different question. It averages a function of the unknowns under the posterior, giving quantities such as a mean or a probability of an event. All these questions ask for information about a region or about the distribution as a whole. Evaluating the score at a promising point can be a useful start, but it supplies none of those totals by itself.

The authors draw a parallel with statistical mechanics. A physical system can be described through the energy of each possible configuration. Each energy determines a weight, and the partition function is the sum of the weights over the configurations. The difficulty lies in the range of configurations to be accounted for. The same structure appears in Bayesian normalization, where a sum or integral over possible explanations plays the role of the partition function. Sampling provides a way to study the distribution without traversing every configuration, although obtaining the partition function itself is a separate computational problem.

Optimization has a related difficulty and a different objective. The desired answer is a feasible choice with the best objective value, and the feasible set can be continuous or unbounded. There is also a selection problem when the candidate explanations differ in structure. In the procedure discussed by the paper, one can fit each candidate by maximum likelihood and then choose among the fits with a penalty such as minimum description length. That procedure may spend substantial effort fitting candidates that will have little bearing on the final decision. A stochastic search can instead devote effort according to how it moves among the candidates. If the goal is Bayesian averaging, visits to multiple candidates also carry information about uncertainty over the choice itself.

How simulation became a way to do inference

The paper relates the Monte Carlo principle through Stan Ulam’s question about solitaire. He wanted to know how often a layout from a deck of 52 cards would lead to a successful game. A direct combinatorial calculation required accounting for the possibilities systematically. Randomly laying out games and counting successes gave him an alternative: the observed frequency could stand in for the probability he wanted. The calculation moved from tracing all possible cases to repeatedly carrying out a simpler operation and recording its result.

The authors describe similar thinking in early work on neutron diffusion. They recount how Ulam and John Von Neumann developed simulation techniques, including rejection and importance sampling, and note Enrico Fermi’s earlier work on diffusion calculations. The public account that Metropolis and Ulam published in 1949 also described particle methods. In the paper’s historical account, those methods anticipate later schemes that represent a changing distribution through a population of samples.

The Metropolis algorithm appeared in 1953. Its move from isolated draws to a chain of dependent states was important for problems where an accessible distribution could supply trial values but was a poor substitute for the distribution of interest. Hastings generalized the acceptance rule in 1970, allowing the probability of proposing a move to differ from the probability of proposing its reverse. The review follows the formulation studied by Hastings and Peskun. That formulation exposes the proposal as a design choice: an algorithm can suggest moves using knowledge of the problem, and the acceptance calculation can correct for the bias of those suggestions.

The paper traces subsequent applications through computer vision and artificial intelligence in the 1980’s, then identifies 1990 as the point at which MCMC began to have a substantial effect in statistics. It also singles out Neal’s work on neural networks as influential in that field. By the time of the review, the authors could draw examples from image analysis, signal processing, graphical inference, and other settings. They were concerned with how to make the methods work in such settings, where a finite run must cover enough of a complicated space to answer a scientific question.

Why a chain can help when independent proposals struggle

Rejection sampling starts from a distribution that is easy to sample and accepts each independent proposal with a probability chosen to correct its distribution. It needs a bound that holds everywhere the target is positive. If the proposal assigns very little probability to a region that matters to the target, that region can force the bound to be large. The algorithm then rejects often, including in regions where the proposal would otherwise work well.

Importance sampling corrects the proposal by giving each draw a weight. This avoids the need for an accept-or-reject decision, but the result can depend heavily on draws that receive large weights. A proposal that works for one integral can also be a poor choice for another. A rare-event calculation benefits from drawing in the region where the event occurs, whereas an approximation intended to answer many questions about a posterior needs more extensive coverage.

A Markov chain can make proposals conditional on its current state. In a locally smooth region, the chain can explore nearby possibilities without having to discover that region again on every draw. It can also mix local updates with occasional moves designed to reach remote regions. This flexibility comes with a new obligation. Samples along the path are dependent, and the behavior of the chain depends on its ability to move between regions. The paper puts that obligation alongside the formal requirement that the chain preserve the target.

The method, step by step

From an integral to a sample average

Consider a posterior based on observations already in hand. The unknowns might be a signal’s parameters or the latent quantities associated with an observed dataset. The first distinction is between the distribution one wants to learn about and the operation one wants to perform on it. For Bayesian inference, the distribution is obtained through normalization.

p(x | y) = p(y | x)p(x) / ∫ₓₑ∈𝒳 p(y | xₑ)p(xₑ) dxₑ

Here 𝒳 is the space of the unknowns, x is a particular value in that space, and y denotes the observed data. The vertical bar means conditioning. The expressions p(x), p(y | x), and p(x | y) are the prior, likelihood, and posterior, respectively. The dummy variable xₑ runs over 𝒳, the integral sign adds the weighted contributions across that space, and dxₑ denotes the integration element. The denominator depends on the data and is common to all x.

When an analysis includes an additional unknown z, the marginal posterior of x is obtained by integrating the joint posterior over z. An expectation may then be taken under that marginal or under the original joint distribution. The paper writes the general Monte Carlo problem using a target p(x), which can stand for the posterior at the fixed data.

I(f) = ∫ₓ∈𝒳 f(x)p(x) dx

The symbol I(f) is the desired expectation. The function f supplies the value to average at the state x, p(x) is the normalized target density, 𝒳 is the state space, and dx is the integration element. For a discrete state space, the corresponding calculation sums over states. If f is an indicator, it takes the value appropriate to whether a state belongs to an event, and the expectation is the probability of that event. Taking f(x) to be x gives a mean. The paper also uses products of coordinates, centered through their means, to illustrate covariance.

If independent draws from p are readily available, the authors represent them as a collection of equally weighted point masses. A point mass places all its weight at its sampled location. Integrating f against this empirical distribution amounts to averaging f over the sample.

Iₙ(f) = (1/N) Σᵢ₌₁ᴺ f(x⁽ⁱ⁾)

Here Iₙ(f) is the estimate using N draws, the subscript n denotes the sample size N, Σ denotes summation, and i indexes the draws from the first through the Nth. The notation x⁽ⁱ⁾ denotes the ith sampled state. The factor 1/N gives each draw equal weight, and f is the function being averaged. In this independent setting the estimate is unbiased, meaning that its expectation over repetitions is I(f). The strong law of large numbers gives almost-sure convergence as the number of draws grows.

Var(Iₙ(f)) = σ²f / N

The operator Var denotes variance across repeated sample sets. The symbol σ²f denotes the variance of the scalar value f(x) for x drawn from the target, and N is the number of independent draws used in Iₙ(f). When that variance is finite, the paper also gives a central limit theorem: the error, multiplied by the square root of N, approaches a centered Gaussian with variance σ²f. This is an independent-sampling result. It explains why a Monte Carlo estimate can come with a measure of uncertainty and establishes the setting in which the displayed variance formula applies.

The paper gives a simple way to use the same sample for optimization. Evaluate the target at each visited point and retain the point with the highest value. This answers which sampled point scored best. Its prospects as a search procedure depend on the amount of probability near the maximum. A narrow peak may be higher than a broad region that receives many more samples. The paper’s annealing construction changes the distribution to make visits near the high peak more frequent as cooling proceeds.

Accepting or weighting independent proposals

Rejection sampling begins with an auxiliary distribution q that can generate trial values. A constant M bounds the target by a multiple of q across the state space. After drawing a candidate, the algorithm draws a number uniformly between 0 and 1 and accepts the candidate if that number falls below the candidate’s target-to-envelope ratio.

Pr(accept | x) = p(x) / (Mq(x))

The expression Pr(accept | x) is the chance of retaining a proposed x. The function q is the proposal density and Mq is the envelope, where M is chosen so that the right-hand side is at most 1 on the proposal’s support. The function p is the target, which can be used up to a common positive multiplier if the envelope bounds that same version of it. With normalized p and q, the overall acceptance probability in the paper is 1/M. The factor q governing how often a candidate is drawn cancels against q in the acceptance probability, leaving accepted candidates distributed according to p. Rejections consume proposals and produce no new draw for the accepted sample.

Importance sampling keeps the candidate and changes how it contributes to the estimate. The proposal must cover the support of the target, meaning that it must give access to the places where the target gives positive probability. The ratio between target and proposal corrects for how often the proposal visits each place.

w(x) = p(x) / q(x)

Here w(x) is the importance weight at x, p is the target, and q is the proposal. With normalized p, the expectation under q of f(x)w(x) equals the expectation of f(x) under p, because q cancels in the integral. Averaging f(x)w(x) over independent proposal draws therefore estimates I(f). The paper examines the variance of that weighted quantity, whose proposal-dependent term is the expectation under q of its square. Large weights can matter disproportionately to this term.

q★(x) = |f(x)|p(x) / ∫ₛ∈𝒳 |f(s)|p(s) ds

The symbol q★ is the variance-minimizing proposal for the specified integral in the paper’s calculation. The absolute value |f(x)| measures the size of the contribution from x without regard to sign. The function p is the target, s is a dummy state, 𝒳 is the state space, and the integral with element ds makes q★ a normalized density. The result follows by bounding the second moment of the weighted quantity using Jensen’s inequality. Under the displayed proposal, the absolute weighted contribution is constant wherever it contributes to the integral.

That result gives a way to reason about rare events. When f indicates an event, candidate locations outside the event contribute nothing to the estimate of its probability. Concentrating proposals where the event occurs can reduce variance even compared with direct draws from p. The optimal expression itself may be difficult to sample from, and a different f changes what counts as an important region. For a general representation of the target the authors therefore discuss proposals that approximate p across a wider part of its support.

A parameterized proposal allows the simulation to alter where it draws candidates. The paper describes using the derivative of the importance-sampling second moment to inform such an update. At the current proposal parameters, it draws candidate states, evaluates the weights and their parameter derivatives, and uses the resulting estimate in a step that aims to lower the second moment. The step size is a learning rate. The observations and target remain fixed as this proposal is adjusted. The optimization concerns the sampling mechanism and the variance of its estimator.

When an unknown normalizing constant is present, all the weights share an unknown multiplier. Dividing each weight by the sum of the weights removes it.

Ĩₙ(f) = [Σᵢ₌₁ᴺ f(x⁽ⁱ⁾)w(x⁽ⁱ⁾)] / [Σᵢ₌₁ᴺ w(x⁽ⁱ⁾)]

The quantity Ĩₙ(f) is the self-normalized estimate from N independent draws from q. Both sums use i to index those draws, x⁽ⁱ⁾ is the ith state, f is the function of interest, and w is the weight known up to a common multiplier. The denominator gives the sum of the unnormalized weights. The ratio is generally biased for a finite sample because both numerator and denominator fluctuate. Under the conditions discussed by the paper it still converges almost surely, and the paper notes that it can perform better under squared error in some settings.

Sampling importance resampling turns such a weighted collection into an equally weighted one. Each resampled point is chosen from the original collection with probability given by its normalized weight. A point may appear repeatedly, and some points can disappear altogether. The resampling adds variation to a standalone estimate. Later, when particles must represent a sequence of changing distributions, this same operation plays a different role by selecting which points have descendants.

Designing a chain that preserves the target

A Markov chain uses the current state to determine the probability distribution of the next state. The earlier history has already influenced where the chain is now. Conditional on that state, the next move follows the transition rule. The chain is homogeneous when the rule is fixed across iterations.

Pr(x⁽ⁱ⁾ | x⁽ⁱ⁻¹⁾, …, x⁽¹⁾) = T(x⁽ⁱ⁾ | x⁽ⁱ⁻¹⁾)

The left-hand side is the conditional probability of the state at iteration i given the states at preceding iterations, with the ellipsis indicating the intervening history back to the first state. The right-hand side uses T, the transition probability, and conditions only on x⁽ⁱ⁻¹⁾, the state immediately before x⁽ⁱ⁾. On a finite space the transition matrix has a row of probabilities for each possible current state. In a continuous space the analogous rule is called a transition kernel, which assigns probabilities to sets of possible next states and can include a probability of staying at the current point.

An invariant distribution is one that a transition leaves unchanged. If the current distribution is p, one application of a kernel that preserves p produces p again. One way to build such a kernel is detailed balance, the equality of the probability flow associated with each move and its reverse.

p(x)T(z | x) = p(z)T(x | z)

Here x and z are two states, p assigns mass to them in the finite setting, T(z | x) is the probability of moving from x to z, and T(x | z) is the reverse probability. Each side multiplies the probability of starting at one state under p by the probability of moving to the other. Summing over x gives invariance because the outgoing transition probabilities from z sum to 1. Detailed balance is sufficient for invariance. The paper’s construction of cycles of updates illustrates why invariance is the broader design requirement.

∫ₓ∈𝒳 p(x)K(z | x) dx = p(z)

The symbol K represents the transition kernel, p is the invariant distribution, x ranges over starting states in 𝒳, and z is the destination. The integral and dx express the continuous form of adding all the ways to arrive at z, in density notation. With a kernel that includes point masses, this equality is understood as invariance of the resulting probability measure.

A chain that preserves a distribution still needs a way to reach its different regions. In the finite example, irreducibility means that every state can reach every other state along a path of positive probability. Aperiodicity rules out a compulsory return rhythm. These properties explain why the chain can approach the invariant distribution from arbitrary starts in the finite setting described by the authors. In a continuous setting, reachability concerns regions of positive probability.

The authors illustrate this distinction with the web. A random walker that follows links could remain within a group of pages connected to one another. A component that allows jumps throughout the web gives the walker another route out. The paper uses this construction to explain the invariant ranking in PageRank. The example makes the design problem visible: changing the allowed transitions changes where the walker can go and may change how often it gets there. For MCMC, the desired frequencies are specified first, and the transition rule is designed around them.

The Metropolis–Hastings step

Metropolis–Hastings starts at a state x where the target can be evaluated. The proposal gives a trial state z. The acceptance rule compares their target values and accounts for the proposal’s tendency to make that move and its reverse. If the trial fails the acceptance test, the chain records x again. That repeated state is part of the sample, because the time spent there contributes to its frequency in the chain.

One Metropolis–Hastings sampling loop

The steps in order.

One Metropolis–Hastings sampling loopStep 1: Start at a state with positive target weight1. Start at a state with positive target weightStep 2: Draw a candidate from the proposal2. Draw a candidate from the proposalStep 3: Compare target weights and proposal probabilities3. Compare target weights and proposal probabilitiesStep 4: Accept the candidate or retain the current state4. Accept the candidate or retain the current stateStep 5: Record the resulting state and repeat5. Record the resulting state and repeatStep 6: Average the function over the recorded states6. Average the function over the recorded states
A(x, z) = min{1, p(z)q(x | z) / [p(x)q(z | x)]}

The quantity A(x, z) is the probability of accepting the move from current state x to candidate z. The functions p(x) and p(z) give their target values, q(z | x) is the forward proposal density, and q(x | z) is the reverse proposal density. The operator min takes the smaller of 1 and the displayed ratio. Multiplying both target values by the same constant leaves the ratio unchanged. The chain can therefore be run with the product of prior and likelihood, even when the normalizing integral has not been evaluated.

The transition consists of accepted movement and a probability of remaining at x. Keeping both terms in the kernel accounts for every outcome of the proposal and acceptance procedure.

Kᴹᴴ(z | x) = q(z | x)A(x, z) + δₓ(z)r(x)

Here Kᴹᴴ is the Metropolis–Hastings kernel, z is the next state, x is the current state, q is the proposal, and A is the acceptance probability. The point mass δₓ is concentrated at x. The quantity r(x) is the total probability of rejection at x and multiplies that point mass.

r(x) = ∫𝓋∈𝒳 q(v | x)[1 − A(x, v)] dv

The state v runs over possible proposals in 𝒳, and dv is the integration element. The factor q(v | x) describes how often such a proposal occurs, and 1 − A(x, v) is its chance of rejection. Their integral gives r(x), the overall rejection probability at x. For the accepted part of the kernel, multiplying by p(x) gives the smaller of the two proposed flows, since the minimum in A caps the larger flow at the smaller one. The same smaller value results when the states exchange roles. A self-transition balances itself. This establishes detailed balance for Kᴹᴴ.

The authors discuss support and rejection as ways to establish the other convergence requirements. The proposal needs to allow the chain to reach regions that carry target probability. A positive chance of holding at a state can break a fixed periodic pattern. The design task then turns to how rapidly the chain explores. A transition rule may have the right target and still cross between important regions so rarely that the run gives a poor account of their relative probability.

With a symmetric proposal, forward and reverse proposal densities are equal, so the rule uses only the target ratio. This is the Metropolis random-walk case described by the paper. The chain accepts a candidate with a higher target value and sometimes accepts one with a lower value. The latter moves allow it to pass through low-density regions on the way to other peaks. The choice of the random walk’s scale controls how frequently it attempts such trips and how frequently trial points fall in regions where acceptance is unlikely.

The independent Metropolis sampler uses a proposal q that is the same at every state. Its acceptance probability can be written using the importance weights.

A(x, z) = min{1, w(z) / w(x)}

The quantities x and z are the current and proposed states, w is the ratio of target to independent proposal density, and A is the acceptance probability. The minimum with 1 caps the ratio as before. The trial values can be drawn independently from q. The resulting states of the chain are dependent, since each trial is tested against the current state and a rejection repeats that state. The comparison with importance sampling therefore concerns how the proposal is corrected as well as how its candidates are drawn.

Combining several ways to move

A proposal that can cross a large space may land imprecisely within a narrow peak. A proposal that explores a peak closely may take a long time to reach another one. The authors discuss using separate transition kernels for these roles. If each kernel preserves the same target p, a mixture chooses among them with fixed probabilities, and a cycle applies them in a fixed sequence. Starting from p, every component step leaves p in place, which explains why both constructions preserve it.

Kₘᵢₓ = νK₁ + (1 − ν)K₂

The quantities K₁ and K₂ are transition kernels with invariant distribution p. The kernel Kₘᵢₓ selects K₁ with probability ν, which lies between 0 and 1, and K₂ with probability 1 − ν. The weighted sum acts on transition probabilities. The product K₁K₂ used for a cycle instead denotes applying K₁ and then K₂. The paper gives examples in which a frequency analysis supplies broad location proposals and a random walk refines them, or observed inputs suggest where to put basis functions and local moves adjust their positions.

A cycle can also divide the unknowns into blocks. Each step updates its own block while conditioning on the current values of the others. If an earlier step in the same cycle has replaced a block, its new value is available to subsequent steps. A block with strongly related variables can move them together. Joint updates over larger blocks can become difficult to propose successfully. The authors present blocking as a way to work with the dependence structure of the unknowns and treat block size as a design tradeoff.

Gibbs sampling is the special case that draws the active block directly from its full conditional distribution. A full conditional gives the distribution of the variables being updated with every other variable fixed. For a single-coordinate update, the Metropolis–Hastings correction is particularly simple.

A(x, z) = min{1, [p(z)p(xⱼ | x₋ⱼ)] / [p(x)p(zⱼ | x₋ⱼ)]} = 1

Here j is the updated coordinate, xⱼ is its old value, zⱼ is its proposed value, and x₋ⱼ is the collection of all coordinates except j. Those other coordinates are identical in x and z. The functions p(x) and p(z) are the joint target values. The two conditional terms are the reverse and forward Gibbs proposal densities, respectively. Each joint value factors into the marginal for the fixed coordinates and the conditional for the active one. In the ratio these factors cancel, so A, the acceptance probability, equals 1. A systematic scan repeats this procedure across the coordinates or blocks in order.

Some full conditionals have forms from which direct draws are straightforward. For others, the paper describes inserting a Metropolis–Hastings update that preserves the required conditional. This maintains the division of the problem into blocks while allowing different computational methods inside different blocks. A directed acyclic graph can further narrow the calculation. Its joint distribution is a product of local conditional factors, each associated with a variable and its parents in the graph.

p(xⱼ | x₋ⱼ) ∝ p(xⱼ | xₚₐ₍ⱼ₎) ∏ₖ∈ch(j) p(xₖ | xₚₐ₍ₖ₎)

The state x contains the variables in the graph. The symbol xⱼ denotes the variable being updated, and x₋ⱼ denotes all the others. The notation pa(j) refers to the parents of j, the variables with arrows into j. The set ch(j) contains the children of j, the variables with arrows from j. The product sign multiplies the conditional factors for those child indices k, each with its own parents pa(k). The proportionality sign means that the right-hand side is normalized as a function of xⱼ. Together, the parents, children, and other parents of the children form the Markov blanket used in the update. The paper names Bayesian Updating with Gibbs Sampling, or BUGS, as software that uses this local structure.

Using samples to fit parameters or to search for an optimum

Expectation maximization, or EM, uses a distribution over hidden variables to fit parameters from observed variables. At the current parameter value, the expectation step averages the complete-data log likelihood over possible hidden values. The maximization step chooses a parameter value that maximizes the resulting function. The hidden values are averaged using the old parameter, even while the prospective parameter varies inside the log likelihood.

Q(θ) = ∫ₓₕ∈𝒳ₕ log p(xₕ, xᵥ | θ) · p(xₕ | xᵥ, θᵒˡᵈ) dxₕ

The quantity Q(θ) is the objective for the maximization step, θ is a candidate parameter value, and θᵒˡᵈ is the current value. The vector xᵥ denotes visible variables and xₕ denotes hidden variables, with 𝒳ₕ their state space. The logarithm acts on the joint likelihood for the complete data, and the conditional density that follows it supplies the weights for hidden configurations. The integral with element dxₕ averages over those configurations while the visible data stay fixed. The next parameter value is the maximizer of Q.

When this expectation is too costly, the paper describes running MCMC on the conditional distribution of the hidden variables and using a sample average in Q. The outer loop then maximizes that approximate objective and repeats the hidden-state calculation with the updated parameter. Drawing a single hidden configuration gives the stochastic EM variant described by the authors. Drawing several gives Monte Carlo EM. The paper also mentions variants that become more deterministic as the fit progresses. Here the chain serves an inner integration task, and the outer procedure produces a point estimate. The objective and the samples change with the current parameter estimate.

Simulated annealing applies stochastic moves to a different kind of optimization problem. It begins with a distribution based on the objective p and changes that distribution by raising p to a power determined by a temperature. At each stage the moves are constructed for the current temperature. The changing schedule makes the full process nonhomogeneous.

pᵢ(x) ∝ p(x)^(1/Tᵢ)

Here i indexes the iteration, pᵢ is the target used at that iteration, x is a candidate solution, and p(x) is the positive objective score whose maximum is sought. The quantity Tᵢ is the temperature, and 1/Tᵢ is the exponent. The proportionality sign indicates normalization over candidate states. Lower temperatures give larger relative weight to higher objective values. Under the regularity conditions discussed in the paper, the limiting target concentrates on the set of global maxima as the temperature approaches 0.

Concentration of the target and convergence of the moving chain are separate questions. A chain needs time to move between promising regions before cooling makes the intervening low-score regions difficult to cross. The authors discuss convergence results that depend on sufficiently rapid mixing of the fixed-temperature transition kernels and a cooling schedule of the following form.

Tᵢ = [C ln(i + T₀)]⁻¹

The temperature at iteration i is Tᵢ. The symbols C and T₀ are problem-dependent constants in the schedule, ln is the natural logarithm, and the exponent −1 takes the reciprocal of the bracketed expression. The authors describe results primarily for finite and compact continuous spaces and also note work on noncompact spaces. The schedule expresses conditions used in convergence arguments. The proposal still determines which movements the stochastic search can accomplish as the temperature falls.

Introducing momentum or a slice

An auxiliary variable gives the chain additional coordinates on which to operate. The joint distribution on the enlarged space must recover the original target when the extra coordinates are averaged out. For estimating an expectation of the original variables, only those variables need to be retained. The paper gives two examples in which the extra variables create different ways to construct moves.

Hybrid Monte Carlo adds a vector interpreted as momentum. In the version described in the paper, the target for x is differentiable and strictly positive, and the momentum has an independent Gaussian distribution. The gradient of the log target determines how the momentum changes during a proposed path.

p(x, u) = p(x)𝒩(u; 0, Iₙₓ)

Here p(x, u) is the extended target, x is the original state, and u is a momentum vector with the same dimension nₓ as x. The function 𝒩 is the Gaussian density evaluated at u, with zero mean and identity covariance Iₙₓ. The product means the auxiliary density integrates out to 1, leaving p(x). The gradient used in the moves is the vector of derivatives of the logarithm of p with respect to the coordinates of x.

At an iteration the method draws fresh momentum and uses a chosen number L of deterministic leapfrog steps of size ρ. The updates use gradient information to change momentum and momentum to change position. The endpoint supplies the joint proposal for a Metropolis–Hastings decision. The path can carry the chain well beyond a single local random displacement, while the acceptance decision corrects the numerical proposal. For L = 1, the paper obtains a Langevin proposal with a Gaussian random displacement and a gradient-dependent shift.

z = x + ρ[u + ρg(x)/2]

The candidate position is z, the current position is x, u is the newly drawn Gaussian momentum, and ρ is the positive step size. The function g(x) denotes the gradient of the log target. The division by 2 comes from the partial momentum update used to form the position step. Larger steps can reduce acceptance, whereas small steps require more gradient calculations to cover a comparable region. Increasing L can move proposals farther from their start and increases the work involved in generating them. The authors also discuss using different step sizes across coordinates.

Slice sampling uses an auxiliary height u. At a fixed x, one draws a height below the density at x. At the resulting height, one moves among points where the density still reaches that level. High-density points have a greater range of permissible heights, which gives them greater weight when the height is discarded.

p̃(x, u) = 𝟙{0 ≤ u ≤ p(x)}

The quantity p̃(x, u) is the joint density under the curve p, x is the original state, and u is the scalar auxiliary height. The indicator 𝟙 is 1 when the condition inside braces holds and 0 otherwise. Integrating over u gives the length of the interval from 0 to p(x), so the x marginal is p(x). Conditional on x, the height is uniform on that interval. Conditional on u, x is uniform over the set of states whose p values are at least u.

Identifying that horizontal set and drawing from it can be difficult. The paper describes a version for a target proportional to a product of positive functions. A separate height is introduced for each factor, with the height bounded above by the factor at the current x. The permissible x values then satisfy all the height constraints. Integrating out each height restores its factor, so the product recovers the target up to normalization. This construction can replace a difficult joint slice with constraints that are easier to handle when the factorization cooperates.

Moving between spaces of different dimensions

Reversible jump MCMC addresses inference where the number of unknowns can itself vary. A state might contain a count of components and their locations. Adding a component increases the number of coordinates, so a density evaluated at the proposed larger state is expressed relative to a different volume element from the density at the current state. The move must account for that difference as well as the relative target values.

The paper associates a parameter space Xₘ with each structure indexed by m and works on the union of those indexed spaces. A chain state carries the parameters for its current structure. This gives the count or structure its own role in the joint target, and summing or integrating over parameters yields probabilities for the structures themselves. To propose a move between two spaces, the algorithm augments them with auxiliary coordinates so that their dimensions match. It then defines a differentiable invertible mapping between the augmented spaces.

(xₘ, uₘ,ₙ) = Fₙ→ₘ(xₙ, uₙ,ₘ)

The indices n and m identify the current and proposed structures. The vector xₙ is the current parameter value, xₘ is the proposed parameter value, and uₙ,ₘ is the auxiliary input drawn for the forward move. The output uₘ,ₙ supplies the auxiliary value associated with the reverse move. The mapping Fₙ→ₘ takes the full augmented point from the current space to a point in the other augmented space. For a reversible proposal, the inverse mapping recovers the original augmented point from that output.

Aₙ→ₘ = min{1, [p(m, xₘ)/p(n, xₙ)] [q(n | m)/q(m | n)] [qₘ→ₙ(uₘ,ₙ | m, xₘ)/qₙ→ₘ(uₙ,ₘ | n, xₙ)] Jₙ→ₘ}

The symbol Aₙ→ₘ is the acceptance probability, with the minimum capping it at 1. The first ratio compares the joint target density of structure and parameters at the proposed and current states. The second compares the probabilities q of selecting the reverse and forward changes of structure. The third compares the corresponding auxiliary proposal densities qₘ→ₙ and qₙ→ₘ, evaluated at the matched auxiliary values. The Jacobian factor Jₙ→ₘ is the absolute determinant of the derivative of the forward mapping with respect to its augmented input, for continuous coordinates. It accounts for how the transformation changes volume. Thus the forward flow and reverse flow are compared on matching dimensions.

The paper illustrates the mapping by splitting a component at location μ into two components on either side. An auxiliary draw sets the displacement, scaled by a simulation parameter β. The paired merge takes the midpoint of the two locations and has a distance restriction to keep it within the range admitted by the split. The two output locations together carry the position of the original component and the displacement used to split it.

(μ₁, μ₂) = (μ − uβ, μ + uβ)

Here μ is the original location, μ₁ and μ₂ are the proposed locations, u denotes the split’s auxiliary draw, and β sets the scale of the separation. In the paper’s scalar illustration the Jacobian for this split is 2β, and the paired merge has its reciprocal. The acceptance test also depends on the probabilities for choosing which component or pair to act on. Split and merge moves can be mixed with births, deaths, and location updates. The mapping and the choice of components must be designed together so that the reverse move has the probability used in the calculation.

Updating a distribution as observations arrive

Sequential Monte Carlo represents a changing posterior with a set of particles. In this setting, a particle can represent a current state or a trajectory up to the present. Each observation changes the probability assigned to the states. The method extends the particles with proposals, computes weights that reflect the new evidence and the proposal used, and may resample the resulting set. The next observation then starts from this new approximation.

The authors formulate the dynamic and observation distributions so they may depend on the past. In the simpler filtering case, the current state follows the previous state and the new observation depends on the current state. The goal of filtering is the posterior distribution of the current state given observations through the current time. A trajectory posterior is a larger object. It retains uncertainty about the path that led there, and a particle scheme that tracks paths must carry that history.

When proposals extend paths without changing their past coordinates, the proposal uses the previous posterior for those coordinates and an extension rule for the new coordinate. The importance weight is the ratio of the new trajectory posterior to the density of this proposal. If the proposal for the new state is the transition prior and the observation depends on the current state, the transition terms cancel. The result is the bootstrap-filter weight.

wₜ ∝ p(yₜ | x̃ₜ)

Here t indexes the current time, wₜ is the new particle’s weight up to a common normalizer, yₜ is the observation at that time, and x̃ₜ is the proposed current state. The expression p(yₜ | x̃ₜ) is the current observation likelihood. The proportionality sign indicates that the weights for the particle set will be normalized together. Particles whose proposed states make the observation more plausible have a greater chance of being selected as parents during resampling. The total number of particles is kept fixed, even though individual parents can have different numbers of descendants.

A proposal can also use the current observation to guide an extension. The authors discuss the conditional distribution of the current state given the past trajectory and the observations through the current time. Using that proposal cancels the corresponding conditional term in the weight, although different past trajectories can still respond differently to the new observation. The bootstrap choice is attractive when that observation-conditioned proposal is hard to evaluate or draw from. It moves the effect of the current observation into the weights.

An MCMC kernel that preserves the current posterior can then move each particle. If the particle distribution already matches that posterior, the extra transition preserves the match. The authors also explain that total variation distance to the invariant target can only decrease under such a transition. A move within a particle update has a narrower task than a standalone sampler started arbitrarily far from equilibrium. It can improve the placement of particles without having to be capable, on its own, of reaching the entire state space.

Experiments and results

A finite chain with an equilibrium to compare against

The paper first works through a finite chain whose transitions can be inspected directly. From the first state, the chain always moves to the second. From the second, it can stay there with probability 0.1 or move to the third with probability 0.9. From the third, it moves to the first with probability 0.6 or to the second with probability 0.4. These are conditional probabilities for one transition from the stated origin. The self-transition at the second state allows a return without enforcing a fixed cycle length, and directed paths connect all the states.

The calculation begins with state probabilities of (0.5, 0.2, 0.3), ordered by state. After applying the transition matrix once, the paper reports (0.2, 0.6, 0.2). With repeated application it reports an invariant distribution of (0.2, 0.4, 0.4), at the precision displayed. The successive distributions are obtained by propagation of the probabilities. This is a calculation with a specified starting distribution and a known transition matrix. It allows a reader to compare the chance of occupying a state at a given stage with its equilibrium probability.

Occupancy probability of the third state in the finite-chain example

The third state has more probability at equilibrium than at initialization or after the first transition.

Occupancy probability of the third state in the finite-chain exampleInitial distribution: 0.3Initial distribution0.3Distribution after one transition: 0.2Distribution after one transition0.2Invariant distribution (this paper): 0.4Invariant distribution (this paper)0.4
The numbers
System or settingprobability
Initial distribution0.3
Distribution after one transition0.2
Invariant distribution (this paper)0.4

The starred value is the equilibrium reference. The direction in the chart describes the amount of probability assigned to this particular state. The chart does not measure sampler quality or imply that a good fit is achieved by increasing that probability. Indeed, the one-step probability falls below its initial value before the chain settles. The comparison shows how a distribution can change during early moves even when the transition rule already preserves the intended equilibrium.

Sampling a target with two peaks

The main continuous example fixes a synthetic target so the authors can compare the samples with a known density. It is a mixture of two bell-shaped terms.

p(x) ∝ 0.3 exp(−0.2x²) + 0.7 exp(−0.2(x − 10)²)

Here x is the scalar state, p(x) is its target density up to a common normalizer, and exp is the exponential function. The values 0.3 and 0.7 multiply the two terms. The coefficient −0.2 controls their quadratic exponents. The second term is shifted by 10 along the state axis, and the first is centered at 0. Because the target shape is specified directly, the relevant comparison is with its density curve. The example has no observations to fit or held-out split on which to score predictions.

The proposal is Gaussian with mean equal to the current state and variance 100. The authors show histograms of the chain at 500 and 5000 iterations against the same target. The numbers identify how many iterations had been run at the displayed stages. The longer run gives a histogram that resembles the intended mixture. The display lets the reader assess whether the chain visited both regions and whether their relative occupancy broadly follows the reference curve.

A histogram summarizes where the recorded values occurred. It suppresses the order of visits, so two traces can yield similar histograms even if one moves regularly between peaks and another spends long periods at a time in each region. The paper connects the visual fit of the histogram with the design of the proposal, using additional plots to show how alternative scales change exploration. It does not reduce the fit to a scalar error score or report a sampling error across replications. The numerical settings and checkpoints describe the demonstration, and the density comparison supplies its outcome.

Applying cooling to the same target

The annealing example starts from the same objective as the bimodal sampling example. The authors show its behavior at stages labeled 500 and 5000 iterations. The plots illustrate the search for modes under the progressively sharpened distribution. In the sampling experiment, the density is a reference for how frequently different neighborhoods should be visited. In the annealing experiment, cooling shifts the desired occupancy towards the peaks, ultimately favoring the global maximum under the stated convergence conditions. A histogram that concentrates near high objective values has a different interpretation in that experiment.

There is no independent test set for this comparison. The objective itself supplies the reference because its shape is known. The illustrated checkpoints show behavior during this run, with no reported aggregate measure of the probability of finding the global maximum across runs. Their role is to connect the change of target with a visible change of behavior. The convergence argument supplies the conditions under which a sequence of such targets and transitions supports a claim about global optimization.

What the ablations show

The paper has no formal ablation suite. Its controlled proposal-scale illustrations and analytical comparisons address several of the questions an ablation would ordinarily test, especially which part of a sampling design is responsible for poor exploration.

The most direct comparison changes the variance of a Gaussian proposal while retaining the Metropolis–Hastings construction. With a narrowly concentrated proposal, a chain can keep making locally reasonable moves and fail to visit a second peak. In such a run, frequent acceptances would reflect the compatibility of the trial points with the current neighborhood. The histogram can still give a poor account of the full target, because the region never reached contributes no samples. A wide proposal produces a different failure. It frequently proposes points the chain seldom accepts, leaving long stretches of repeated states. Those stretches reveal strong dependence between successive recorded values.

The useful middle ground is expressed by the authors as mixing. The chain needs enough accepted movement to explore within a region and enough mobility to move between regions. The comparison isolates the proposal scale as a reason why runs with the same invariant target can behave differently. It also explains why the acceptance rate has to be read alongside evidence of movement. The wide proposal and the narrow proposal can both give poor coverage through distinct mechanisms, with one constrained by rejection and the other by the limited distance of its trial moves.

The discussion of blocks gives a related analytical contrast. Updating a strongly dependent set of variables coordinate by coordinate can confine the chain to small changes, because changing just one coordinate may move away from the combinations of values that are plausible together. A well-designed block can move those variables in concert. A proposal that updates all coordinates can encounter low acceptance if it changes too much at once. The authors use this tradeoff to explain the value of intermediate groupings and of conditioning on the latest values in a cycle. The paper gives the mechanism and examples of the approach, rather than measured gains for a particular blocking scheme.

The importance-sampling calculation isolates another source of efficiency. When the desired quantity is a particular expectation, the variance bound identifies a proposal tilted toward large absolute contributions to that expectation. For a rare event, the calculation explains why a simulator can do better by putting its draws where the event may occur than by using direct target draws throughout the space. When the aim is broad coverage of the distribution, the same specialization can leave other questions poorly served. The comparison is therefore between estimators for a specified quantity, under the proposal assumptions of the derivation.

The paper also analyzes why repeated adaptation can undermine an otherwise correct transition. A fixed schedule that cycles through target-preserving kernels maintains invariance at each step. A history-dependent policy can select its next kernel using information beyond the current state. The authors cite an example in which this selection changes the stationary behavior even though each kernel individually has the desired invariant distribution. This comparison exposes the assumption behind the mixture and cycle construction. Knowing that every possible kernel preserves p is useful, but the mechanism that chooses among them is also part of the transition law.

Limitations

Limits the authors identify

The authors emphasize the difficulty of deciding when a chain has run long enough. Discarding early iterations, or burn-in, can reduce the influence of initialization. Graphical and statistical diagnostics can help assess whether the observed chain appears stable. The paper treats those diagnostics as approximate. A trace that has settled into a consistent pattern within one region may still be missing another region. How long to run the chain depends on access to regions that a finite trace may reveal only weakly.

The paper describes mixing time as the number of transitions needed to get close to the target and remain close. One measure of closeness is total variation distance. In density notation, the authors express it through the accumulated absolute discrepancy between the distribution after t steps and the invariant distribution.

Δₓ(t) = (1/2) ∫ᵧ∈𝒳 |K⁽ᵗ⁾(y | x) − p(y)| dy

Here Δₓ(t) is the total variation distance at step t from starting state x. The expression K⁽ᵗ⁾(y | x) describes the distribution at y after t applications of K beginning at x. The function p(y) is the target, 𝒳 is the state space, dy is the integration element, and the bars denote absolute value. The factor 1/2 is the convention used in the paper’s distance. On a finite space the integral is replaced by a sum.

τₓ(ε) = min{t : Δₓ(t′) ≤ ε for every t′ ≥ t}

The quantity τₓ(ε) is the mixing time from x for tolerance ε. The minimum is over step counts t for which the distance stays within ε at every later count t′. This is a statement about distributions generated by the chain. Seeing an apparently stable path gives indirect evidence about it.

For finite reversible chains the paper explains how eigenvalues of the transition operator give a geometric bound. The eigenvalue associated with the invariant distribution is 1. The convergence rate in the bound depends on the largest magnitude among the other eigenvalues, so an eigenvalue near either end of the admissible range can matter. The authors discuss conductance as a way to reason about slow movement. A set with appreciable probability and little outward flow can keep the chain in one part of the space for a long time. Such bounds have led to polynomial-time results for particular problems discussed in the paper. The authors stress the distance between those results and the practical work of designing a fast sampler for a new high-dimensional target.

The review also distinguishes convergence in the limit from perfect sampling, which produces an independent target draw under specific restrictions. The authors discuss coupling from the past and Fill’s algorithm in this connection. They describe practical restrictions and computational costs that limit the use of such methods. For ordinary MCMC, the available evidence about convergence often comes from the combination of what is known about the transition and what is observed in finite runs.

Adaptive tuning has its own limits. The simplest remedy described by the paper is to adapt for a fixed initial period and then hold the proposal fixed. The authors also discuss continuous adaptation based on constructions such as regeneration and judge the available methods to have efficiency limitations. Other bottlenecks concern the structure of a given problem. Hybrid Monte Carlo requires choices about the number and size of gradient steps. Slice sampling can be difficult when the region at a sampled height is hard to identify. Reversible jump requires designing useful forward and reverse mappings, a task the authors describe as laborious.

The authors also identify an unresolved choice in hybrid exact and stochastic inference. When some unknowns can be integrated out analytically conditional on others, Rao–Blackwellisation lets the simulation focus on the remaining unknowns. For example, averaging conditional distributions over sampled values can stand in for drawing all variables jointly. This can reduce the dimension that needs to be explored. Automatically finding which variables should be sampled and which should be handled analytically remains open in the paper’s account. The review also explicitly leaves out fuller treatments of tempering and coupling.

Limits of the evidence in the demonstrations

The finite-chain example gives the transition probabilities, so its behavior can be studied directly. The Gaussian proposal example gives a target curve against which a histogram can be judged. These are favorable conditions for seeing the mechanism. In an inference problem where the target is known only up to a multiplier and its relevant regions are hard to locate, the same sort of visual agreement may be impossible to inspect. The illustrations establish what good and poor exploration can look like on the chosen examples. They provide no numerical rule for selecting a proposal scale on an unfamiliar target.

The experiments also leave the per-iteration costs of different algorithm families incomparable. A random walk requires a trial and an acceptance test. A gradient-guided proposal may perform several expensive computations before its test, and a reversible jump move may require a problem-specific mapping. An iteration count on the synthetic bimodal task cannot tell a reader which method will estimate a different expectation with the least computational work. A comparison of that kind would require a specified target, a quantity to estimate, a criterion for estimation error, and a way to account for the work of generating samples.

Finally, an unknown normalizing constant cancels in Metropolis–Hastings, so sampling can proceed without it. This is a valuable answer to the problem of drawing from a posterior. It leaves a distinct question when the normalizing constant is itself the quantity of interest, as in the partition-function motivation. The acceptance formula gives no direct estimate of that constant. Likewise, the variance calculation for independent samples does not give the uncertainty of averages along a dependent chain. The demonstrations show why an invariant distribution is a necessary foundation for the method and why further analysis is needed to say how much information a particular run provides.

What came after

Sampling with information beyond a local decision

The most direct continuation in the citing work is the use of Gibbs sampling for information extraction. Finkel and colleagues address the incorporation of non-local information into an extraction system. The connection is the full conditional: a sampling update can reconsider a single part of a structured state while taking the rest of that state into account. In the review, that is the distinction between the small part of the state a step changes and the potentially broader information that determines its conditional distribution. The later work names both the extraction problem and the sampling mechanism used to bring non-local information into it. Incorporating Non-local Information into Information Extraction Systems by Gibbs Sampling

Mausam and colleagues apply probabilistic inference to assembling a multilingual dictionary. The link to the review lies in the kind of calculation being asked of an inference procedure. Information relevant to a candidate dictionary entry can contribute through a larger set of possibilities, and the computational objective is to turn uncertain evidence into an inference about entries. The title identifies probabilistic inference as the means of compiling the dictionary. It leaves the particular sampling updates unspecified, so the connection is to the review’s account of inference over many possibilities. Compiling a Massive, Multilingual Dictionary via Probabilistic Inference

Search in programs and at inference time

Stochastic superoptimization places random search in the setting of program optimization. This connects to the review’s distinction between estimating features of a distribution and seeking high-scoring candidates from a large feasible set. A program search needs trial changes that can generate useful alternatives, just as the optimization discussion in the review needs proposals that can travel between promising regions. The later work identifies stochastic optimization as its approach. The citation supports the connection at that level, without establishing that the program search uses the review’s particular cooling schedule or dimension-changing moves. Stochastic Superoptimization

Snell and colleagues examine how to scale computation at test time and compare the benefit with increasing the parameter count. Their title makes a conditional claim about the relative effectiveness of those choices. The point of contact is where to spend computation during inference. In the review, the design choices include how often to generate a proposal, how much work to invest in a move, and how to use the results of a finite run. The later paper addresses a different inference setting and puts the allocation of computation itself at the center of the question. Scaling LLM Test-Time Compute Optimally

Wu and colleagues study agents whose tool documentation changes continually. The connection to the review is adaptation during operation. The review asks what happens if information obtained during a run is used to modify the mechanism that will generate subsequent states. The later work applies continual adaptation to documentation that guides tool use. Its stated object of adaptation is therefore different from a proposal distribution in a Markov chain. The two settings share a design question about how adjustments made during a run affect later behavior. The convergence conditions in the review concern the sampling setting, where there is an explicit target distribution to preserve. Beyond Static Toolsets

Cite

Cite as Christophe Andrieu, Nando de Freitas, Arnaud Doucet B and Michael I. Jordan. 2003. An Introduction to MCMC for Machine Learning. Machine Learning.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.1023/a:1020281327116

@inproceedings{andrieu2003introduction,
  title = {{An Introduction to MCMC for Machine Learning}},
  author = {Christophe Andrieu, Nando {de Freitas}, Arnaud Doucet B and Michael I. Jordan},
  booktitle = {Machine Learning},
  year = {2003},
  doi = {10.1023/a:1020281327116},
  url = {https://doi.org/10.1023/a:1020281327116}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/andrieu-2003-introduction-mcmc-machine-learning/