Skip to content
BIASED

Gibbs sampling and Metropolis–Hastings

Block 1 of 7~2 min

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.

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

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.