Gibbs sampling and Metropolis–Hastings
Two Markov chains whose stationary distribution is the posterior we want: Metropolis–Hastings with its proposal, acceptance probability and repeated state on rejection, and Gibbs sampling, where every update is accepted with probability 1. A Gibbs sweep on a normal model with unknown mean and precision, the trap of simultaneous updates, blocked and collapsed Gibbs.
A posterior we cannot normalize
The topic Monte Carlo and Markov chains gave us two tools. A Monte Carlo average turns an expectation into a sum over samples. A Markov chain whose stationary distribution is produces such samples, once we discard the burn-in and account for autocorrelation. What that topic did not say is how to build a chain whose stationary distribution is our posterior. This topic gives two recipes: Metropolis–Hastings, which works for almost any posterior, and Gibbs sampling, which needs no tuning when the conditionals are standard distributions.
The obstacle is always the same. In
we can evaluate the numerator at any , but the evidence is an integral. Call the numerator the unnormalized posterior:
The running example is the coin from the topic The Bayesian approach: three flips, three heads. There a Beta prior made the posterior a one-liner. Now put the prior on the log-odds instead, as logistic regression does: is the probability of heads and . The likelihood of three heads is , so
No conjugate family covers this, and has no closed form. Numerical integration in one dimension still works, and it says ; we will use it to check the samplers. In twenty dimensions a grid would be hopeless.
The way out is that some quantities do not need at all. Both algorithms below are built only from those.
A note on letters. The chain's state is written and the target with an unknown ; for a posterior, and . The data stay .
One Metropolis–Hastings step
Metropolis–Hastings needs a proposal : any distribution we can sample from and evaluate. One step from the current state :
- Propose a candidate .
- Compute the acceptance probability
- Draw . If , the next state is . Otherwise the chain stays put, and the next state is again: the repeat is recorded as a sample.
Only a ratio of appears, so cancels and the evidence is never needed.
The simplest proposal is a random walk: with and a step size . It is symmetric, , and the proposal factors cancel. This special case is the original Metropolis algorithm:
A move uphill is always accepted. A move downhill is accepted with probability equal to the density ratio. That second rule is what separates sampling from optimization: the chain does visit lower-density regions, just less often.
Two steps on the coin with . Work in logs: with many data points underflows, while its logarithm is a harmless sum. The chain starts at and proposes :
The ratio exceeds , so and the chain moves. From it proposes :
Now . The data like a little more, but the prior likes it much less. Say : the proposal is rejected and the chain reads .
Detailed balance and the repeated state
Why does this chain have as its stationary distribution? By detailed balance, from the topic Monte Carlo and Markov chains. For the chain moves with density , and
The right-hand side is symmetric in and , so it also equals : the flow from to matches the flow back. The rest of the probability, the rejections, stays at . It is a point mass on the diagonal of the kernel, where balance holds trivially. Hence is stationary. Dividing both sides by changes nothing, which is the formal reason the evidence is not needed.
Several consequences are worth stating plainly.
The repeat is part of the sample. Rejections happen most often at high-density states, where almost every proposal leads downhill. Repeating such a state is how the chain gives it the right weight. A run on the coin, steps with and the first discarded, accepts of proposals and gives and a standard deviation of ; numerical integration gives and . Keep only the accepted moves, and the standard deviation becomes : the centre is under-weighted.
Impossible candidates are always rejected. If , the ratio is zero. If the proposal can go to but never come back, , the ratio is zero too.
Stationarity is not convergence. It also needs irreducibility and aperiodicity. The Gaussian walk on the coin can reach any interval in a single step, which gives both. A proposal that can only move right would not.
Burn-in does not make draws independent. Each state is built from the previous one, so the draws stay autocorrelated, and the honest sample size is the ESS.
The step size is a trade-off. On the coin:
| step | accepted | lag-1 autocorrelation of |
|---|---|---|
A tiny step accepts almost everything and goes nowhere. A huge step proposes absurd values and repeats the state. A high acceptance rate is not a goal in itself; common rules of thumb aim for a quarter to a half of proposals accepted.
This also explains the grid chain from the topic Monte Carlo and Markov chains, with states and . It is Metropolis with a neighbour proposal: step left or right with probability each, a step off the grid counts as a rejection, and a step from to is accepted with probability . From the chain moves up with probability and down with probability ; from it moves down with probability . These are exactly the entries of that topic's matrix, and only ratios of were needed.
Asymmetric proposals
A random walk is symmetric. Many useful proposals are not, and then the factor , the Hastings correction, is mandatory. Without it the chain drifts to wherever the proposal prefers to go.
The clearest case is an independence proposal , which ignores the current state, like the proposal in importance sampling. The ratio becomes
These are exactly the importance weights from the topic Monte Carlo and Markov chains. A candidate with a larger weight than the current state is always accepted; one with a smaller weight is accepted with probability equal to the weight ratio. Drop the correction, and detailed balance holds for a density proportional to instead of : the proposal's preferences leak into the answer.
An independence proposal works when is close to the posterior, for example the Gaussian from the topic The Laplace approximation and Bayesian classification, with somewhat heavier tails. It fails when misses part of the posterior, for the same reason importance sampling fails.
Asymmetry also appears quietly. A random walk on for a positive parameter , such as a precision, is symmetric in but not in . Proposal densities must be written in the variable the target is written in, and the check below makes you do exactly that.
A Gibbs sweep
Metropolis–Hastings needs a proposal and a step size. Gibbs sampling needs neither, at a price: the parameters are split into blocks , and each complete conditional must be a distribution we can sample directly. Here means all blocks except . A sweep updates the blocks in turn, always conditioning on the newest values:
A complete conditional is the joint with the other blocks frozen: . Keep the factors that contain , drop the rest, and recognize the distribution.
Example: four measurements from with unknown mean and precision . The priors are independent: and in the shape–rate form. With a Normal–Gamma prior, where the prior variance of scales with , the posterior would be closed-form (see the topic Conjugate priors and the exponential family). With independent priors it is not a standard distribution. But each conditional is a conjugate update from that topic.
Given , this is the Normal mean with known variance, and precisions add:
Given , the Gamma prior on a precision is conjugate:
One sweep, starting from . Here and , so . Say the draw is . The residuals are with squares summing to , so with mean . Say . The next sweep draws from : with less trust in the data, is pulled harder towards the prior mean , and its conditional is wider.
A long run, sweeps with the first discarded, gives with standard deviation and . A two-dimensional grid gives , and . The posterior mean sits well below because the prior is confident compared with four points.
Gibbs as Metropolis–Hastings with acceptance 1
Why does Gibbs sample the right thing? Because each update is a Metropolis–Hastings step whose proposal is the complete conditional. To update block from state , propose with and . Write (dropping for brevity), and the MH ratio is
So : nothing is ever rejected and there is no step size to tune. What follows from this, and what does not:
- Each single update satisfies detailed balance and leaves invariant, so a sweep, their composition, leaves invariant too. A fixed-order sweep is usually not reversible; a sweep in random order is.
- "No rejections" is not "no repeats". A discrete block, such as a cluster label, can redraw its current value. That is a genuine draw.
- Invariance is not convergence. Take the uniform distribution on two unit squares, and , touching at a corner. Every conditional is a proper uniform distribution, yet from the first square the chain never reaches the second: in sweeps it visits it zero times and looks perfectly converged. The positivity condition, a joint density positive wherever the product of its marginals is, rules this out.
- Strongly correlated blocks make Gibbs crawl. For a bivariate normal with unit variances and correlation , the conditional is narrow when is near , so each move is short. The autocorrelation of between sweeps is : at .
- Conditionally independent blocks can be updated in parallel. In a mixture, all labels given the parameters are independent of each other, so they can be drawn at once.
The phrase "newest values" in the sweep is not a detail. Drawing every block from conditionals on the old state is a different algorithm, and generally a wrong one. The second check shows how wrong.
Blocked and collapsed Gibbs
Two standard repairs for slow mixing change what the blocks are.
Blocking draws strongly coupled variables together from their joint conditional. For the bivariate normal, one joint draw of is an exact independent sample, and the autocorrelation is gone. Blocking helps only while the joint conditional stays easy to sample.
Collapsing integrates some variables out analytically and runs Gibbs on the rest. Take the two-component Gaussian mixture from the topic EM and Bayesian PCA, on seven points
To keep the arithmetic short, fix the component means at and with unit variances. The unknowns are the labels and the weight , with the prior . The plain sampler alternates two conjugate draws: , and then every label from , where and .
The collapsed sampler integrates out. The prior probability of a label given all the other labels is then the Beta–Bernoulli posterior predictive, the same rule that gave for the coin:
where counts the other points currently in component . The denominator is the same for both and drops out when we normalize. For example, redraw the label of while the three points to its left are in component 1 and the three to its right in component 2. With both count factors are , and the decision rests on the densities: against , so . When the counts differ, the bigger component attracts the point.
Integrating the means out too would replace by a predictive density with a wider variance, and the same collapsed sampler returns in the topics Dirichlet processes and Latent Dirichlet allocation.
Every model so far has had a fixed number of parameters: one coin bias, a mean and a precision, two mixture components. What if the unknown should grow with the data, all the way to a whole function? That is the next topic, Gaussian processes, and for regression with Gaussian noise its posterior is exact again.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- Metropolis–Hastings on a 1D Gaussianoptional
Run T MH steps with a Normal proposal; estimate acceptance rate and mean.
~25 min · easier on a computer · The matching course topic has been read.
Self-check in the notebook — not part of mastery or the certificate.
Answers are saved on the server and tied to this browser until you sign in.