Course contents 06 / 15

06 / 15 · Bayesian Linear Models

The Laplace approximation and Bayesian classification

Replace a posterior that has no formula by the Gaussian that matches it at its mode: Bayesian logistic regression, predictions that grow less confident away from the data, and a relevance vector machine that classifies.

On this page 6

A logistic regression with one weight, p(t=1∣x)=σ(wx)p(t = 1 \mid x) = \sigma(wx), is fitted to five points and asked about a new input at x=3x = 3. With the fitted weight it answers 0.870.87. But five points say little about the weight: its posterior standard deviation, computed in the worked example below, is as large as the weight itself. Averaged over the plausible weights, the probability is 0.790.79. Far from the data the gap grows, and on separable data the fitted weights run off to infinity and every plug-in probability becomes 0 or 1.

The average is ∫σ(w⊤φ∗) p(w∣t) dw\int \sigma(w^\top\varphi_*)\, p(w \mid t)\, dw, and here the Gaussian algebra of regression stops working. The targets are 0 or 1, the likelihood is a product of sigmoids, and the integral that normalizes the posterior has no formula. The relevance vector machine cannot classify for the same reason: it needs that integral as its evidence. The simplest way around it is to replace the posterior by a Gaussian centred at its mode, with the curvature of the log-posterior there as its precision. This is the Laplace approximation.

The Laplace approximation#

Let θ∈Rd\theta \in \mathbb R^d be the unknowns and p~(θ)=p(D∣θ) p(θ)\tilde p(\theta) = p(D \mid \theta)\, p(\theta) the unnormalized posterior. Its normalizer Z=∫p~(θ) dθZ = \int \tilde p(\theta)\, d\theta is the evidence p(D)p(D). Near its maximum, any smooth log-density looks like a parabola, and a density whose logarithm is a parabola is a Gaussian. So expand log⁡p~\log\tilde p to second order around the mode θ^\hat\theta. The linear term vanishes there, because the gradient is zero:

log⁡p~(θ)≈log⁡p~(θ^)−12(θ−θ^)⊤H (θ−θ^),\log\tilde p(\theta) \approx \log\tilde p(\hat\theta) - \tfrac12 (\theta - \hat\theta)^\top H\, (\theta - \hat\theta) ,

where H=−∇∇log⁡p~(θ^)H = -\nabla\nabla \log\tilde p(\hat\theta) is the negative Hessian at the mode. Exponentiated, the right side is p~(θ^)\tilde p(\hat\theta) times an unnormalized Gaussian, and the Gaussian integral with no linear term, ∫e−12u⊤Hu du=(2π)d/2det⁡(H)−1/2\int e^{-\frac12 u^\top H u}\, du = (2\pi)^{d/2} \det(H)^{-1/2}, gives its normalizer:

p(θ∣D)≈N(θ∣θ^, H−1),Z≈p~(θ^) (2π)d/2det⁡(H)−1/2\boxed{ \begin{aligned} p(\theta \mid D) &\approx \mathcal N\big(\theta \mid \hat\theta,\ H^{-1}\big), \\ Z &\approx \tilde p(\hat\theta)\, (2\pi)^{d/2} \det(H)^{-1/2} \end{aligned} }

The approximation needs a smooth log⁡p~\log\tilde p and a positive definite HH. At any local maximum HH is positive semidefinite, the second-order necessary condition; positive definite is the stronger requirement of a nondegenerate maximum. The density e−θ4e^{-\theta^4} has a strict maximum at 0 with H=0H = 0, and there the Gaussian has infinite variance. Its ingredients are an optimizer, which finds θ^\hat\theta, and second derivatives at one point. For a linear-Gaussian model the log-posterior is exactly quadratic and the approximation is exact; that is how the evidence of Bayesian linear regression was computed. The logarithm of the ZZ formula is the Laplace approximation of the evidence, and its large-sample limit is the BIC of the model selection note. Laplace used the method for integrals of this kind; Tierney and Kadane (1986) made it a standard tool for posterior moments.

Worked example. A coin with a uniform prior shows 3 heads and 1 tail. The exact posterior is Beta(4,2)\mathrm{Beta}(4, 2), with log⁡p~(p)=3log⁡p+log⁡(1−p)\log\tilde p(p) = 3\log p + \log(1 - p). The derivative 3/p−1/(1−p)3/p - 1/(1 - p) vanishes at p^=3/4\hat p = 3/4, and

QuantityValue
H=3/p^2+1/(1−p^)2H = 3/\hat p^2 + 1/(1 - \hat p)^216/3+16=21.3316/3 + 16 = 21.33
standard deviation H−1/2H^{-1/2}0.21650.2165
evidence estimate p^3(1−p^)2π/H\hat p^3 (1 - \hat p) \sqrt{2\pi/H}0.1055⋅0.5427=0.05720.1055 \cdot 0.5427 = 0.0572
exact evidence B(4,2)B(4, 2)1/20=0.051/20 = 0.05

The estimate is 14.5% too large. Four observations leave the posterior visibly skewed, and the last section returns to what that costs.

Bayesian logistic regression#

Take features φ(x)\varphi(x), a design matrix Φ\Phi with rows φ(xi)⊤\varphi(x_i)^\top, targets ti∈{0,1}t_i \in \{0, 1\} and the prior N(0,α−1I)\mathcal N(0, \alpha^{-1} I). With yi=σ(w⊤φ(xi))y_i = \sigma(w^\top\varphi(x_i)) the predicted probability of class 1, the log-posterior is

log⁡p(w∣t)=∑i=1n(tilog⁡yi+(1−ti)log⁡(1−yi))−α2∥w∥2+const.\begin{aligned} \log p(w \mid t) ={}& \sum_{i=1}^n \big(t_i\log y_i + (1 - t_i)\log(1 - y_i)\big) \\ &- \frac\alpha2\lVert w\rVert^2 + \text{const} . \end{aligned}

Its gradient is the residuals times the inputs minus the prior term. Differentiating once more with ∂yi/∂w=yi(1−yi) φ(xi)\partial y_i/\partial w = y_i(1 - y_i)\,\varphi(x_i), from σ′=σ(1−σ)\sigma' = \sigma(1 - \sigma), gives

∇log⁡p(w∣t)=Φ⊤(t−y)−αw,∇∇log⁡p(w∣t)=−(Φ⊤B Φ+αI),\begin{aligned} \nabla\log p(w \mid t) &= \Phi^\top(t - y) - \alpha w, \\ \nabla\nabla\log p(w \mid t) &= -\big(\Phi^\top B\, \Phi + \alpha I\big), \end{aligned}

where B=diag⁡(yi(1−yi))B = \operatorname{diag}\big(y_i(1 - y_i)\big). The Hessian is negative definite for every ww: for any v≠0v \ne 0, v⊤(Φ⊤B Φ+αI)v=∑iyi(1−yi)(φ(xi)⊤v)2+α∥v∥2>0v^\top(\Phi^\top B\,\Phi + \alpha I)v = \sum_i y_i(1 - y_i)(\varphi(x_i)^\top v)^2 + \alpha\lVert v\rVert^2 \gt 0. So the log-posterior is strictly concave and has at most one maximum. It has one, because the log-likelihood is at most 0 and the prior term tends to −∞-\infty as ∥w∥→∞\lVert w\rVert \to \infty. Newton’s method finds it, with quadratic convergence near the mode and a damped step that guarantees ascent far from it:

wnew=w+(Φ⊤B Φ+αI)−1(Φ⊤(t−y)−αw),w^{\text{new}} = w + \big(\Phi^\top B\, \Phi + \alpha I\big)^{-1}\big(\Phi^\top(t - y) - \alpha w\big),

with BB and yy at the current ww. Multiplying by Φ⊤B Φ+αI\Phi^\top B\,\Phi + \alpha I shows what each step solves:

(Φ⊤B Φ+αI) wnew=Φ⊤B Φw+αw+Φ⊤(t−y)−αw=Φ⊤B (Φw+B−1(t−y))=Φ⊤B z.\begin{aligned} (\Phi^\top B\,\Phi + \alpha I)\, w^{\text{new}} &= \Phi^\top B\,\Phi w + \alpha w + \Phi^\top(t - y) - \alpha w \\ &= \Phi^\top B\,\big(\Phi w + B^{-1}(t - y)\big) = \Phi^\top B\, z . \end{aligned}

These are the normal equations of ridge regression on the working targets zz, with weight yi(1−yi)y_i(1 - y_i) on point ii. Each step solves a weighted least-squares problem whose weights change with ww, which is why the method is also called iteratively reweighted least squares (IRLS). At convergence,

p(w∣t)≈N(w∣w^, Σ),Σ=(Φ⊤B Φ+αI)−1,\boxed{ \begin{aligned} p(w \mid t) &\approx \mathcal N\big(w \mid \hat w,\ \Sigma\big), \\ \Sigma &= \big(\Phi^\top B\, \Phi + \alpha I\big)^{-1}, \end{aligned} }

with BB evaluated at w^\hat w. This is the posterior of regression with the noise precision β\beta replaced by a precision yi(1−yi)y_i(1 - y_i) for each point. A point the model classifies confidently, with yiy_i near 0 or 1, adds little curvature; points near the boundary, with yiy_i near 12\frac12, add the most. The prior keeps the mode finite even on separable data.

Worked example. The model of the opening has one weight and no bias, five points x=(−1.5,−0.5,0.5,1,2)x = (-1.5, -0.5, 0.5, 1, 2) with t=(0,1,0,1,1)t = (0, 1, 0, 1, 1), and α=1\alpha = 1. From w=0w = 0, Newton’s method gives 0.5960.596, 0.6300.630 and 0.63050.6305, after which the digits stop changing. At the mode,

H=∑ixi2 yi(1−yi)+α=2.490,q(w)=N(0.6305, 1/2.490).\begin{aligned} H &= \sum_i x_i^2\, y_i(1 - y_i) + \alpha = 2.490, \\ q(w) &= \mathcal N(0.6305,\ 1/2.490) . \end{aligned}

The standard deviation, 0.6340.634, is as large as the mode: the five points favour a positive weight but say little about its size.

Figure

The Laplace approximation for logistic regression with one weight

The Laplace approximation for logistic regression with one weightFive points, one weight, prior N(0, 1). Newton's method from zero: 0.596, 0.630, the mode ŵ = 0.6305. The precision of the approximation is H = 2.490, the standard deviation 0.634. At x* = 3 the activation a = wx* is N(1.891, 3.614); κ = 0.643 and the moderated probability σ(κμₐ) = 0.771 against 0.869 for the MAP plug-in; the exact answer is 0.790.−1.5−0.50.512x01011tα = 1N(0, 1/α)w ← w − ℓ′(w)/ℓ″(w)Newton steps on ln p(w | t)00.5960.6300.6305w1H = −ℓ″(ŵ) = 2.490sd = 0.63423x*μₐ = 3ŵ, s² = 9/Ha ~ N(1.891, 3.614)3σ(κμₐ) = 0.771κ = 0.643MAP plug-in σ(μₐ) = 0.869; exact posterior 0.7904The Laplace approximation for logistic regression with one weightFive points, one weight, prior N(0, 1). Newton's method from zero: 0.596, 0.630, the mode ŵ = 0.6305. The precision of the approximation is H = 2.490, the standard deviation 0.634. At x* = 3 the activation a = wx* is N(1.891, 3.614); κ = 0.643 and the moderated probability σ(κμₐ) = 0.771 against 0.869 for the MAP plug-in; the exact answer is 0.790.−1.5−0.50.512x01011tα = 1N(0, 1/α)w ← w − ℓ′(w)/ℓ″(w)Newton steps00.5960.6300.6305w1H = −ℓ″(ŵ) = 2.490sd = 0.63423x*μₐ = 3ŵ, s² = 9/Ha ~ N(1.891, 3.614)3σ(κμₐ) = 0.771κ = 0.643MAP σ(μₐ) = 0.869; exact 0.7904
Logistic regression p(t = 1 | x) = σ(wx) without a bias, five points, prior N(0, 1). Green: the data; amber: the prior; blue: the posterior and its approximation; red: the prediction. Newton's method reaches the mode in three steps, and the approximation is N(0.630, 1/2.490). At x* = 3 the moderated probability 0.771 is closer to the exact 0.790 than the plug-in 0.869.

The numbered steps of the figure:

  1. Newton’s method climbs the concave log-posterior to its mode w^\hat w.
  2. The curvature at the mode is the precision of the Gaussian approximation.
  3. At a new input the activation a=wx∗a = w x_* is Gaussian under the approximation.
  4. Averaging the sigmoid over that Gaussian gives the moderated probability of the next section.

The predictive distribution and the moderated output#

The sigmoid depends on ww only through the activation a=w⊤φ∗a = w^\top\varphi_* of the new input. Under the approximation aa is an affine map of a Gaussian, so it is Gaussian too:

μa=w^⊤φ∗,sa2=φ∗⊤Σ φ∗.\begin{aligned} \mu_a &= \hat w^\top\varphi_*, \\ s_a^2 &= \varphi_*^\top\Sigma\,\varphi_* . \end{aligned}

The predictive probability becomes a one-dimensional integral, ∫σ(a) N(a∣μa,sa2) da\int \sigma(a)\, \mathcal N(a \mid \mu_a, s_a^2)\, da. It has no closed form, but an excellent approximation. The sigmoid is very close to a rescaled normal distribution function, and a normal distribution function averaged over a Gaussian is again one. Write ΦN\Phi_{\mathcal N} for the standard normal distribution function, with a subscript to keep it apart from the design matrix.

First, approximate σ(a)≈ΦN(λa)\sigma(a) \approx \Phi_{\mathcal N}(\lambda a), with λ\lambda chosen so that the two curves have the same slope at 0. The slopes are σ′(0)=14\sigma'(0) = \frac14 and λ/2π\lambda/\sqrt{2\pi}, so λ2=π/8\lambda^2 = \pi/8.

Next, average the normal distribution function. Let Z∼N(0,1)Z \sim \mathcal N(0, 1) be independent of a=μa+saεa = \mu_a + s_a\varepsilon, with ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1). Then ΦN(λa)=P(Z≤λa∣a)\Phi_{\mathcal N}(\lambda a) = P(Z \le \lambda a \mid a), and Z−λsaεZ - \lambda s_a\varepsilon is a sum of independent Gaussians with variance 1+λ2sa21 + \lambda^2 s_a^2:

E[ΦN(λa)]=P(Z−λsaε≤λμa)=ΦN(λμa1+λ2sa2).\begin{aligned} \mathbb E\big[\Phi_{\mathcal N}(\lambda a)\big] &= P\big(Z - \lambda s_a\varepsilon \le \lambda\mu_a\big) \\ &= \Phi_{\mathcal N}\Big(\frac{\lambda\mu_a}{\sqrt{1 + \lambda^2 s_a^2}}\Big) . \end{aligned}

Finally, turn back to the sigmoid with ΦN(λu)≈σ(u)\Phi_{\mathcal N}(\lambda u) \approx \sigma(u), now at u=μa/1+λ2sa2u = \mu_a/\sqrt{1 + \lambda^2 s_a^2}:

p(t∗=1∣x∗,t)≈σ(κ(sa2) μa),κ(s2)=(1+πs28)−1/2\boxed{ \begin{aligned} p(t_* = 1 \mid x_*, t) &\approx \sigma\big(\kappa(s_a^2)\, \mu_a\big), \\ \kappa(s^2) &= \Big(1 + \frac{\pi s^2}{8}\Big)^{-1/2} \end{aligned} }

This is the moderated output of MacKay (1992): the plug-in prediction, with its activation shrunk towards 0 by an amount that grows with the uncertainty at that input. Since κ>0\kappa \gt 0, the sign of κμa\kappa\mu_a is the sign of μa\mu_a. The decision boundary p=12p = \frac12 is therefore that of the plug-in, and so is every classification at that threshold. What changes is the confidence, and with it every decision at another threshold and every log-loss. Far from the data, where sa2s_a^2 is large, the probability stays near 12\frac12 instead of running to 0 or 1.

Two alternatives are worth knowing (Murphy, 2023, Section 15.3.6). The integral can be estimated by sampling weights from the Gaussian and averaging σ(w⊤φ∗)\sigma(w^\top\varphi_*). And for KK classes the same rescaling, applied to each logit with its own variance, gives a generalized probit approximation of the softmax average.

Worked example. In the one-weight example at x∗=3x_* = 3:

QuantityValue
μa=3w^\mu_a = 3\hat w, sa2=9/Hs_a^2 = 9/H1.8911.891, 3.6143.614
κ=(1+π⋅3.614/8)−1/2\kappa = (1 + \pi \cdot 3.614/8)^{-1/2}0.6430.643
plug-in σ(μa)\sigma(\mu_a)0.8690.869
moderated σ(κμa)\sigma(\kappa\mu_a)0.7710.771
exact Gaussian average ∫σ(a) N(a∣μa,sa2) da\int\sigma(a)\,\mathcal N(a \mid \mu_a, s_a^2)\, da0.7690.769
exact predictive, averaged over the true posterior0.7900.790

The probit step costs only 0.0020.002. The Laplace approximation recovers most of the correction, from 0.8690.869 towards 0.7900.790, and then goes a little too far.

Figure

The moderated output of Bayesian logistic regression

The moderated output of Bayesian logistic regressionThree curves of the probability of class 1 over x from −5 to 5: the plug-in of the mode goes quickly to 0 and 1, the moderated output stays closer to 1/2, and the exact predictive lies between them. All three cross 1/2 at the same point.00.51−4−2024xplug-in of the mode σ(μₐ)moderated σ(κμₐ)exact posterior predictiveThe moderated output of Bayesian logistic regressionThree curves of the probability of class 1 over x from −5 to 5: the plug-in of the mode goes quickly to 0 and 1, the moderated output stays closer to 1/2, and the exact predictive lies between them. All three cross 1/2 at the same point.00.51−4−2024xplug-in of the mode σ(μₐ)moderated σ(κμₐ)exact posterior predictive
Six points, three of each class (dots at the bottom: class 0; at the top: class 1), features (1, x), prior N(0, I). Red: the plug-in of the mode; blue: the moderated output; black: the exact predictive, computed on a grid over the two weights. All three cross 1/2 at the same point; at x = 3 they give 0.890, 0.790 and 0.814.

With a bias and six points the pattern holds along the whole axis. At x=3x = 3 the plug-in gives 0.8900.890, the moderated output 0.7900.790 and the exact predictive 0.8140.814; at x=1x = 1, inside the data, 0.6690.669, 0.6490.649 and 0.6630.663. The overshoot has a visible cause in the one-weight example. The exact posterior has its mean at 0.7090.709, to the right of the mode 0.63050.6305, and a skewness of 0.210.21: large weights, and so confident predictions, are more probable than the symmetric Gaussian around the mode allows.

The evidence and relevance vector classification#

The Laplace estimate of ZZ gives the evidence of the prior precisions. Take the prior N(0,A−1)\mathcal N(0, A^{-1}) of the relevance vector machine, with A=diag⁡(α1,…,αm)A = \operatorname{diag}(\alpha_1, \dots, \alpha_m), and let w^\hat w be the mode for the current α\alpha. Then

log⁡p(t∣α)≈log⁡p(t∣w^)+log⁡N(w^∣0,A−1)+m2log⁡2π−12log⁡det⁡(Φ⊤B Φ+A).\begin{aligned} \log p(t \mid \alpha) \approx{}& \log p(t \mid \hat w) + \log \mathcal N\big(\hat w \mid 0, A^{-1}\big) \\ &+ \tfrac m2\log 2\pi - \tfrac12\log\det\big(\Phi^\top B\,\Phi + A\big) . \end{aligned}

This has the shape of the regression evidence, and Tipping (2001), following MacKay (1992), maximizes it with the same updates, using the Laplace mean and covariance in place of the exact ones. Differentiate in one αi\alpha_i. At the mode the gradient of the first two terms in ww is zero, so the dependence through w^\hat w drops out of them; Tipping also neglects it inside BB. The log-determinant rule gives the last term:

∂log⁡p(t∣α)∂αi≈−w^i22+12αi−Σii2=0⟹αiw^i2=1−αiΣii=γi.\begin{aligned} \frac{\partial \log p(t \mid \alpha)}{\partial \alpha_i} &\approx -\frac{\hat w_i^2}{2} + \frac{1}{2\alpha_i} - \frac{\Sigma_{ii}}{2} = 0 \\ \Longrightarrow\quad \alpha_i \hat w_i^2 &= 1 - \alpha_i \Sigma_{ii} = \gamma_i . \end{aligned}

Relevance vector classification alternates:

  1. for the current α\alpha, find the mode w^\hat w by Newton’s method, warm-started from the previous mode;
  2. compute Σ=(Φ⊤B Φ+A)−1\Sigma = (\Phi^\top B\,\Phi + A)^{-1} at the mode;
  3. update γi=1−αiΣii\gamma_i = 1 - \alpha_i\Sigma_{ii} and αi=γi/w^i2\alpha_i = \gamma_i/\hat w_i^2, and prune the features whose αi\alpha_i passes a large threshold;
  4. repeat until the precisions settle.

The analogy with regression is exact in one sense. At the mode the gradient is zero, Φ⊤(t−y)=Aw^\Phi^\top(t - y) = A\hat w; adding Φ⊤B Φw^\Phi^\top B\,\Phi\hat w to both sides gives (Φ⊤B Φ+A)w^=Φ⊤B t^(\Phi^\top B\,\Phi + A)\hat w = \Phi^\top B\,\hat t, the IRLS step at its fixed point, and therefore

w^=Σ Φ⊤B t^,t^=Φw^+B−1(t−y).\begin{aligned} \hat w &= \Sigma\,\Phi^\top B\,\hat t, \\ \hat t &= \Phi\hat w + B^{-1}(t - y) . \end{aligned}

This is the regression posterior mean for the targets t^\hat t, with a noise precision yi(1−yi)y_i(1 - y_i) of its own for every point. The Laplace approximation maps classification onto a regression with heteroscedastic noise (Tipping, 2001, Section 3), and the sparsity analysis of the previous note carries over. Because the log-posterior of this linear model is concave, the posterior is unimodal, and the Gaussian approximation is much safer here than for neural networks, whose posteriors have many modes.

ARD selects raw features as well as kernels. In an experiment of Vetrov and Kropotov, 100 training points have 50 features, of which only two separate the classes. Logistic regression gives every weight a nonzero value and errs on 16% of the test points. The relevance vector classifier keeps three weights, including the two informative ones, and errs on 8%, the Bayes error of the problem.

Worked example. On kernel features the RVM is again far sparser than the SVM. Our run uses 200 points of the two-moons data (scikit-learn’s make_moons with noise 0.30.3), a bias and one Gaussian kernel of width 0.50.5 per point, 2000 test points from the same generator, and an SVM with the same kernel and CC from 5-fold cross-validation. Tipping’s run uses 100 points of Ripley’s two-class mixture, a Gaussian kernel and 1000 test points (Tipping, 2001, Section 4.2).

RVMSVM
two moons: vectors kept794
two moons: test error0.1090.1090.09650.0965
Ripley (Tipping): vectors kept438
Ripley (Tipping): test error9.3%9.3\%10.6%10.6\%

On the two moons the RVM ran 279 iterations. Its test log-loss is 0.2770.277 with plug-in probabilities and 0.2570.257 with moderated ones. Tipping also observed that the relevance vectors lie away from the decision boundary, as prototypes of their classes rather than as boundary points. The two experiments differ in data and settings, and neither ranks the methods; both show the difference in sparsity.

What the Laplace approximation misses#

The approximation looks at one point of the posterior: its location and its curvature there. Whatever the posterior does away from the mode is invisible to it.

Figure

What the Laplace approximation misses

What the Laplace approximation missesLeft: the skewed density Beta(4, 2) on 0 to 1 and a symmetric Gaussian centred at 0.75 with 12% of its mass beyond 1. Right: a posterior with two equal peaks at ±1.40 and the Laplace Gaussian, which covers only the right peak.skewed: Beta(4, 2)1200.51bimodal: the sign of θ is unknown12−2−1012exact posteriorLaplace approximationWhat the Laplace approximation missesLeft: the skewed density Beta(4, 2) on 0 to 1 and a symmetric Gaussian centred at 0.75 with 12% of its mass beyond 1. Right: a posterior with two equal peaks at ±1.40 and the Laplace Gaussian, which covers only the right peak.skewed: Beta(4, 2)1200.51bimodal: the sign of θ is unknown12−2−1012exact posteriorLaplace approximation
Left: Beta(4, 2), a coin after three heads and one tail under a uniform prior, and its Laplace approximation N(0.75, 0.2165²), with 12.4% of its mass above 1 (shaded). Right: only θ² is observed (t = 2, noise 0.5, prior N(0, 2²)); the Laplace Gaussian at the right mode, standard deviation 0.178, covers one of two peaks.

The coin’s Beta(4,2)\mathrm{Beta}(4, 2) is skewed and bounded. Its mode is 0.750.75 and its mean 0.6670.667, and its density is zero above 1. The Gaussian is symmetric, centred at the mode, and puts 12.4%12.4\% of its mass on the impossible values p>1p \gt 1. In the logistic example the same skewness made the moderation slightly too strong.

The result also depends on the coordinates, because the mode and the curvature do. Apply the method to the log-odds η=log⁡p1−p\eta = \log\frac{p}{1 - p} instead of pp. The posterior density of η\eta is proportional to p4(1−p)2p^4(1 - p)^2, the old density times the Jacobian p(1−p)p(1 - p), so its log-density is 4log⁡p+2log⁡(1−p)4\log p + 2\log(1 - p) with dp/dη=p(1−p)dp/d\eta = p(1 - p). Its derivative in η\eta is 4(1−p)−2p4(1 - p) - 2p, zero at p=2/3p = 2/3, η=log⁡2\eta = \log 2; differentiating 4−6p4 - 6p once more gives −6p(1−p)-6p(1 - p), so the curvature is H=6⋅23⋅13=4/3H = 6 \cdot \frac23 \cdot \frac13 = 4/3. Mapped back to pp, the two approximations of the same posterior compare as follows:

Laplace in ppLaplace in η\etaexact
mean of pp0.750.750.6450.6450.6670.667
standard deviation of pp0.2170.2170.1740.1740.1780.178
mass outside [0,1][0, 1]12.4%12.4\%nonenone
evidence0.05720.05720.04760.04760.050.05

On an unbounded scale the posterior is closer to Gaussian, and every number improves. Choosing the parametrization is part of the modelling (Murphy, 2023, Section 7.4.3; Bishop, 2006, Section 4.4).

Several modes are the hardest case. Suppose only θ2\theta^2 is observed: t=2t = 2 with noise standard deviation 0.50.5 and the prior N(0,22)\mathcal N(0, 2^2). The posterior has two equal peaks at ±1.403\pm 1.403, and its standard deviation is 1.3771.377. The Laplace approximation at the positive mode, N(1.403, 0.1782)\mathcal N(1.403,\ 0.178^2), represents half of the mass and reports a standard deviation about eight times too small. The same symmetry appears in mixtures, by relabelling the components, and in neural networks, by permuting hidden units, whose posteriors have very many equivalent modes.

Two smaller failures complete the list. The curvature at the mode says nothing about how slowly the density decays far away, so heavy tails are lost, and a nearly flat direction gives a nearly singular HH. And the Hessian costs O(d2)O(d^2) memory and O(d3)O(d^3) time to invert, so large models replace it by its diagonal or by low-rank or Kronecker-factored forms, which adds another layer of approximation.

The approximation is good when the posterior is close to Gaussian: unimodal, with many observations per parameter. The Bernstein–von Mises theorem says that this is what happens as the sample grows, under regularity conditions. Log-concave posteriors, such as that of logistic regression, have a single mode, since the maxima of a concave function form a convex set, and light tails: beyond the mode a concave log-density lies below its tangent line, whose slope there is negative, so it falls at least linearly and the density at least exponentially. When these conditions fail, the next part of the course offers two alternatives. Variational inference chooses a Gaussian or another tractable family by minimizing a divergence to the whole posterior instead of matching one point. Sampling methods, such as Gibbs sampling and the Markov chain Monte Carlo of the probability course, can represent any shape at the price of computation.

What you should remember#

  • Laplace: N(θ^,H−1)\mathcal N(\hat\theta, H^{-1}) with H=−∇∇log⁡p~(θ^)H = -\nabla\nabla\log\tilde p(\hat\theta); Z≈p~(θ^) (2π)d/2det⁡(H)−1/2Z \approx \tilde p(\hat\theta)\,(2\pi)^{d/2}\det(H)^{-1/2}.
  • Logistic regression: Hessian −(Φ⊤B Φ+αI)-(\Phi^\top B\,\Phi + \alpha I), B=diag⁡(yi(1−yi))B = \operatorname{diag}(y_i(1 - y_i)); concave, so Newton finds the mode.
  • Moderated output σ(κμa)\sigma(\kappa\mu_a), κ=(1+πsa2/8)−1/2\kappa = (1 + \pi s_a^2/8)^{-1/2}: same boundary, less confidence where ww is uncertain.
  • RVM classification: the regression updates with the Laplace mean and covariance.
  • Misses skewness, bounded support and other modes; depends on the parametrization.
  • Good for unimodal, nearly Gaussian posteriors with many data.

Code#

The Laplace approximation of two posteriors and of a reparametrized one, Bayesian logistic regression with one weight and with two, the moderated output against the exact predictive, and relevance vector classification on two moons with an SVM on the same data. The script runs in about a second; exact numbers can differ in the last digit across platforms and library versions.

import numpy as np
from scipy import stats, integrate
from scipy.special import expit
from sklearn.datasets import make_moons
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV

# Laplace on a skewed posterior: Beta(4, 2), a coin after 3 heads and 1 tail under a uniform prior
mode = 3 / 4                                          # the maximum of 3 log p + log(1 - p)
H = 3 / mode ** 2 + 1 / (1 - mode) ** 2               # minus its second derivative at the mode
Z = mode ** 3 * (1 - mode) * np.sqrt(2 * np.pi / H)   # Laplace's estimate of the normalizer B(4, 2) = 1/20
print(round(H, 3), round(1 / np.sqrt(H), 4), round(Z, 5), round(Z / 0.05, 3))       # 21.333 0.2165 0.05724 1.145
print(round(stats.beta(4, 2).mean(), 4), round(stats.beta(4, 2).std(), 4), round(stats.norm(mode, 1 / np.sqrt(H)).sf(1), 4))
# 0.6667 0.1782 0.1241: the true mean and sd; the Laplace mass above 1

# the same posterior in the log-odds eta: density p^4 (1 - p)^2, mode at p = 2/3, curvature 6 p (1 - p) = 4/3
eta, He = np.log(2), 4 / 3
f = lambda e: expit(e) ** 4 * expit(-e) ** 2
q = stats.norm(eta, 1 / np.sqrt(He))
m = integrate.quad(lambda e: expit(e) * q.pdf(e), -30, 30)[0]
sdp = np.sqrt(integrate.quad(lambda e: (expit(e) - m) ** 2 * q.pdf(e), -30, 30)[0])
print(round(m, 3), round(sdp, 3), round(f(eta) * np.sqrt(2 * np.pi / He), 4))      # 0.645 0.174 0.0476

# a bimodal posterior: t = theta^2 + noise, t = 2 observed with noise sd 0.5, prior N(0, 2^2)
logp = lambda th: -(2 - th ** 2) ** 2 / (2 * 0.25) - th ** 2 / 8
th_hat = np.sqrt(2 - 1 / 32)                          # the positive mode: 8 (2 - theta^2) = 1/4
H2 = -(8 * (2 - th_hat ** 2) - 16 * th_hat ** 2 - 0.25)   # minus the second derivative of logp at the mode
Zp = integrate.quad(lambda v: np.exp(logp(v)), -6, 6)[0]
sd_exact = np.sqrt(integrate.quad(lambda v: v ** 2 * np.exp(logp(v)), -6, 6)[0] / Zp)
print(round(th_hat, 4), round(H2, 3), round(1 / np.sqrt(H2), 4), round(sd_exact, 4))   # 1.4031 31.5 0.1782 1.377: the Laplace sd against the exact posterior sd

# Bayesian logistic regression with one weight, prior N(0, 1): Newton's method to the mode, then the Hessian
x = np.array([-1.5, -0.5, 0.5, 1.0, 2.0]); t = np.array([0, 1, 0, 1, 1.0]); alpha = 1.0
w = 0.0
for k in range(1, 5):
    y = expit(w * x)
    w = w + (x @ (t - y) - alpha * w) / (x ** 2 @ (y * (1 - y)) + alpha)   # w - gradient / Hessian
    print(k, round(w, 5))                             # 1 0.59574 | 2 0.63021 | 3 0.63048 | 4 0.63048
y = expit(w * x)
H1 = x ** 2 @ (y * (1 - y)) + alpha                   # the precision of the Laplace approximation
mu_a, s2 = 3 * w, 9 / H1                              # the activation w x* at x* = 3: mean and variance
kappa = 1 / np.sqrt(1 + np.pi * s2 / 8)
gauss = integrate.quad(lambda a: expit(a) * stats.norm(mu_a, np.sqrt(s2)).pdf(a), -40, 40)[0]
post = lambda v: np.exp(np.sum(t * np.log(expit(v * x)) + (1 - t) * np.log(expit(-v * x))) - alpha * v * v / 2)
Zw = integrate.quad(post, -20, 20)[0]
exact = integrate.quad(lambda v: expit(3 * v) * post(v), -20, 20)[0] / Zw
print(round(H1, 4), round(mu_a, 4), round(s2, 4), round(kappa, 4))                 # 2.4902 1.8914 3.6141 0.6429
print(round(expit(mu_a), 4), round(expit(kappa * mu_a), 4), round(gauss, 4), round(exact, 4))   # 0.8689 0.7714 0.7693 0.7899
m1 = integrate.quad(lambda v: v * post(v), -20, 20)[0] / Zw
m2, m3 = (integrate.quad(lambda v: (v - m1) ** k * post(v), -20, 20)[0] / Zw for k in (2, 3))
print(round(m1, 4), round(m3 / m2 ** 1.5, 3))        # 0.7091 0.211: the exact posterior mean is right of the mode, and skewed

# the same in one dimension with a bias, phi(x) = (1, x): MAP, moderated and exact predictive probabilities
rng = np.random.default_rng(4)
x = np.concatenate([rng.normal(-1, 1, 3), rng.normal(1, 1, 3)]).round(2); t = np.repeat([0, 1.0], 3)
Phi = np.stack([np.ones(6), x], axis=1)
w = np.zeros(2)
for _ in range(30):                                   # Newton's method in two dimensions (IRLS)
    y = expit(Phi @ w)
    w = w + np.linalg.solve(Phi.T @ (Phi * (y * (1 - y))[:, None]) + np.eye(2), Phi.T @ (t - y) - w)
y = expit(Phi @ w)
S = np.linalg.inv(Phi.T @ (Phi * (y * (1 - y))[:, None]) + np.eye(2))
print(x, w.round(4), S.round(4).tolist())            # [-1.65 -1.17  0.66  1.66 -0.64  0.99] [0.0099 0.694 ] [[0.4393, 0.0047], [0.0047, 0.3687]]
g = np.linspace(-8, 8, 321); U, V = np.meshgrid(g, g)
W = w[:, None] + np.linalg.cholesky(S) @ np.stack([U.ravel(), V.ravel()])   # a grid over the weights, in whitened coordinates
lp = (t[:, None] * np.log(expit(Phi @ W)) + (1 - t[:, None]) * np.log(expit(-(Phi @ W)))).sum(0) - (W ** 2).sum(0) / 2
p = np.exp(lp - lp.max()); p /= p.sum()               # the exact posterior on the grid
for xs in (0, 1, 3):
    f1 = np.array([1, xs]); m, v = f1 @ w, f1 @ S @ f1
    print(xs, round(expit(m), 3), round(expit(m / np.sqrt(1 + np.pi * v / 8)), 3), round(float(p @ expit(f1 @ W)), 3))
# 0 0.502 0.502 0.502 | 1 0.669 0.649 0.663 | 3 0.89 0.79 0.814: MAP, moderated, exact

# RVM classification on two moons: Laplace inside the evidence loop, Gaussian kernels of width 0.5
X, t = make_moons(200, noise=0.3, random_state=0)
Xt, tt = make_moons(2000, noise=0.3, random_state=1)
K = lambda P, Q: np.exp(-((P[:, None, :] - Q[None]) ** 2).sum(-1) / (2 * 0.5 ** 2))
Phi = np.hstack([np.ones((200, 1)), K(X, X)])

def laplace(P, t, a, w):
    """Newton's method to the mode of the log-posterior; returns the mode and the Laplace covariance."""
    for _ in range(50):
        y = expit(P @ w)
        step = np.linalg.solve(P.T @ (P * (y * (1 - y))[:, None]) + np.diag(a), P.T @ (t - y) - a * w)
        w = w + step
        if np.max(np.abs(step)) < 1e-8: break
    y = expit(P @ w)
    return w, np.linalg.inv(P.T @ (P * (y * (1 - y))[:, None]) + np.diag(a))

alpha, keep, w = np.ones(201), np.arange(201), np.zeros(201)
for it in range(1, 501):
    wk, S = laplace(Phi[:, keep], t, alpha[keep], w[keep])
    new = (1 - alpha[keep] * np.diag(S)) / wk ** 2    # the regression updates, with the Laplace mean and covariance
    change = np.max(np.abs(np.log(new / alpha[keep])))
    alpha[keep] = new; w[:] = 0; w[keep] = wk
    keep = keep[new < 1e9]
    if change < 1e-4: break
wk, S = laplace(Phi[:, keep], t, alpha[keep], w[keep])
Pt = np.hstack([np.ones((2000, 1)), K(Xt, X)])[:, keep]
m, v = Pt @ wk, np.einsum('ij,jk,ik->i', Pt, S, Pt)
nll = lambda q: round(-np.mean(tt * np.log(q) + (1 - tt) * np.log(1 - q)), 4)
print(it, len(keep), round(np.mean((m > 0) != tt), 4), nll(expit(m)), nll(expit(m / np.sqrt(1 + np.pi * v / 8))))
# 279 7 0.109 0.2771 0.2566: 7 relevance vectors, test error, test log-loss of the MAP and the moderated output
svc = GridSearchCV(SVC(kernel='rbf', gamma=1 / (2 * 0.5 ** 2)), {'C': [0.1, 0.3, 1, 3, 10, 30, 100]}, cv=5).fit(X, t)
print(svc.best_params_, len(svc.best_estimator_.support_), round(1 - svc.score(Xt, tt), 4))   # {'C': 0.3} 94 0.0965

Next#

The Laplace approximation replaced an intractable posterior by a Gaussian fitted at one point. Many models are intractable for a different reason: they contain hidden variables, such as the component of a mixture or the low-dimensional coordinates of a data point, and the evidence is an integral over them. The next note returns to the EM algorithm as the general tool for such models, and uses the ARD idea of the relevance vector machine to let Bayesian PCA choose its own number of components.

References#