The Laplace approximation and Bayesian logistic regression
When the likelihood is no longer Gaussian, the posterior loses its closed form. The Laplace approximation replaces it with a Gaussian centered on the MAP, using the curvature of the log posterior. We apply it to Bayesian logistic regression, obtain the moderated predictive distribution using the probit approximation, and estimate the evidence.
After this lesson you can
- Construct the Laplace approximation from the MAP and the Hessian of the log posterior.
- Implement Bayesian logistic regression with Newton (IRLS) and Laplace.
- Derive the probit approximation to the predictive distribution and compare its probabilities with the MAP probabilities.
- Estimate log evidence with Laplace and understand its failure modes, including asymmetry, multimodality and support boundaries.
Before you start
A distribution around the solution
A logistic classifier with a single weight vector can produce probabilities very close to zero or one even where data are scarce. A prior and a posterior over the weights let us express that several boundaries are compatible with the observations. To predict, we average the probabilities of those boundaries, not just the probability of the maximum-density boundary.
The logistic posterior has no closed Gaussian form. The Laplace approximation replaces it with a local Gaussian centered on the MAP. It is a fast, useful method when there is a well-defined interior mode and the log posterior is approximately quadratic near it.
A Gaussian at the mode
Let be twice differentiable and let be an interior maximum. The second-order Taylor expansion is
The linear term vanishes because the gradient is zero. If is positive definite, exponentiating and normalizing yields . In one dimension, the variance is the inverse of the negative curvature. If curvature is small, the local Gaussian is wide; if the point is not a maximum or the Hessian is singular, this interpretation fails.
The figure uses Gamma with shape 2 and rate 1, Beta(1.5,5), and an equally weighted mixture of two normals. For Gamma, the transformation maps the positive support to the whole real line. The transformed density includes the Jacobian: . Fit Laplace in and return to by dividing by . For Beta, logit maps to the real line and introduces the Jacobian . The mode depends on the coordinate: maximizing the transformed density is generally not equivalent to transforming the original mode.
The transformation may represent a tail or boundary better, but it does not guarantee an accurate approximation. In the mixture, a Gaussian fitted to one mode ignores the other and underestimates part of the uncertainty. The drawing uses a local approximation around the negative mixture mean, practically its mode in this example; it does not make a bimodal posterior unimodal. Examine asymmetry, support and modes before interpreting a covariance.
The local calculation answers a specific question: how does the log density change under small perturbations around the mode? It does not use the complete shape of the tails. An exact curve and a Gaussian can have the same curvature at the maximum and differ far from it, particularly when the support has a boundary. The normalized approximation need not match the height of the exact density at the mode either: its constant is determined by making the Gaussian integrate to one.
A transformation changes the measure with respect to which a density is expressed. If , a small interval corresponds approximately to ; hence the Jacobian. In the Gamma example, the density in has mode one, whereas the density of has mode . Fitting a normal around each yields different approximations. Returning to the original scale produces a positive distribution, not a symmetric normal.
Bayesian logistic regression
For binary observations and rows of , use
The sigmoid is . With , the negative log posterior, up to constants independent of the weights, has gradient and Hessian
Bayesian logistic regression with an isotropic Gaussian prior has a strictly convex objective for : is positive definite even with collinear predictors or separable data. The prior also regularizes the intercept if the column of ones is included in and the prior applies to all coordinates. This detail must match when comparing implementations.
Newton solves and proposes . The IRLS formulation interprets each iteration as a weighted least-squares problem; both give the same step when solved exactly. A descending line search avoids accepting a Newton step that increases the loss. Check the gradient, convergence and positive definiteness of the Hessian before using its inverse as the Laplace covariance.
The derivation starts with the negative contribution of each observation, . Its derivative with respect to is and its second derivative is . The chain rule multiplies by and , respectively. The prior contributes to the gradient and to the Hessian. Since , for any nonzero vector we have .
Without a proper prior, perfectly separable data can make the likelihood improve as the norm of the weights grows without bound, without attaining a finite maximum. The Gaussian prior penalizes that growth. This does not mean that the chosen prior is right for every problem: its scale determines how much the weights shrink and how much prior information weighs against the data.
The Newton step does not require forming an explicit inverse. Solve the linear system with a Cholesky factorization; to obtain the full covariance in a small example you can solve against the identity. In high dimensions it is often useful to solve only for inverse products or use structured approximations. An ill-conditioned Hessian, feature scaling errors or interrupted optimization can produce misleading uncertainty even when the algebraic formula is correct.
The figure’s data are two synthetic clouds of eight points with fixed labels, and the MAP and Hessian are recalculated when they move. The contours are probability levels 0.1, 0.5 and 0.9. The 0.5 level line coincides because the moderating denominator is positive and does not change the sign of the logit; the other contours can change.
Predicting by integrating over weights
For a new input, under the Gaussian posterior , the logit is normal with mean and variance . The Laplace-approximated predictive distribution is
There is no elementary form for this integral. The probit approximation uses with , chosen to match slopes at zero. If and is independent, . Approximating the probit again with a sigmoid gives
This approximates the integral under the Laplace Gaussian, not an identity for the exact posterior. With zero variance it matches the MAP prediction. For fixed , greater variance moves this approximation toward 0.5. By contrast, moving away along a ray , both the mean and standard deviation can grow proportionally to : the limit can differ from 0.5. Uncertainty about weights moderates confidence, but does not guarantee that every distant input is recognized as unknown or that the prior represents distribution shifts.
There are two distinct approximations in this chain. First we replace the true posterior over weights with a local normal. Then we replace the logistic-normal integral with the probit formula. A comparison with Monte Carlo weights sampled from that same normal checks the second step; to evaluate the first we would need, for example, a numerical reference or sufficiently diagnosed sampling of the original posterior.
The mean probability and the variance of the weights do not answer the same question either. Two posteriors can give the same predictive mean at one point while differing greatly in their weight distributions and decisions at other points. If the population distribution changes, ECE measured on a split with the same generating mechanism does not ensure good behavior in the new population.
Each blue line is the boundary of a weight vector sampled from the Gaussian; the orange line corresponds to the MAP. They do not represent individual data probabilities. More information usually reduces uncertainty, but the reduction need not be monotonic in every direction with each new dataset and a changing MAP.
Evidence and complexity
The Laplace evidence approximates the integral of the product of likelihood and prior. For parameters and an interior mode,
Here includes the normalization constants of the prior and likelihood; they cannot be omitted when comparing models. The volume term favors parameter regions that explain the data with appreciable prior probability, not just the best point fit. It is often called the Occam factor, but it is not an isolated universal penalty: it depends on the prior scale, Hessian and parameterization of the integral.
If there are several separated modes, it may be necessary to sum local contributions instead of using one. Near a boundary, the Gaussian may assign mass outside the support and the integral formula over the whole real line may fail. Transforming parameters requires including the Jacobian before optimizing again; using the same mode on both scales without that adjustment is incorrect. Approximate evidence can be sensitive to posterior shape even when the MAP is stable.
The formula comes from integrating the exponential of the Taylor quadratic: around the mode the integrand is approximated by times an unnormalized bell curve, whose integral is . Comparing models requires specifying their proper priors and the same definition of observed data. In a binomial, for example, the probability of a count includes the number of sequences with that count; the probability of a particular sequence does not include that factor.
For more detail, Tierney and Kadane study approximations for posterior moments and marginals; Murphy develops inference and Bayesian logistic regression in his text. MacKay’s treatment of evidence in classification networks shows the connection with model comparison.
Lab: MAP, Laplace and calibration
The following engine implements the stable loss with logaddexp, Newton with line search, covariance and the probit predictive distribution. It generates 40 synthetic Bernoulli observations and 2000 test observations using an explicit seed and true weights; these are not real measurements. The column of ones receives the same prior as the others. The code is self-contained and matches the lesson module.
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit
def negative_log_posterior(w, X, y, alpha):
z = X @ w
p = expit(z)
value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
gradient = X.T @ (p-y) + alpha*w
H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
return value, gradient, H
def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
raise ValueError('dimensiones incompatibles')
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
w=np.zeros(X.shape[1]); converged=False
for iteration in range(max_iter):
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:
converged=True;break
direction=np.linalg.solve(H,gradient)
rate=1.
while rate>1e-12:
candidate=w-rate*direction
if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
break
rate*=.5
if rate<=1e-12:break
w=candidate
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:converged=True
cov=np.linalg.solve(H,np.eye(X.shape[1]))
return w,cov,{'converged':converged,'iterations':iteration+1,
'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}
def predict_probit(X, mean, covariance):
X=np.asarray(X,dtype=float)
variance=np.einsum('ij,jk,ik->i',X,covariance,X)
return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))
def synthetic_data(seed=2026,n_train=40,n_test=2000):
"""Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
rng=np.random.default_rng(seed)
true_w=np.array([-.4,1.4,-1.])
def generate(n):
X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
y=rng.binomial(1,expit(X@true_w))
return X,y
X,y=generate(n_train);X_test,y_test=generate(n_test)
return X,y,X_test,y_test,true_wX,y,X_test,y_test,true_w=synthetic_data(seed=2026,n_train=40,n_test=2000)
alpha=1.5
mean,cov,info=fit_laplace(X,y,alpha)
value,gradient,H=negative_log_posterior(mean,X,y,alpha)
eps=1e-5
basis=np.eye(X.shape[1])
H_fd=np.column_stack([(negative_log_posterior(mean+eps*v,X,y,alpha)[1]
-negative_log_posterior(mean-eps*v,X,y,alpha)[1])/(2*eps)
for v in basis])
print('MAP:',mean,'estado:',info)
print('autovalor mínimo del hessiano:',np.linalg.eigvalsh(H).min())
print('error máximo del hessiano por diferencias centrales:',np.max(abs(H-H_fd)))
assert info['converged'] and np.allclose(H,H_fd,atol=1e-7)The test set consists of 2000 new observations from the same synthetic mechanism; it was not used for training. In ten equal-width bins, empirical expected calibration error (ECE) weights the absolute difference between confidence and class frequency by their frequency. It depends on binning and sample size; it does not prove out-of-distribution calibration.
def ece(y,p,bins=10):
index=np.minimum((p*bins).astype(int),bins-1)
total=len(y);error=0.
for b in range(bins):
mask=index==b
if mask.any():
error+=mask.sum()/total*abs(p[mask].mean()-y[mask].mean())
return error
map_probability=expit(X_test@mean)
probit_probability=predict_probit(X_test,mean,cov)
rng=np.random.default_rng(7)
weights=rng.multivariate_normal(mean,cov,size=5000)
mc_probability=np.empty(len(X_test))
for i in range(0,len(X_test),200):
mc_probability[i:i+200]=expit(X_test[i:i+200]@weights.T).mean(axis=1)
print('ECE MAP, probit y Monte Carlo:',ece(y_test,map_probability),
ece(y_test,probit_probability),ece(y_test,mc_probability))
print('error medio y máximo de probit respecto a Monte Carlo:',
np.mean(abs(probit_probability-mc_probability)),
np.max(abs(probit_probability-mc_probability)))Monte Carlo also uses the approximate Laplace posterior: it compares the numerical integral with the probit formula, not the exact posterior. ECEs from a single realization do not guarantee that one of the three predictions always wins. Repeating with other seeds and sizes reveals variability.
import numpy as np
from scipy.special import expit
from scipy.optimize import minimize
from sklearn.linear_model import LogisticRegression
rng=np.random.default_rng(2026)
X=np.column_stack((np.ones(40),rng.normal(size=(40,2))))
y=rng.binomial(1,expit([email protected]([-.4,1.4,-1.])))
alpha=1.5
def loss(w):
z=X@w
return np.logaddexp(0.,z).sum()-y@z+.5*alpha*w@w, X.T@(expit(z)-y)+alpha*w
reference=minimize(loss,np.zeros(3),jac=True,method='BFGS',options={'gtol':1e-9})
sk=LogisticRegression(C=1/alpha,fit_intercept=False,tol=1e-12,max_iter=2000).fit(X,y)
print('gradiente de SciPy:',np.linalg.norm(reference.jac,np.inf))
print('máxima diferencia con scikit-learn:',np.max(abs(reference.x-sk.coef_[0])))
assert np.linalg.norm(reference.jac,np.inf)<1e-6
assert np.allclose(reference.x,sk.coef_[0],atol=1e-5)npm run lab and open the connection link.The local comparison uses the same column of ones and penalizes all coordinates, including the intercept. Comparing with an unpenalized intercept would be a different model. The following calculation distinguishes observing a count of successes from observing an ordered sequence: the binomial likelihood of the count includes the combinatorial coefficient.
from scipy.special import betaln, gammaln
k,n=7,10
mode=k/n
H=k/mode**2+(n-k)/(1-mode)**2
log_choose=gammaln(n+1)-gammaln(k+1)-gammaln(n-k+1)
exact=log_choose+betaln(k+1,n-k+1)
laplace=log_choose+k*np.log(mode)+(n-k)*np.log1p(-mode)+.5*np.log(2*np.pi/H)
print('log evidencia exacta y Laplace para el conteo:',exact,laplace)Exercises
Step 1 of 3. Which value of κ matches the slopes at zero?
import numpy as np
from scipy.special import expit
def laplace_logreg(X,y,alpha):
return None,None