Simple Algorithm
Machine Learning · Descent · 24 min

Approximate Inference

When the posterior is intractable: sampling and variational methods.

Bayes' rule fits on one line, but the number it divides by, the evidence p(D)p(\data), is an integral over every possible parameter value, and beyond a handful of dimensions nobody can compute it. Almost every Bayesian model used in practice is therefore fitted approximately: either by drawing samples whose averages converge to the answer, or by optimizing a simpler distribution to sit as close to the posterior as possible. This lesson builds both toolkits and shows how to tell when they have failed.

What you’ll learn

  • Explain why posterior expectations are intractable in general, and estimate them by Monte Carlo and importance sampling, with their error rates and failure modes.
  • Derive the Metropolis–Hastings acceptance rule from detailed balance, and tune a random-walk sampler by its acceptance rate.
  • Diagnose MCMC output with burn-in, autocorrelation, effective sample size and R^\hat R, and use Gibbs sampling when full conditionals are available.
  • Set up variational inference as maximization of the ELBO, explain why it underestimates uncertainty, and compare it with MCMC.

The integral at the heart of Bayes

The posterior is p(θ∣D)=p(D∣θ) p(θ)/p(D)p(\boldsymbol\theta\mid\data)=p(\data\mid\boldsymbol\theta)\,p(\boldsymbol\theta)/p(\data), and the evidence p(D)=∫p(D∣θ) p(θ) dθp(\data)=\int p(\data\mid\boldsymbol\theta)\,p(\boldsymbol\theta)\,d\boldsymbol\theta is an integral over the whole parameter space. Conjugate models (Bayesian Inference) are the rare cases where it has a closed form. Change one ingredient, say a Gaussian prior with a logistic likelihood, as in Bayesian logistic regression, and it has none.

Almost everything you want from a posterior is an expectation of some function ff: the posterior mean (f=θf=\boldsymbol\theta), the probability that a coefficient is positive (f=1{θj>0}f=\mathbf 1\{\theta_j>0\}), the posterior predictive p(y⋆∣x⋆,D)=E[p(y⋆∣x⋆,θ)∣D]p(y^\star\mid\mathbf x^\star,\data)=\E[p(y^\star\mid\mathbf x^\star,\boldsymbol\theta)\mid\data]. Credible intervals are quantiles, which also follow from samples.

E[f(θ)∣D]=∫f(θ) π~(θ) dθ∫π~(θ) dθ,π~(θ)=p(D∣θ) p(θ)\E\big[f(\boldsymbol\theta)\mid\data\big]=\frac{\int f(\boldsymbol\theta)\,\tilde\pi(\boldsymbol\theta)\,d\boldsymbol\theta}{\int\tilde\pi(\boldsymbol\theta)\,d\boldsymbol\theta},\qquad\tilde\pi(\boldsymbol\theta)=p(\data\mid\boldsymbol\theta)\,p(\boldsymbol\theta)
The unnormalized posterior π~\tilde\pi is easy to evaluate at any single point; only its integral is hard. Every method in this lesson needs π~\tilde\pi alone.
Predict before you look

A brute-force approach evaluates π~\tilde\pi on a grid with 100 points per coordinate. For a model with d=10d=10 parameters, how many evaluations is that? Answer with the power of ten.

Show the answer

20 power of 10

10010=1020100^{10}=10^{20} evaluations: at a billion per second, about 3,000 years. Grids scale exponentially with dimension, so practical methods either sample where the posterior mass is or replace the posterior with something tractable.

StrategyIdeaExact in the limit?Typical cost
Monte Carlo and importance samplingaverage ff over independent drawsyes, as the number of draws growsneeds a good proposal; fails in high dimension
MCMCa Markov chain that wanders through the posterioryes, as the chain runs longermany correlated draws; convergence is hard to certify
Laplace approximationa Gaussian at the posterior mode, with the inverse Hessian as covarianceno (exact only for Gaussian posteriors)one optimization and one Hessian
Variational inferencethe closest member of a simple family, found by optimizationno: biased by the familyan optimization; scales to huge data
Sampling is slow but asymptotically exact; approximation is fast but biased. The rest of the lesson builds both.

Monte Carlo and importance sampling

If you can draw θ1,…,θN\boldsymbol\theta_1,\dots,\boldsymbol\theta_N independently from π\pi, the average f^N=1N∑if(θi)\hat f_N=\frac1N\sum_if(\boldsymbol\theta_i) is unbiased with variance Var⁡π(f)/N\Var_\pi(f)/N. By the central limit theorem its error is about σf/N\sigma_f/\sqrt N, whatever the dimension of θ\boldsymbol\theta: the dimension enters only through σf\sigma_f and through how hard it is to draw the samples. Each extra decimal digit of accuracy costs a hundred times more samples.

Usually you cannot sample π\pi directly. Importance sampling draws from a proposal qq you can sample and reweights: Eπ[f]=Eq[f π/q]\E_\pi[f]=\E_q[f\,\pi/q]. With only π~\tilde\pi available, normalize the weights by their sum,

f^=∑iwif(θi)∑iwi,wi=π~(θi)q(θi),θi∼q,\hat f=\frac{\sum_iw_if(\boldsymbol\theta_i)}{\sum_iw_i},\qquad w_i=\frac{\tilde\pi(\boldsymbol\theta_i)}{q(\boldsymbol\theta_i)},\qquad\boldsymbol\theta_i\sim q,

which is consistent (though slightly biased for finite NN). The quantity (∑iwi)2/∑iwi2(\sum_iw_i)^2/\sum_iw_i^2, between 1 and NN, measures how many samples are effectively used.

DerivationWhy importance sampling collapses in high dimension
  1. Eq[w2]=∫π(x)2q(x) dx=s2π∫e−x2(1−12s2)dx=s22s2−1(s2>12)\E_q[w^2]=\int\frac{\pi(x)^2}{q(x)}\,dx=\frac{s}{\sqrt{2\pi}}\int e^{-x^2\left(1-\frac1{2s^2}\right)}dx=\frac{s^2}{\sqrt{2s^2-1}}\qquad(s^2>\tfrac12)

    Take target π=N(0,1)\pi=\mathcal N(0,1) and proposal q=N(0,s2)q=\mathcal N(0,s^2), slightly too wide (s>1s>1). The normalized weight w=π/qw=\pi/q has Eq[w]=1\E_q[w]=1, and its second moment is a Gaussian integral:

  2. Eq[w2]=(s22s2−1)d,ESSN≈(2s2−1s2)d\E_q[w^2]=\Big(\frac{s^2}{\sqrt{2s^2-1}}\Big)^d,\qquad\frac{\text{ESS}}N\approx\Big(\frac{\sqrt{2s^2-1}}{s^2}\Big)^d

    In dd independent coordinates the weights multiply, so their second moments do too. With E[w]=1\E[w]=1, the effective fraction of samples is about 1/Eq[w2]1/\E_q[w^2]:

  3. 1.0502100≈1341.0502^{100}\approx134

    For s=1.2s=1.2 the base is 1.05021.0502: harmless in one dimension, 134134 in a hundred, 1.9×10211.9\times10^{21} in a thousand. A handful of samples carry all the weight. (If qq is narrower than π\pi by a factor 2\sqrt2 or more, s2≤12s^2\le\frac12, the variance is infinite even in one dimension.)

Predict before you look

In that example (s=1.2s=1.2, d=100d=100), you draw 10,00010{,}000 importance samples. About how many effectively count?

Show the answer

74 samples

10,000/134≈7410{,}000/134\approx74. A proposal only 20% too wide in each direction wastes over 99% of the work in 100 dimensions. Importance sampling stays valuable in low dimension and as a building block (sequential Monte Carlo, checking variational fits), but high-dimensional posteriors need samplers that adapt to where the mass is.

Markov chain Monte Carlo

MCMC gives up on independent draws. It builds a Markov chain θ0,θ1,…\boldsymbol\theta_0,\boldsymbol\theta_1,\dots that has the posterior as its stationary distribution: once the chain is distributed according to π\pi, one more step leaves it so. Run long enough, the chain forgets where it started, and averages along it converge to posterior expectations.

The Metropolis–Hastings algorithm (Metropolis et al., 1953; Hastings, 1970) builds such a chain from any proposal q(θ′∣θ)q(\boldsymbol\theta'\mid\boldsymbol\theta):

text
METROPOLIS-HASTINGS(unnormalized target pi~, proposal q, start theta_0, N)
  for t = 0 .. N-1:
      propose  theta' ~ q( . | theta_t)
      a = min(1,  pi~(theta') q(theta_t | theta') / ( pi~(theta_t) q(theta' | theta_t) ))
      with probability a:  theta_{t+1} = theta'          # accept
      otherwise:           theta_{t+1} = theta_t         # reject: record the current point again
  return theta_1 .. theta_N

The normalizer of π\pi cancels in the ratio, so π~\tilde\pi suffices. For a symmetric proposal, such as the random walk θ′=θ+s z\boldsymbol\theta'=\boldsymbol\theta+s\,\mathbf z with z∼N(0,I)\mathbf z\sim\mathcal N(\mathbf 0,I), the qq terms cancel too and a=min⁡(1,π~(θ′)/π~(θ))a=\min(1,\tilde\pi(\boldsymbol\theta')/\tilde\pi(\boldsymbol\theta)): always move uphill, sometimes downhill.

Why does this target π\pi? A transition rule TT satisfies detailed balance if π(θ)T(θ→θ′)=π(θ′)T(θ′→θ)\pi(\boldsymbol\theta)T(\boldsymbol\theta\to\boldsymbol\theta')=\pi(\boldsymbol\theta')T(\boldsymbol\theta'\to\boldsymbol\theta) for all pairs: in equilibrium, the flow from θ\boldsymbol\theta to θ′\boldsymbol\theta' equals the flow back. Summing over θ\boldsymbol\theta shows that π\pi is then stationary. For θ′≠θ\boldsymbol\theta'\ne\boldsymbol\theta the Metropolis–Hastings flow is

π(θ) q(θ′∣θ) a(θ,θ′)=min⁡(π(θ)q(θ′∣θ), π(θ′)q(θ∣θ′)),\pi(\boldsymbol\theta)\,q(\boldsymbol\theta'\mid\boldsymbol\theta)\,a(\boldsymbol\theta,\boldsymbol\theta')=\min\big(\pi(\boldsymbol\theta)q(\boldsymbol\theta'\mid\boldsymbol\theta),\ \pi(\boldsymbol\theta')q(\boldsymbol\theta\mid\boldsymbol\theta')\big),

which is symmetric in θ\boldsymbol\theta and θ′\boldsymbol\theta': detailed balance holds. The full proof, the conditions for convergence and the theory of tuning are in MCMC: Metropolis–Hastings & Gibbs.

Check your understanding

A random-walk Metropolis chain with a very small proposal accepts 99% of its moves. Why is that bad news?

  1. It means the target density is wrong
  2. Consecutive samples are nearly identical, so the chain explores slowly and its averages have huge variance
  3. A high acceptance rate means the chain has not reached stationarity yet
  4. It is good news: almost no computation is wasted on rejections
Show the answer

B. Consecutive samples are nearly identical, so the chain explores slowly and its averages have huge variance

Tiny moves are almost always accepted because π~\tilde\pi barely changes, but each sample is nearly a copy of the last. Autocorrelation is high and the effective sample size is tiny. Too-large proposals fail the other way, by rejecting nearly everything.

Is the chain any good?

MCMC output needs three checks.

  • Burn-in (warm-up). Early samples still remember the starting point. Discard them, and use the warm-up to adapt tuning parameters such as the step size.
  • Autocorrelation. Successive samples are correlated, so NN samples are worth fewer independent ones. If ρk\rho_k is the autocorrelation at lag kk, the effective sample size is ESS=N/(1+2∑k≥1ρk)\mathrm{ESS}=N/(1+2\sum_{k\ge1}\rho_k), and the Monte Carlo standard error of a mean is sd/ESS\mathrm{sd}/\sqrt{\mathrm{ESS}}.
  • Agreement between chains. Run several chains from dispersed starts and compare. The potential scale reduction factor of Gelman & Rubin (1992) compares the variance between chains with the variance within them; in its common form, with mm chains of length nn, within-chain variance WW and between-chain variance B/nB/n, R^=(n−1nW+Bn)/W\hat R=\sqrt{\big(\tfrac{n-1}nW+\tfrac Bn\big)/W}, which tends to 1 as the chains agree. Vehtari, Gelman, Simpson, Carpenter & Bürkner (2021) improved it with rank normalization and folding, and recommend at least four chains, R^<1.01\hat R<1.01 and a rank-normalized ESS above 400.
Predict before you look

A chain behaves like an AR(1) process with lag-one autocorrelation ρ=0.9\rho=0.9, so ρk=0.9k\rho_k=0.9^k. What is the effective sample size of 10,00010{,}000 samples?

Show the answer

526 samples

1+2∑k≥1ρk=1+2ρ1−ρ=1+ρ1−ρ=191+2\sum_{k\ge1}\rho^k=1+\frac{2\rho}{1-\rho}=\frac{1+\rho}{1-\rho}=19, so ESS=10,000/19≈526\mathrm{ESS}=10{,}000/19\approx526. The chain's averages are as precise as about 526 independent draws, and the standard error is 19≈4.4\sqrt{19}\approx4.4 times larger than the naive one.

Gibbs sampling (Geman & Geman, 1984; Gelfand & Smith, 1990) updates one coordinate (or block) at a time, drawing it from its full conditional distribution given all the others. It is a special case of Metropolis–Hastings whose proposals are always accepted, and it shines when the full conditionals are standard distributions, as in conjugate hierarchical models and the collapsed sampler for topic models (Topic Models & Latent Dirichlet Allocation). Its weakness is strong correlation: moves are parallel to the axes, so a narrow diagonal ridge is climbed in a staircase of tiny steps.

Variational inference: inference as optimization

Variational inference picks a family Q\mathcal Q of tractable distributions, for instance fully factorized Gaussians q(θ)=∏jN(θj∣mj,sj2)q(\boldsymbol\theta)=\prod_j\mathcal N(\theta_j\mid m_j,s_j^2) (the mean-field family), and finds the member closest to the posterior in Kullback–Leibler divergence. The divergence itself contains the unknown p(D)p(\data), but the same decomposition that powers EM removes it:

log⁡p(D)=Eq[log⁡p(D,θ)]−Eq[log⁡q(θ)]⏟ELBO(q)+DKL(q ∥ p(θ∣D)).\log p(\data)=\underbrace{\E_q\big[\log p(\data,\boldsymbol\theta)\big]-\E_q\big[\log q(\boldsymbol\theta)\big]}_{\text{ELBO}(q)}+\KL\big(q\,\|\,p(\boldsymbol\theta\mid\data)\big).

Since log⁡p(D)\log p(\data) does not depend on qq, maximizing the ELBO, which needs only π~\tilde\pi, minimizes the KL divergence to the posterior. Inference becomes optimization, solvable by coordinate ascent or by stochastic gradients on minibatches, which is how variational inference scales to millions of data points and to deep generative models.

Think first The divergence minimized is DKL(q ∥ p)=Eq[log⁡q−log⁡p]\KL(q\,\|\,p)=\E_q[\log q-\log p]. Where is it most expensive for qq to put probability mass, and what does that do to the approximation?

Wherever pp is nearly zero but qq is not, log⁡q−log⁡p\log q-\log p is huge, and qq pays for it in full. So qq hides inside the posterior's bulk: it locks onto one mode of a multimodal posterior and, within a mode, tends to be too narrow. For a Gaussian posterior with correlation 0.9, the best fully factorized approximation gets the means exactly right but its marginal variances are only 1−0.92=0.191-0.9^2=0.19 of the true ones. Variational posteriors are typically overconfident.

PropertyMCMCVariational inference
Targetexact posterior, in the limit of long runsthe closest member of Q\mathcal Q, biased by the family
Outputcorrelated samplesa distribution with known form, easy to evaluate and sample
Speed and scaleslow; each step touches all the datafast; stochastic gradients on minibatches
Uncertaintyfaithful if convergedusually underestimated (mode-seeking divergence)
Knowing it workeddiagnostics (R^\hat R, ESS), never proofthe ELBO rises, but its gap to log⁡p(D)\log p(\data) is unknown
Typical usemoderate models where accuracy mattershuge data, deep latent-variable models, a first fit

Key takeaways

  • Posterior quantities are expectations, E[f(θ)∣D]\E[f(\boldsymbol\theta)\mid\data], under a density known only up to its normalizer; grids are hopeless beyond a few dimensions.
  • Monte Carlo error falls as σf/N\sigma_f/\sqrt N regardless of dimension, but drawing the samples is the hard part. Importance sampling reweights a proposal and collapses in high dimension, where the weights' second moment grows exponentially.
  • Metropolis–Hastings accepts with probability min⁡(1,π~(θ′)q(θ∣θ′)π~(θ)q(θ′∣θ))\min\big(1,\frac{\tilde\pi(\boldsymbol\theta')q(\boldsymbol\theta\mid\boldsymbol\theta')}{\tilde\pi(\boldsymbol\theta)q(\boldsymbol\theta'\mid\boldsymbol\theta)}\big), which enforces detailed balance; tiny proposals crawl, huge ones are rejected, and the effective sample size measures the result.
  • Check MCMC with burn-in, ESS =N/(1+2∑ρk)=N/(1+2\sum\rho_k) and R^\hat R over at least four chains; no diagnostic proves convergence. Gibbs sampling never rejects but crawls along correlated ridges.
  • Variational inference maximizes the ELBO, which minimizes DKL(q ∥ p)\KL(q\,\|\,p): fast and scalable, but biased by the family and usually overconfident.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can Metropolis–Hastings sample a posterior whose normalizing constant p(D)p(\data) is unknown?

  1. It estimates p(D)p(\data) during burn-in
  2. It only ever uses ratios π(θ′)/π(θ)\pi(\boldsymbol\theta')/\pi(\boldsymbol\theta), in which the constant cancels
  3. It assumes the posterior is Gaussian
  4. It replaces the posterior by the likelihood
Show the answer

B. It only ever uses ratios π(θ′)/π(θ)\pi(\boldsymbol\theta')/\pi(\boldsymbol\theta), in which the constant cancels

The acceptance probability involves π(θ′)/π(θ)=π~(θ′)/π~(θ)\pi(\boldsymbol\theta')/\pi(\boldsymbol\theta)=\tilde\pi(\boldsymbol\theta')/\tilde\pi(\boldsymbol\theta), so p(D)p(\data) never needs to be computed.

Question 2

An MCMC run of 5,000 draws has an effective sample size of 250. Compared with 5,000 independent draws, its Monte Carlo standard error for the posterior mean is about:

  1. 20 times larger
  2. the same
  3. 4.5 times larger
  4. 20 times smaller
Show the answer

C. 4.5 times larger

Standard error scales as 1/ESS1/\sqrt{\mathrm{ESS}}, so the ratio is 5000/250=20≈4.5\sqrt{5000/250}=\sqrt{20}\approx4.5.

Question 3

Which statement about Gibbs sampling is true?

  1. It needs a tuned step size, like random-walk Metropolis
  2. It can only be used for Gaussian targets
  3. It is guaranteed to mix fast because nothing is ever rejected
  4. It is Metropolis–Hastings with full-conditional proposals, which are always accepted, and it slows down when coordinates are strongly correlated
Show the answer

D. It is Metropolis–Hastings with full-conditional proposals, which are always accepted, and it slows down when coordinates are strongly correlated

Proposing from π(θj∣θ−j)\pi(\theta_j\mid\boldsymbol\theta_{-j}) makes the acceptance ratio exactly 1. But each move changes one coordinate, so strong correlations force tiny axis-parallel steps; with correlation ρ\rho between two Gaussian coordinates, each sweep's autocorrelation is ρ2\rho^2.

Question 4

Variational inference maximizes the ELBO over a family Q\mathcal Q. Which statement is correct?

  1. Maximizing the ELBO minimizes DKL(q ∥ p(θ∣D))\KL(q\,\|\,p(\boldsymbol\theta\mid\data)), and the optimum is biased by the family, typically underestimating posterior variance
  2. With enough iterations VI converges to the exact posterior, like MCMC
  3. The ELBO equals log⁡p(D)\log p(\data) at the optimum, so it measures the approximation's quality directly
  4. VI minimizes DKL(p ∥ q)\KL(p\,\|\,q), so it covers every mode of the posterior
Show the answer

A. Maximizing the ELBO minimizes DKL(q ∥ p(θ∣D))\KL(q\,\|\,p(\boldsymbol\theta\mid\data)), and the optimum is biased by the family, typically underestimating posterior variance

log⁡p(D)=ELBO+DKL(q ∥ p)\log p(\data)=\text{ELBO}+\KL(q\,\|\,p) with log⁡p(D)\log p(\data) fixed. Unless the posterior lies in Q\mathcal Q, the KL term stays positive at the optimum, and its mode-seeking form makes qq too narrow.

Question 5

Why does plain importance sampling usually fail for posteriors with hundreds of parameters?

  1. Importance sampling is biased even with infinitely many samples
  2. Any small mismatch between proposal and target compounds across dimensions, so the weights' variance grows exponentially and a few samples carry all the weight
  3. It needs the normalizing constant of the target
  4. Its error decreases like 1/N1/N instead of 1/N1/\sqrt N
Show the answer

B. Any small mismatch between proposal and target compounds across dimensions, so the weights' variance grows exponentially and a few samples carry all the weight

Weights are products of per-coordinate ratios. With a proposal only 20% too wide in each of 100 coordinates, E[w2]≈134\E[w^2]\approx134, so 10,000 samples are worth about 74. MCMC avoids this by moving locally through the region where the posterior has mass.

Go deeper

Further reading

  • C. P. Robert & G. Casella, Monte Carlo Statistical Methods, 2nd ed. (Springer, 2004).
  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapters 10 and 11.
  • D. M. Blei, A. Kucukelbir & J. D. McAuliffe, "Variational inference: A review for statisticians," Journal of the American Statistical Association 112(518), 859–877 (2017).
  • A. Vehtari, A. Gelman, D. Simpson, B. Carpenter & P.-C. Bürkner, "Rank-normalization, folding, and localization: An improved R^\hat R for assessing convergence of MCMC," Bayesian Analysis 16(2), 667–718 (2021).