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 , 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 , 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 , and the evidence 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 : the posterior mean (), the probability that a coefficient is positive (), the posterior predictive . Credible intervals are quantiles, which also follow from samples.
A brute-force approach evaluates on a grid with 100 points per coordinate. For a model with parameters, how many evaluations is that? Answer with the power of ten.
Show the answer
20 power of 10
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.
| Strategy | Idea | Exact in the limit? | Typical cost |
|---|---|---|---|
| Monte Carlo and importance sampling | average over independent draws | yes, as the number of draws grows | needs a good proposal; fails in high dimension |
| MCMC | a Markov chain that wanders through the posterior | yes, as the chain runs longer | many correlated draws; convergence is hard to certify |
| Laplace approximation | a Gaussian at the posterior mode, with the inverse Hessian as covariance | no (exact only for Gaussian posteriors) | one optimization and one Hessian |
| Variational inference | the closest member of a simple family, found by optimization | no: biased by the family | an optimization; scales to huge data |
Monte Carlo and importance sampling
If you can draw independently from , the average is unbiased with variance . By the central limit theorem its error is about , whatever the dimension of : the dimension enters only through 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 directly. Importance sampling draws from a proposal you can sample and reweights: . With only available, normalize the weights by their sum,
which is consistent (though slightly biased for finite ). The quantity , between 1 and , measures how many samples are effectively used.
Take target and proposal , slightly too wide (). The normalized weight has , and its second moment is a Gaussian integral:
In independent coordinates the weights multiply, so their second moments do too. With , the effective fraction of samples is about :
For the base is : harmless in one dimension, in a hundred, in a thousand. A handful of samples carry all the weight. (If is narrower than by a factor or more, , the variance is infinite even in one dimension.)
In that example (, ), you draw importance samples. About how many effectively count?
Show the answer
74 samples
. 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 that has the posterior as its stationary distribution: once the chain is distributed according to , 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 :
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_NThe normalizer of cancels in the ratio, so suffices. For a symmetric proposal, such as the random walk with , the terms cancel too and : always move uphill, sometimes downhill.
Why does this target ? A transition rule satisfies detailed balance if for all pairs: in equilibrium, the flow from to equals the flow back. Summing over shows that is then stationary. For the Metropolis–Hastings flow is
which is symmetric in and : detailed balance holds. The full proof, the conditions for convergence and the theory of tuning are in MCMC: Metropolis–Hastings & Gibbs.
A random-walk Metropolis chain with a very small proposal accepts 99% of its moves. Why is that bad news?
- It means the target density is wrong
- Consecutive samples are nearly identical, so the chain explores slowly and its averages have huge variance
- A high acceptance rate means the chain has not reached stationarity yet
- 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 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 samples are worth fewer independent ones. If is the autocorrelation at lag , the effective sample size is , and the Monte Carlo standard error of a mean is .
- 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 chains of length , within-chain variance and between-chain variance , , 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, and a rank-normalized ESS above 400.
A chain behaves like an AR(1) process with lag-one autocorrelation , so . What is the effective sample size of samples?
Show the answer
526 samples
, so . The chain's averages are as precise as about 526 independent draws, and the standard error is 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 of tractable distributions, for instance fully factorized Gaussians (the mean-field family), and finds the member closest to the posterior in Kullback–Leibler divergence. The divergence itself contains the unknown , but the same decomposition that powers EM removes it:
Since does not depend on , maximizing the ELBO, which needs only , 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 . Where is it most expensive for to put probability mass, and what does that do to the approximation?
Wherever is nearly zero but is not, is huge, and pays for it in full. So 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 of the true ones. Variational posteriors are typically overconfident.
| Property | MCMC | Variational inference |
|---|---|---|
| Target | exact posterior, in the limit of long runs | the closest member of , biased by the family |
| Output | correlated samples | a distribution with known form, easy to evaluate and sample |
| Speed and scale | slow; each step touches all the data | fast; stochastic gradients on minibatches |
| Uncertainty | faithful if converged | usually underestimated (mode-seeking divergence) |
| Knowing it worked | diagnostics (, ESS), never proof | the ELBO rises, but its gap to is unknown |
| Typical use | moderate models where accuracy matters | huge data, deep latent-variable models, a first fit |
Key takeaways
- Posterior quantities are expectations, , under a density known only up to its normalizer; grids are hopeless beyond a few dimensions.
- Monte Carlo error falls as 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 , 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 and 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 : 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.
Why can Metropolis–Hastings sample a posterior whose normalizing constant is unknown?
- It estimates during burn-in
- It only ever uses ratios , in which the constant cancels
- It assumes the posterior is Gaussian
- It replaces the posterior by the likelihood
Show the answer
B. It only ever uses ratios , in which the constant cancels
The acceptance probability involves , so never needs to be computed.
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:
- 20 times larger
- the same
- 4.5 times larger
- 20 times smaller
Show the answer
C. 4.5 times larger
Standard error scales as , so the ratio is .
Which statement about Gibbs sampling is true?
- It needs a tuned step size, like random-walk Metropolis
- It can only be used for Gaussian targets
- It is guaranteed to mix fast because nothing is ever rejected
- 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 makes the acceptance ratio exactly 1. But each move changes one coordinate, so strong correlations force tiny axis-parallel steps; with correlation between two Gaussian coordinates, each sweep's autocorrelation is .
Variational inference maximizes the ELBO over a family . Which statement is correct?
- Maximizing the ELBO minimizes , and the optimum is biased by the family, typically underestimating posterior variance
- With enough iterations VI converges to the exact posterior, like MCMC
- The ELBO equals at the optimum, so it measures the approximation's quality directly
- VI minimizes , so it covers every mode of the posterior
Show the answer
A. Maximizing the ELBO minimizes , and the optimum is biased by the family, typically underestimating posterior variance
with fixed. Unless the posterior lies in , the KL term stays positive at the optimum, and its mode-seeking form makes too narrow.
Why does plain importance sampling usually fail for posteriors with hundreds of parameters?
- Importance sampling is biased even with infinitely many samples
- Any small mismatch between proposal and target compounds across dimensions, so the weights' variance grows exponentially and a few samples carry all the weight
- It needs the normalizing constant of the target
- Its error decreases like instead of
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, , so 10,000 samples are worth about 74. MCMC avoids this by moving locally through the region where the posterior has mass.
Go deeper
- MCMC: Metropolis–Hastings & Gibbs · Random walks whose long-run distribution is the posterior.
- Hamiltonian Monte Carlo · Using gradients to take long steps that are still accepted.
- Variational Inference · Turning inference into optimization: the ELBO and the reparameterization trick.
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 for assessing convergence of MCMC," Bayesian Analysis 16(2), 667–718 (2021).