Skip to content
BIASED

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 pp 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

p(θ∣X)=p(X∣θ) p(θ)p(X)p(\theta \mid X) = \frac{p(X \mid \theta)\, p(\theta)}{p(X)}

we can evaluate the numerator at any θ\theta, but the evidence p(X)p(X) is an integral. Call the numerator the unnormalized posterior:

p~(θ)=p(X∣θ) p(θ).\tilde p(\theta) = p(X \mid \theta)\, p(\theta).

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: f=σ(ϕ)f = \sigma(\phi) is the probability of heads and ϕ∼N(0,1)\phi \sim \mathcal N(0, 1). The likelihood of three heads is σ(ϕ)3\sigma(\phi)^3, so

log⁡p~(ϕ)=3log⁡σ(ϕ)−ϕ22+const.\log \tilde p(\phi) = 3 \log \sigma(\phi) - \frac{\phi^2}{2} + \text{const}.

No conjugate family covers this, and ∫σ(ϕ)3 N(ϕ∣0,1) dϕ\int \sigma(\phi)^3\, \mathcal N(\phi \mid 0, 1)\, d\phi has no closed form. Numerical integration in one dimension still works, and it says E[f∣X]≈0.692\mathbb E[f \mid X] \approx 0.692; 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 p(X)p(X) at all. Both algorithms below are built only from those.

A note on letters. The chain's state is written xx and the target p(x)=p~(x)/Zp(x) = \tilde p(x) / Z with an unknown ZZ; for a posterior, x=θx = \theta and Z=p(X)Z = p(X). The data stay XX.

One Metropolis–Hastings step

Metropolis–Hastings needs a proposal r(y∣x)r(y \mid x): any distribution we can sample from and evaluate. One step from the current state xx:

  1. Propose a candidate y∼r(⋅∣x)y \sim r(\cdot \mid x).
  2. Compute the acceptance probability
A(x,y)=min⁡(1, p~(y) r(x∣y)p~(x) r(y∣x)).A(x, y) = \min\left(1,\ \frac{\tilde p(y)\, r(x \mid y)}{\tilde p(x)\, r(y \mid x)}\right).
  1. Draw u∼U(0,1)u \sim U(0, 1). If u≤A(x,y)u \le A(x, y), the next state is yy. Otherwise the chain stays put, and the next state is xx again: the repeat is recorded as a sample.

Only a ratio of p~\tilde p appears, so ZZ cancels and the evidence is never needed.

The simplest proposal is a random walk: y=x+sεy = x + s\varepsilon with ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1) and a step size ss. It is symmetric, r(y∣x)=r(x∣y)r(y \mid x) = r(x \mid y), and the proposal factors cancel. This special case is the original Metropolis algorithm:

A(x,y)=min⁡(1, p~(y)p~(x)).A(x, y) = \min\left(1,\ \frac{\tilde p(y)}{\tilde p(x)}\right).

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 s=1.5s = 1.5. Work in logs: with many data points p~\tilde p underflows, while its logarithm is a harmless sum. The chain starts at ϕ=0\phi = 0 and proposes ϕ′=1\phi' = 1:

log⁡p~(1)p~(0)=3 [log⁡σ(1)−log⁡σ(0)]−12−022=1.140−0.5=0.640.\log \frac{\tilde p(1)}{\tilde p(0)} = 3\,[\log \sigma(1) - \log \sigma(0)] - \frac{1^2 - 0^2}{2} = 1.140 - 0.5 = 0.640.

The ratio exceeds 11, so A=1A = 1 and the chain moves. From ϕ=1\phi = 1 it proposes ϕ′=2\phi' = 2:

log⁡p~(2)p~(1)=3 [log⁡σ(2)−log⁡σ(1)]−4−12=0.559−1.5=−0.941.\log \frac{\tilde p(2)}{\tilde p(1)} = 3\,[\log \sigma(2) - \log \sigma(1)] - \frac{4 - 1}{2} = 0.559 - 1.5 = -0.941.

Now A=e−0.941=0.390A = e^{-0.941} = 0.390. The data like ϕ=2\phi = 2 a little more, but the prior likes it much less. Say u=0.62u = 0.62: the proposal is rejected and the chain reads 0,1,10, 1, 1.

Detailed balance and the repeated state

Why does this chain have pp as its stationary distribution? By detailed balance, from the topic Monte Carlo and Markov chains. For y≠xy \ne x the chain moves with density r(y∣x) A(x,y)r(y \mid x)\, A(x, y), and

p(x) r(y∣x) A(x,y)=min⁡(p(x) r(y∣x), p(y) r(x∣y)).p(x)\, r(y \mid x)\, A(x, y) = \min\big(p(x)\, r(y \mid x),\ p(y)\, r(x \mid y)\big).

The right-hand side is symmetric in xx and yy, so it also equals p(y) r(x∣y) A(y,x)p(y)\, r(x \mid y)\, A(y, x): the flow from xx to yy matches the flow back. The rest of the probability, the rejections, stays at xx. It is a point mass on the diagonal of the kernel, where balance holds trivially. Hence pp is stationary. Dividing both sides by ZZ 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, 200,000200{,}000 steps with s=1.5s = 1.5 and the first 2,0002{,}000 discarded, accepts 52%52\% of proposals and gives E[f∣X]≈0.693\mathbb E[f \mid X] \approx 0.693 and a standard deviation of 0.1520.152; numerical integration gives 0.6920.692 and 0.1530.153. Keep only the accepted moves, and the standard deviation becomes 0.1580.158: the centre is under-weighted.

Impossible candidates are always rejected. If p~(y)=0\tilde p(y) = 0, the ratio is zero. If the proposal can go to yy but never come back, r(x∣y)=0r(x \mid y) = 0, 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 ss accepted lag-1 autocorrelation of ϕ\phi
0.10.1 96%96\% 0.990.99
1.51.5 52%52\% 0.650.65
1010 10%10\% 0.870.87

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 θ∈{0.25,0.5,0.75}\theta \in \{0.25, 0.5, 0.75\} and π∝θ3=(1,8,27)/36\pi \propto \theta^3 = (1, 8, 27)/36. It is Metropolis with a neighbour proposal: step left or right with probability 12\tfrac12 each, a step off the grid counts as a rejection, and a step from ii to jj is accepted with probability min⁡(1,πj/πi)\min(1, \pi_j / \pi_i). From 0.50.5 the chain moves up with probability 12⋅1=12\tfrac12 \cdot 1 = \tfrac12 and down with probability 12⋅18=116\tfrac12 \cdot \tfrac18 = \tfrac1{16}; from 0.750.75 it moves down with probability 12⋅827=427\tfrac12 \cdot \tfrac{8}{27} = \tfrac{4}{27}. These are exactly the entries of that topic's matrix, and only ratios of π\pi were needed.

Asymmetric proposals

A random walk is symmetric. Many useful proposals are not, and then the factor r(x∣y)/r(y∣x)r(x \mid y) / r(y \mid x), the Hastings correction, is mandatory. Without it the chain drifts to wherever the proposal prefers to go.

The clearest case is an independence proposal r(y∣x)=g(y)r(y \mid x) = g(y), which ignores the current state, like the proposal in importance sampling. The ratio becomes

p~(y) g(x)p~(x) g(y)=w(y)w(x),w(x)=p~(x)g(x).\frac{\tilde p(y)\, g(x)}{\tilde p(x)\, g(y)} = \frac{w(y)}{w(x)}, \qquad w(x) = \frac{\tilde p(x)}{g(x)}.

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 p~(x) g(x)\tilde p(x)\, g(x) instead of p~(x)\tilde p(x): the proposal's preferences leak into the answer.

An independence proposal works when gg 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 gg misses part of the posterior, for the same reason importance sampling fails.

Asymmetry also appears quietly. A random walk on log⁡t\log t for a positive parameter tt, such as a precision, is symmetric in log⁡t\log t but not in tt. 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 z=(z1,…,zm)z = (z_1, \dots, z_m), and each complete conditional p(zj∣z−j,X)p(z_j \mid z_{-j}, X) must be a distribution we can sample directly. Here z−jz_{-j} means all blocks except zjz_j. A sweep updates the blocks in turn, always conditioning on the newest values:

z1(t+1)∼p(z1∣z2(t),…,zm(t),X),z2(t+1)∼p(z2∣z1(t+1),z3(t),…,zm(t),X),  ⋮zm(t+1)∼p(zm∣z1(t+1),…,zm−1(t+1),X).\begin{aligned} z_1^{(t+1)} &\sim p\big(z_1 \mid z_2^{(t)}, \dots, z_m^{(t)}, X\big), \\ z_2^{(t+1)} &\sim p\big(z_2 \mid z_1^{(t+1)}, z_3^{(t)}, \dots, z_m^{(t)}, X\big), \\ &\ \ \vdots \\ z_m^{(t+1)} &\sim p\big(z_m \mid z_1^{(t+1)}, \dots, z_{m-1}^{(t+1)}, X\big). \end{aligned}

A complete conditional is the joint with the other blocks frozen: log⁡p(zj∣z−j,X)=log⁡p(X,z)+const\log p(z_j \mid z_{-j}, X) = \log p(X, z) + \text{const}. Keep the factors that contain zjz_j, drop the rest, and recognize the distribution.

Example: four measurements X=(2,3,3,4)X = (2, 3, 3, 4) from N(μ,λ−1)\mathcal N(\mu, \lambda^{-1}) with unknown mean μ\mu and precision λ\lambda. The priors are independent: μ∼N(0,1)\mu \sim \mathcal N(0, 1) and λ∼Gamma⁡(2,2)\lambda \sim \operatorname{Gamma}(2, 2) in the shape–rate form. With a Normal–Gamma prior, where the prior variance of μ\mu scales with 1/λ1/\lambda, 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 λ\lambda, this is the Normal mean with known variance, and precisions add:

μ∣λ,X∼N(λ∑ixi1+nλ, 11+nλ).\mu \mid \lambda, X \sim \mathcal N\left(\frac{\lambda \sum_i x_i}{1 + n\lambda},\ \frac{1}{1 + n\lambda}\right).

Given μ\mu, the Gamma prior on a precision is conjugate:

λ∣μ,X∼Gamma⁡(2+n2, 2+12∑i(xi−μ)2).\lambda \mid \mu, X \sim \operatorname{Gamma}\left(2 + \frac n2,\ 2 + \frac12 \sum_i (x_i - \mu)^2\right).

One sweep, starting from λ(0)=1\lambda^{(0)} = 1. Here n=4n = 4 and ∑ixi=12\sum_i x_i = 12, so μ∼N(12/5, 1/5)=N(2.4, 0.2)\mu \sim \mathcal N(12/5,\ 1/5) = \mathcal N(2.4,\ 0.2). Say the draw is μ(1)=2.0\mu^{(1)} = 2.0. The residuals are 0,1,1,20, 1, 1, 2 with squares summing to 66, so λ∼Gamma⁡(4,5)\lambda \sim \operatorname{Gamma}(4, 5) with mean 0.80.8. Say λ(1)=0.5\lambda^{(1)} = 0.5. The next sweep draws μ\mu from N(6/3, 1/3)=N(2, 1/3)\mathcal N(6/3,\ 1/3) = \mathcal N(2,\ 1/3): with less trust in the data, μ\mu is pulled harder towards the prior mean 00, and its conditional is wider.

A long run, 50,00050{,}000 sweeps with the first 1,0001{,}000 discarded, gives E[μ∣X]≈2.21\mathbb E[\mu \mid X] \approx 2.21 with standard deviation 0.6450.645 and E[λ∣X]≈0.945\mathbb E[\lambda \mid X] \approx 0.945. A two-dimensional grid gives 2.2112.211, 0.6450.645 and 0.9450.945. The posterior mean sits well below xˉ=3\bar x = 3 because the prior N(0,1)\mathcal N(0, 1) 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 jj from state zz, propose z′z' with z−j′=z−jz'_{-j} = z_{-j} and zj′∼p(zj′∣z−j)z'_j \sim p(z'_j \mid z_{-j}). Write p(z)=p(zj∣z−j) p(z−j)p(z) = p(z_j \mid z_{-j})\, p(z_{-j}) (dropping XX for brevity), and the MH ratio is

p(z′) r(z∣z′)p(z) r(z′∣z)=p(zj′∣z−j) p(z−j)⋅p(zj∣z−j)p(zj∣z−j) p(z−j)⋅p(zj′∣z−j)=1.\frac{p(z')\, r(z \mid z')}{p(z)\, r(z' \mid z)} = \frac{p(z'_j \mid z_{-j})\, p(z_{-j}) \cdot p(z_j \mid z_{-j})}{p(z_j \mid z_{-j})\, p(z_{-j}) \cdot p(z'_j \mid z_{-j})} = 1.

So A=1A = 1: 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 pp invariant, so a sweep, their composition, leaves pp 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, [0,1]2[0, 1]^2 and [−1,0]2[-1, 0]^2, touching at a corner. Every conditional is a proper uniform distribution, yet from the first square the chain never reaches the second: in 10,00010{,}000 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 ρ\rho, the conditional z1∣z2∼N(ρz2,1−ρ2)z_1 \mid z_2 \sim \mathcal N(\rho z_2, 1 - \rho^2) is narrow when ∣ρ∣|\rho| is near 11, so each move is short. The autocorrelation of z1z_1 between sweeps is ρ2\rho^2: 0.640.64 at ρ=0.8\rho = 0.8.
  • 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 (z1,z2)(z_1, z_2) is an exact independent sample, and the ρ2\rho^2 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

X=(−0.8, −0.2, 0.3, 0.9, 2.1, 2.8, 3.4).X = (-0.8,\ -0.2,\ 0.3,\ 0.9,\ 2.1,\ 2.8,\ 3.4).

To keep the arithmetic short, fix the component means at μ1=0\mu_1 = 0 and μ2=3\mu_2 = 3 with unit variances. The unknowns are the labels zi∈{1,2}z_i \in \{1, 2\} and the weight π=P(zi=1)\pi = P(z_i = 1), with the prior π∼Beta⁡(α,α)\pi \sim \operatorname{Beta}(\alpha, \alpha). The plain sampler alternates two conjugate draws: π∣z∼Beta⁡(α+n1,α+n2)\pi \mid z \sim \operatorname{Beta}(\alpha + n_1, \alpha + n_2), and then every label from p(zi=k∣π,xi)∝πk N(xi∣μk,1)p(z_i = k \mid \pi, x_i) \propto \pi_k\, \mathcal N(x_i \mid \mu_k, 1), where π1=π\pi_1 = \pi and π2=1−π\pi_2 = 1 - \pi.

The collapsed sampler integrates π\pi out. The prior probability of a label given all the other labels is then the Beta–Bernoulli posterior predictive, the same rule that gave 4/54/5 for the coin:

p(zi=k∣z−i,X)∝nk−i+αn−1+2α N(xi∣μk,1),p(z_i = k \mid z_{-i}, X) \propto \frac{n_k^{-i} + \alpha}{n - 1 + 2\alpha}\ \mathcal N(x_i \mid \mu_k, 1),

where nk−in_k^{-i} counts the other points currently in component kk. The denominator is the same for both kk and drops out when we normalize. For example, redraw the label of x4=0.9x_4 = 0.9 while the three points to its left are in component 1 and the three to its right in component 2. With α=1\alpha = 1 both count factors are 4/84/8, and the decision rests on the densities: N(0.9∣0,1)=0.266\mathcal N(0.9 \mid 0, 1) = 0.266 against N(0.9∣3,1)=0.044\mathcal N(0.9 \mid 3, 1) = 0.044, so p(z4=1)=0.266/0.310≈0.858p(z_4 = 1) = 0.266 / 0.310 \approx 0.858. When the counts differ, the bigger component attracts the point.

Integrating the means out too would replace N(xi∣μk,1)\mathcal N(x_i \mid \mu_k, 1) 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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.