Module contents
Lesson 7 of 27Core 90 min

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 h(θ)=log⁡p(D,θ)h(\theta)=\log p(\Data,\theta) be twice differentiable and let θ^\hat\theta be an interior maximum. The second-order Taylor expansion is

h(θ)≈h(θ^)−12(θ−θ^)⊤H(θ−θ^),H=−∇2h(θ^).h(\theta)\approx h(\hat\theta)-\tfrac12 (\theta-\hat\theta)\T\mat{H}(\theta-\hat\theta),\quad \mat{H}=-\nabla^2h(\hat\theta).

The linear term vanishes because the gradient is zero. If H\mat{H} is positive definite, exponentiating and normalizing yields q(θ)=N(θ^,H−1)q(\theta)=\Normal(\hat\theta,\mat{H}^{-1}). 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.

InteractiveA Gaussian at the mode
  • Exact density
  • Local Laplace

Gamma(2, rate 1), Beta(1.5, 5), or an equally weighted mixture of normals with means ±2 and standard deviation 0.65. Log is used for Gamma and logit for Beta. The mixture shows only one local approximation, even when the switch is on.

Original mode1.000
Original local standard deviation1.000
Compare the exact density with the local approximation and change coordinates for positive or bounded supports.

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 t=log⁡θt=\log\theta maps the positive support to the whole real line. The transformed density includes the Jacobian: pt(t)=pθ(et)etp_t(t)=p_\theta(e^t)e^t. Fit Laplace in tt and return to θ\theta by dividing by θ\theta. For Beta, logit maps (0,1)(0,1) to the real line and introduces the Jacobian θ(1−θ)\theta(1-\theta). 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 θ=et\theta=e^t, a small interval  ⁣dt\dd t corresponds approximately to  ⁣dθ=et ⁣dt\dd\theta=e^t\dd t; hence the Jacobian. In the Gamma example, the density in θ\theta has mode one, whereas the density of tt has mode log⁡2\log 2. 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 yiy_i and rows xi⊤\vb{x}_i\T of X\mat{X}, use

p(yi=1∣w)=σ(xi⊤w),w∼N(0,α−1I),α>0.p(y_i=1\given\vb{w})=\sigma(\vb{x}_i\T\vb{w}),\qquad \vb{w}\sim\Normal(\vb{0},\alpha^{-1}\mat{I}),\quad\alpha>0.

The sigmoid is σ(z)=(1+e−z)−1\sigma(z)=(1+e^{-z})^{-1}. With pi=σ(xi⊤w)p_i=\sigma(\vb{x}_i\T\vb{w}), the negative log posterior, up to constants independent of the weights, has gradient and Hessian

∇L=X⊤(p−y)+αw,H=X⊤RX+αI,Rii=pi(1−pi).\nabla L=\mat{X}\T(\vb{p}-\vb{y})+\alpha\vb{w},\qquad \mat{H}=\mat{X}\T\mat{R}\mat{X}+\alpha\mat{I}, \quad R_{ii}=p_i(1-p_i).

Bayesian logistic regression with an isotropic Gaussian prior has a strictly convex objective for α>0\alpha>0: H\mat{H} is positive definite even with collinear predictors or separable data. The prior also regularizes the intercept if the column of ones is included in X\mat{X} and the prior applies to all coordinates. This detail must match when comparing implementations.

Newton solves HΔ=∇L\mat{H}\Delta=\nabla L and proposes wnuevo=w−Δ\vb{w}_{\rm nuevo}=\vb{w}-\Delta. 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, log⁡(1+eai)−yiai\log(1+e^{a_i})-y_i a_i. Its derivative with respect to aia_i is pi−yip_i-y_i and its second derivative is pi(1−pi)p_i(1-p_i). The chain rule multiplies by xi\vb x_i and xixi⊤\vb x_i\vb x_i\T, respectively. The prior contributes αw\alpha\vb w to the gradient and αI\alpha\mat I to the Hessian. Since pi(1−pi)≥0p_i(1-p_i)\ge0, for any nonzero vector v\vb v we have v⊤Hv≥α∥v∥2>0\vb v\T\mat H\vb v\ge\alpha\norm{\vb v}^2>0.

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.

InteractiveMAP versus moderated prediction

Synthetic data from two clouds, with fixed generator and seed. Contours: orange 0.1, gray 0.5, blue 0.9; orange and blue points are classes 0 and 1. The intercept is fitted with the same prior as the weights. The predictive distribution is an approximation, not a guarantee of out-of-distribution calibration.

1.0
P(class 1) MAP at (3,0)0.984
P(class 1) moderated at (3,0)0.926
Drag the data and compare the MAP contours with those of the Laplace and probit predictive distribution.

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 q(w)=N(m,S)q(\vb w)=\Normal(\vb m,\mat S), the logit a=x⊤wa=\vb x\T\vb w is normal with mean μ=x⊤m\mu=\vb x\T\vb m and variance s2=x⊤Sxs^2=\vb x\T\mat S\vb x. The Laplace-approximated predictive distribution is

∫σ(a)N(a∣μ,s2)  ⁣da.\int\sigma(a)\Normal(a\given\mu,s^2)\,\dd a.

There is no elementary form for this integral. The probit approximation uses σ(a)≈Φ(κa)\sigma(a)\approx\Phi(\kappa a) with κ=π/8\kappa=\sqrt{\pi/8}, chosen to match slopes at zero. If A∼N(μ,s2)A\sim\Normal(\mu,s^2) and Z∼N(0,1)Z\sim\Normal(0,1) is independent, EΦ(κA)=P(Z≤κA)=Φ(κμ/1+κ2s2)\E\Phi(\kappa A)=P(Z\le\kappa A)=\Phi(\kappa\mu/\sqrt{1+\kappa^2s^2}). Approximating the probit again with a sigmoid gives

p(y=1∣x,D)≈σ ⁣(μ1+πs2/8).p(y=1\given\vb x,\Data)\approx \sigma\!\left(\frac{\mu}{\sqrt{1+\pi s^2/8}}\right).

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 μ\mu, greater variance moves this approximation toward 0.5. By contrast, moving away along a ray x=tv\vb x=t\vb v, both the mean and standard deviation can grow proportionally to tt: 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.

InteractiveA bundle of boundaries

Each blue line corresponds to a weight sampled from the Laplace Gaussian; orange is the MAP boundary. The data are synthetic and nested. Adding data usually reduces uncertainty, but its effect need not be monotonic in every direction or realization.

4
Boundaries shown: 30
Logit standard deviation at (1,1)1.388
Visible samples30
Add synthetic data and observe 30 boundaries for weights sampled from the Laplace posterior.

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 dd parameters and an interior mode,

log⁡p(D)≈h(θ^)+d2log⁡(2π)−12log⁡det⁡H.\log p(\Data)\approx h(\hat\theta)+\frac d2\log(2\pi) -\frac12\log\det\mat H.

Here hh 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 eh(θ^)e^{h(\hat\theta)} times an unnormalized bell curve, whose integral is (2π)d/2det⁡(H)−1/2(2\pi)^{d/2}\det(\mat H)^{-1/2}. 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.

[ ]Logistic engine and synthetic dataBrowser
"""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_w
[ ]Fit and check the HessianBrowser
X,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.

[ ]Probit prediction, Monte Carlo and ECEBrowser
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.

[ ]Compare the MAP with scikit-learnLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Beta-binomial evidenceBrowser
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

ProofIntegrating the probit
Prove: Derive the approximate formula for the Gaussian logistic predictive distribution by matching a probit's slope at zero.
0
A is normal N(μ,s²), Z is an independent standard normal, and σ(a)≈Φ(κa).

Step 1 of 3. Which value of κ matches the slopes at zero?

Numeric
With a uniform Beta(1,1) prior, you observe 7 successes in 10 trials and record only the count. What is the Laplace-approximated log evidence in θ, including the binomial coefficient? Give the result in nats.
Quiz
A posterior for a positive parameter concentrates mass near zero. Which option is worth trying before accepting a local Gaussian?
CodeLaplace logistic posterior
Implement laplace_logreg(X,y,alpha): an N(0,I/alpha) prior over all columns, MAP by Newton, and the inverse Hessian covariance. Return (mean,covariance). The tests use alpha>0 and check the gradient and Hessian by central differences.
import numpy as np
from scipy.special import expit
def laplace_logreg(X,y,alpha):
  return None,None
Shift+Enter to run
Key idea
Laplace uses the curvature at the MAP to approximate uncertainty; integrating the predictive distribution and checking support, Hessian and multimodality avoids interpreting a point solution as certainty.