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, , is fitted to five points and asked about a new input at . With the fitted weight it answers . 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 . 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 , 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 be the unknowns and the unnormalized posterior. Its normalizer is the evidence . Near its maximum, any smooth log-density looks like a parabola, and a density whose logarithm is a parabola is a Gaussian. So expand to second order around the mode . The linear term vanishes there, because the gradient is zero:
where is the negative Hessian at the mode. Exponentiated, the right side is times an unnormalized Gaussian, and the Gaussian integral with no linear term, , gives its normalizer:
The approximation needs a smooth and a positive definite . At any local maximum is positive semidefinite, the second-order necessary condition; positive definite is the stronger requirement of a nondegenerate maximum. The density has a strict maximum at 0 with , and there the Gaussian has infinite variance. Its ingredients are an optimizer, which finds , 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 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 , with . The derivative vanishes at , and
| Quantity | Value |
|---|---|
| standard deviation | |
| evidence estimate | |
| exact evidence |
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 , a design matrix with rows , targets and the prior . With the predicted probability of class 1, the log-posterior is
Its gradient is the residuals times the inputs minus the prior term. Differentiating once more with , from , gives
where . The Hessian is negative definite for every : for any , . 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 as . Newton’s method finds it, with quadratic convergence near the mode and a damped step that guarantees ascent far from it:
with and at the current . Multiplying by shows what each step solves:
These are the normal equations of ridge regression on the working targets , with weight on point . Each step solves a weighted least-squares problem whose weights change with , which is why the method is also called iteratively reweighted least squares (IRLS). At convergence,
with evaluated at . This is the posterior of regression with the noise precision replaced by a precision for each point. A point the model classifies confidently, with near 0 or 1, adds little curvature; points near the boundary, with near , 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 with , and . From , Newton’s method gives , and , after which the digits stop changing. At the mode,
The standard deviation, , is as large as the mode: the five points favour a positive weight but say little about its size.
The Laplace approximation for logistic regression with one weight
The numbered steps of the figure:
- Newton’s method climbs the concave log-posterior to its mode .
- The curvature at the mode is the precision of the Gaussian approximation.
- At a new input the activation is Gaussian under the approximation.
- 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 only through the activation of the new input. Under the approximation is an affine map of a Gaussian, so it is Gaussian too:
The predictive probability becomes a one-dimensional integral, . 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 for the standard normal distribution function, with a subscript to keep it apart from the design matrix.
First, approximate , with chosen so that the two curves have the same slope at 0. The slopes are and , so .
Next, average the normal distribution function. Let be independent of , with . Then , and is a sum of independent Gaussians with variance :
Finally, turn back to the sigmoid with , now at :
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 , the sign of is the sign of . The decision boundary 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 is large, the probability stays near 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 . And for 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 :
| Quantity | Value |
|---|---|
| , | , |
| plug-in | |
| moderated | |
| exact Gaussian average | |
| exact predictive, averaged over the true posterior |
The probit step costs only . The Laplace approximation recovers most of the correction, from towards , and then goes a little too far.
The moderated output of Bayesian logistic regression
With a bias and six points the pattern holds along the whole axis. At the plug-in gives , the moderated output and the exact predictive ; at , inside the data, , and . The overshoot has a visible cause in the one-weight example. The exact posterior has its mean at , to the right of the mode , and a skewness of : 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 gives the evidence of the prior precisions. Take the prior of the relevance vector machine, with , and let be the mode for the current . Then
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 . At the mode the gradient of the first two terms in is zero, so the dependence through drops out of them; Tipping also neglects it inside . The log-determinant rule gives the last term:
Relevance vector classification alternates:
- for the current , find the mode by Newton’s method, warm-started from the previous mode;
- compute at the mode;
- update and , and prune the features whose passes a large threshold;
- repeat until the precisions settle.
The analogy with regression is exact in one sense. At the mode the gradient is zero, ; adding to both sides gives , the IRLS step at its fixed point, and therefore
This is the regression posterior mean for the targets , with a noise precision 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 ), a bias and one Gaussian kernel of width per point, 2000 test points from the same generator, and an SVM with the same kernel and 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).
| RVM | SVM | |
|---|---|---|
| two moons: vectors kept | 7 | 94 |
| two moons: test error | ||
| Ripley (Tipping): vectors kept | 4 | 38 |
| Ripley (Tipping): test error |
On the two moons the RVM ran 279 iterations. Its test log-loss is with plug-in probabilities and 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.
What the Laplace approximation misses
The coin’s is skewed and bounded. Its mode is and its mean , and its density is zero above 1. The Gaussian is symmetric, centred at the mode, and puts of its mass on the impossible values . 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 instead of . The posterior density of is proportional to , the old density times the Jacobian , so its log-density is with . Its derivative in is , zero at , ; differentiating once more gives , so the curvature is . Mapped back to , the two approximations of the same posterior compare as follows:
| Laplace in | Laplace in | exact | |
|---|---|---|---|
| mean of | |||
| standard deviation of | |||
| mass outside | none | none | |
| evidence |
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 is observed: with noise standard deviation and the prior . The posterior has two equal peaks at , and its standard deviation is . The Laplace approximation at the positive mode, , 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 . And the Hessian costs memory and 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: with ; .
- Logistic regression: Hessian , ; concave, so Newton finds the mode.
- Moderated output , : same boundary, less confidence where 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#
- D. P. Vetrov, D. A. Kropotov. Байесовские методы машинного обучения, lecture course, Moscow State University, 2015. Course page; lecture 4, the relevance vector machine for regression and classification, the Laplace approximation (slides), and lecture 5, Newton’s method, EM and the relevance vector machine for classification (notes).
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 4.4 (the Laplace approximation), Section 4.5 (Bayesian logistic regression; 4.5.2, the probit approximation), Section 7.2.3 (relevance vector machines for classification).
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 7.4.3 (the Laplace approximation and the change of variables), Sections 15.3.5–15.3.6 (Bayesian logistic regression and its predictive distribution).
- D. J. C. MacKay. The Evidence Framework Applied to Classification Networks. Neural Computation, 4(5), 720–736, 1992.
- L. Tierney, J. B. Kadane. Accurate Approximations for Posterior Moments and Marginal Densities. Journal of the American Statistical Association, 81(393), 82–86, 1986.
- M. E. Tipping. Sparse Bayesian Learning and the Relevance Vector Machine. Journal of Machine Learning Research, 1, 211–244, 2001. Section 3 (sparse Bayesian classification), Section 4.2 (Ripley’s data).