---
title: Approximate inference
heading: When the posterior has no closed form, the Laplace approximation and its evidence estimate, variational inference with the evidence lower bound and mean-field factors, which way the KL divergence leans, and the variational autoencoder
eyebrow: S14 · Lesson 35 · Approximate inference
xp: 50
---

::: hook
Conjugate priors and Gaussian processes gave exact posteriors, but most models don't. Logistic regression's posterior over its weights, a mixture model's posterior over its assignments, a neural network's posterior over anything: none has a closed form, and the integrals for predictions and evidence are out of reach. Two families of approximation fill the gap. Laplace's method fits a Gaussian at the peak; variational inference picks the best member of a tractable family by optimization, and the variational autoencoder turns that into a way of training generative networks.
:::

::: play
- The solid curve is a gamma posterior for a count rate, with shape a (from a − 1 events under a flat prior), scaled to peak at 1.
- The dashed curve is its Laplace approximation: a Gaussian at the same peak with the same curvature there.
- With few events the posterior is skewed and the Gaussian misplaces its mass; as a grows, the two converge, as the central limit theorem suggests.
:::

```sim plot
view: graph
x: L = 0..40
y: p = 0..1.1
slider: a = 2..30 = 10
plot: (L/(a - 1))^(a - 1)*exp(-(L - (a - 1))) | label: exact posterior
plot: exp(-(L - (a - 1))^2/(2*(a - 1))) | dashed | label: Laplace approximation
```

::: predict
## A two-dimensional Gaussian posterior has unit variances and correlation 0.9. A mean-field variational approximation (a product of independent Gaussians) is fitted by minimizing KL(q‖p). What variance does it give each variable?

- [ ] 1, the true marginal variance
- [ ] 1.9
- [x] 0.19
- [ ] 0.9

::: reveal
The best factorized q matches the conditional precision, not the marginal variance: each factor's variance is $1/\Lambda_{ii} = 1 - \rho^2$ = 0.19, a standard deviation of 0.44 against the true 1. Minimizing KL(q‖p) heavily penalizes q for putting mass where p has little, so a factorized q shrinks to fit inside the correlated ellipse. Variational posteriors tend to be overconfident.
:::
:::

::: nameit
## The Laplace approximation

Find the posterior's mode $\mathbf z_0$ and the curvature of its logarithm there, $A = -\nabla\nabla\ln p(\mathbf z)|_{\mathbf z_0}$. Then
$$q(\mathbf z) = \mathcal N(\mathbf z_0, A^{-1})$$
For M parameters it also estimates the evidence:
$$\ln p(D) \approx \ln p(D|\mathbf z_0) + \ln p(\mathbf z_0) + \frac M2\ln 2\pi - \frac12\ln|A|$$
Since |A| grows about as $N^M$, dropping the terms that don't grow with N leaves BIC (lesson 12). The approximation is good when the posterior is nearly Gaussian, which large data sets usually make it, and poor for skewed or multimodal posteriors.

## Variational inference

For any distribution q over the hidden variables Z,
$$\ln p(X) = \mathcal L(q) + \text{KL}(q\,\|\,p(Z|X)), \qquad \mathcal L(q) = \int q(Z)\ln\frac{p(X, Z)}{q(Z)}\,dZ$$
The KL term is never negative, so $\mathcal L$, the **evidence lower bound** (ELBO), is a lower bound on the log evidence, and maximizing it over a tractable family of q minimizes the divergence from the true posterior. In the **mean-field** family $q(Z) = \prod_jq_j(Z_j)$, each factor's best form is
$$\ln q_j^*(Z_j) = \mathbb E_{i \ne j}[\ln p(X, Z)] + \text{const}$$
updated in turn, a coordinate ascent that never lowers the bound. EM (lesson 36) is the special case where q is the exact posterior over the hidden assignments.

## Which way KL leans

KL(q‖p) is large wherever q has mass and p doesn't, so minimizing it makes q **zero-forcing**: it sits inside p, under one mode if p has several, and underestimates spread. KL(p‖q), used by expectation propagation, is **zero-avoiding**: q covers all of p's mass, spreading over every mode.

## The variational autoencoder

An encoder network outputs a Gaussian $q(\mathbf z|\mathbf x) = \mathcal N(\boldsymbol\mu(\mathbf x), \text{diag}\,\boldsymbol\sigma^2(\mathbf x))$; a decoder network gives $p(\mathbf x|\mathbf z)$; the prior is $\mathcal N(0, I)$. Both are trained to maximize the ELBO, a reconstruction term minus
$$\text{KL}(q\,\|\,\mathcal N(0, 1)) = \frac12\sum_j(\mu_j^2 + \sigma_j^2 - 1 - \ln\sigma_j^2)$$
Samples are drawn as $\mathbf z = \boldsymbol\mu + \boldsymbol\sigma \odot \boldsymbol\epsilon$ with $\boldsymbol\epsilon \sim \mathcal N(0, I)$, the **reparameterization** that lets gradients flow through the sampling to μ and σ.
:::

::: example
## A pass rate has a uniform prior, and 7 of 10 trials pass. Compare the Laplace approximation with the exact beta(8, 4) posterior.

::: solution
1. **Mode.** The log posterior is $7\ln\theta + 3\ln(1 - \theta)$, with its mode at 0.7.
2. **Curvature.** At the mode it is
   $$7/0.7^2 + 3/0.3^2 = 47.6$$
   so the Laplace approximation is N(0.7, 0.021), a standard deviation of 0.145.
3. **Exact posterior.** Beta(8, 4) has mean 0.667 and standard deviation 0.131.
4. **Compare.** The Laplace version is centered at the mode rather than the mean and is a little too wide, because the true posterior is skewed toward 0.5 by the boundary at 1; with 70 of 100 the two would agree to a few percent.

**Answer:** the Laplace approximation is N(0.7, 0.021), with standard deviation 0.145, against the exact posterior's mean 0.667 and standard deviation 0.131.
:::
:::

::: example
## Work out the mean-field approximation in the predict question and its KL divergence from the true posterior.

::: solution
1. **True precision matrix.**
   $$\Sigma^{-1} = \frac1{0.19}\begin{bmatrix}1 & -0.9 \\ -0.9 & 1\end{bmatrix}$$
   so each mean-field factor is N(0, 0.19).
2. **KL divergence.** For two zero-mean Gaussians:
   $$\begin{aligned} D &= \tfrac12[\text{tr}(\Sigma^{-1}\Sigma_q) - 2 \\ &\qquad + \ln(|\Sigma|/|\Sigma_q|)] \\ &= \tfrac12[2 - 2 + \ln(0.19/0.0361)] \\ &= 0.83\ \text{nats} \end{aligned}$$
3. **What suffers.** The means are right; only the spread suffers, and predictions that need the posterior's width will be overconfident.

**Answer:** each mean-field factor is N(0, 0.19), and the KL divergence from the true posterior is 0.83 nats.
:::
:::

::: example
## A VAE's encoder gives one latent variable μ = 1 and σ = 0.5. Find its KL term and the sample drawn with ε = −1.2. What would the total KL be for 32 such latent dimensions?

::: solution
1. **KL term.**
   $$\begin{aligned} \text{KL} &= \tfrac12(1^2 + 0.25 - 1 - \ln 0.25) \\ &= 0.818\ \text{nats} \end{aligned}$$
2. **Sample.**
   $$\begin{aligned} z &= 1 + 0.5 \times (-1.2) \\ &= 0.4 \end{aligned}$$
3. **32 dimensions.** The KL cost is 26.2 nats per example, which the reconstruction must repay.
4. **Unused dimensions.** Dimensions the decoder doesn't use are pushed to μ = 0, σ = 1, where their KL is zero, so a VAE switches off latent dimensions it doesn't need.

**Answer:** the KL term is 0.818 nats, the sample is z = 0.4, and 32 such dimensions cost 26.2 nats.
:::
:::

::: check
kind: parts
given: N = 10 | 50 | 100; f = 0.3 | 0.7 | 0.9; let m = f*N

## A success probability has a uniform prior, and {m} of {N} trials succeed.

::: part
answer: m/N
tolerance: 0.5%

### Where is the Laplace approximation centered?

::: misses
- [(m + 1)/(N + 2)] That's the posterior mean; Laplace uses the mode.
- [any] The mode of $\theta^m(1 - \theta)^{N - m}$.
:::
:::

::: part
answer: sqrt(m/N*(1 - m/N)/N)
tolerance: 0.5%

### What standard deviation does it give?

::: misses
- [sqrt((m + 1)*(N - m + 1)/((N + 2)^2*(N + 3)))] That's the exact posterior's.
- [any] $\sqrt{\theta_0(1 - \theta_0)/N}$ from the curvature.
:::
:::
:::

::: check
kind: parts
given: a = 3 | 10 | 40; b = 0.5 | 2 | 10

## A rate's posterior is gamma with shape {a} and rate {b}.

::: part
answer: sqrt(a - 1)/b
tolerance: 0.5%

### What standard deviation does its Laplace approximation have?

::: misses
- [sqrt(a)/b] That's the exact standard deviation; Laplace's curvature at the mode gives $\sqrt{a - 1}/b$.
- [any] At the mode $(a - 1)/b$ the curvature is $b^2/(a - 1)$.
:::
:::

::: part
answer: (a/b - (a - 1)/b)/(sqrt(a)/b)
tolerance: 0.5%

### By how many exact standard deviations is the approximation's center below the true mean?

::: misses
- [any] (mean − mode)/sd = $1/\sqrt a$.
:::
:::
:::

::: check
kind: parts
given: s = 0.5 | 1 | 3; r = 0.5 | 0.8 | 0.95

## A Gaussian posterior over two variables has equal standard deviations {s} and correlation {r}. It's approximated by minimizing KL(q‖p) over factorized Gaussians.

::: part
answer: s*sqrt(1 - r^2)
tolerance: 0.5%

### What standard deviation does each factor get?

::: misses
- [s] That's the true marginal; mean field underestimates it.
- [s*(1 - r^2)] Take the square root of the variance $\sigma^2(1 - \rho^2)$.
- [any] $\sigma\sqrt{1 - \rho^2}$.
:::
:::

::: part
answer: 0.5*ln(1/(1 - r^2))
unit: nats
tolerance: 0.5%

### What is the KL divergence of the approximation from the posterior?

::: misses
- [any] $\frac12\ln[1/(1 - \rho^2)]$.
:::
:::
:::

::: check
kind: parts
given: m = 0 | 0.5 | 2; s = 0.2 | 0.6 | 1.5; D = 1 | 16 | 64; e = -1 | 0.7

## A VAE encoder outputs μ = {m} and σ = {s} for each of {D} latent dimensions.

::: part
answer: D*0.5*(m^2 + s^2 - 1 - ln(s^2))
unit: nats
tolerance: 0.5%

### What is the total KL term?

::: misses
- [D*0.5*(m^2 + s^2 - 1 - ln(s))] The log is of the variance, σ².
- [any] $\frac D2(\mu^2 + \sigma^2 - 1 - \ln\sigma^2)$.
:::
:::

::: part
answer: m + s*e
tolerance: 0.5%

### What sample does ε = {e} give in one dimension?

::: misses
- [m + s^2*e] Multiply ε by σ, not σ².
- [any] $z = \mu + \sigma\epsilon$.
:::
:::
:::

::: check
kind: parts
given: L = -150 | -40; P = -3 | -1; M = 1 | 5; A = 50 | 2000

## A model with {M} parameters has a peak log-likelihood of {L} and log prior {P} at its mode, where the log posterior's Hessian has determinant {A} (in magnitude).

::: part
answer: L + P + M/2*ln(2*pi) - 0.5*ln(A)
unit: nats
tolerance: 0.5%

### What log evidence does Laplace's method estimate?

::: misses
- [L + P - 0.5*ln(A)] Include $\frac M2\ln 2\pi$.
- [any] $\ln p(D|\mathbf z_0) + \ln p(\mathbf z_0) + \frac M2\ln 2\pi - \frac12\ln|A|$.
:::
:::
:::

::: check
kind: choice

## A posterior has two well-separated modes of equal height. What does a single Gaussian fitted by minimizing KL(q‖p) do?

- [ ] Covers both modes with one broad Gaussian
- [x] Sits on one mode, since spreading over the gap would put q's mass where p has almost none
- [ ] Centers between the modes, where p is small
- [ ] Fails to converge

::: misses
- [1] That's what minimizing KL(p‖q) does.
- [3] That would put q's mass where p is nearly zero, the most expensive choice.
- [4] It converges, to one mode or the other depending on where it starts.
:::
:::

::: check
kind: derivation
vars: a = 2..50, b = 2..50

## A probability's posterior is beta(a, b).

::: step
answer: (a - 1)/(a + b - 2)

### Where is its mode?
:::

::: step
answer: (a - 1)*(b - 1)/(a + b - 2)^3

### What variance does the Laplace approximation give?
:::

::: step
answer: a*b/((a + b)^2*(a + b + 1))

### What is the exact variance?
:::

::: right
Right. For large a and b the two agree; for small ones Laplace is too wide and misplaced.
:::
:::

::: explain
## Why does a variational approximation found by minimizing KL(q‖p) tend to underestimate the posterior's uncertainty?

::: model
The divergence KL(q‖p) averages the log ratio of q to p over q's own mass. Wherever q places probability and p has little, that ratio is huge, so the optimization strongly avoids spreading q into regions p considers unlikely, while it pays little for missing parts of p that q doesn't cover. If the approximating family can't match p's shape, for example because it assumes independence where p is correlated, or has one mode where p has several, the best compromise is a q that fits inside p, narrower than p's true spread. Predictions built on it inherit that overconfidence.
:::
:::

::: practice
::: check
given: N = 20 | 80; f = 0.25 | 0.6; let m = f*N
answer: sqrt(m/N*(1 - m/N)/N)
tolerance: 0.5%

## Laplace sd: {m} of {N}, uniform prior?

::: misses
- [any] $\sqrt{\theta_0(1 - \theta_0)/N}$.
:::
:::

::: check
given: m = 0.3 | 1.5; s = 0.4 | 2
answer: 0.5*(m^2 + s^2 - 1 - ln(s^2))
unit: nats
tolerance: 0.5%

## VAE KL: μ = {m}, σ = {s}?

::: misses
- [any] $\frac12(\mu^2 + \sigma^2 - 1 - \ln\sigma^2)$.
:::
:::

::: check
given: s = 1 | 2; r = 0.6 | 0.99
answer: s*sqrt(1 - r^2)
tolerance: 0.5%

## Mean-field sd: σ = {s}, ρ = {r}?

::: misses
- [any] $\sigma\sqrt{1 - \rho^2}$.
:::
:::
:::
