Bayesian Neural Networks: Laplace and Evidence Framework

Turn a point-estimate MLP into a Bayesian neural network with the Laplace approximation and the evidence framework. Fit a GELU net with error bars.

Cover Image for Bayesian Neural Networks: Laplace and Evidence Framework

You've trained a small network using backpropagation and gradient descent, and its curve fits the observations well. Outside that range, it still returns a number, even though the data gives you less reason to trust it. Bayesian neural networks let us examine uncertainty around the weights and the predictions, as we previously did with a Gaussian process.

The predictive band hugs the fitted mean within the observations, then widens to roughly ±3 outside their support. We form it with the Laplace approximation, using the earlier curvature calculations for weight uncertainty and the evidence framework to choose modelling settings. That band expresses uncertainty a point prediction leaves out.

By the end, you will be able to take any small MLP, slap a Laplace posterior on it, and extract a principled ±2σ\pm 2\sigma band around every prediction.

Quick Win: A BNN in One Picture

Open In Colab

Fit a two-layer GELU network with 12 hidden units (37 weights and biases) to 25 noisy observations of sin⁡(2πx)\sin(2\pi x). Leave a gap around the origin and no training data beyond ∣x∣>0.9|x| > 0.9, so the model has regions where a sensible posterior should admit uncertainty.

Left: MLE fit (no prior) threading every point. Middle: MAP fit with a Gaussian prior, slightly smoother. Right: Bayesian Laplace fit with a ±2σ band that is tight where data is dense, balloons where data is absent.

The MLE and MAP panels collapse the network to a single w^\hat{\mathbf{w}} and output one number per xx. The Bayesian panel uses the same network, the same architecture, the same activation, but replaces the point estimate with a Gaussian posterior q(w∣D)=N(wMAP,A−1)q(\mathbf{w}\mid \mathcal{D}) = \mathcal{N}(\mathbf{w}_{\text{MAP}}, \mathbf{A}^{-1}) and marginalises at prediction time. The red band is the resulting ±2σ\pm 2\sigma predictive interval. Where the training support has gaps, the band explodes. That is the whole point.

The core code is a few dozen lines of NumPy, SciPy and one torch.autograd.functional.hessian call:

import torch, numpy as np
import torch.nn.functional as F
from torch.autograd.functional import hessian

torch.set_default_dtype(torch.float64); torch.manual_seed(0)
HIDDEN, W = 12, 37  # 37 total parameters

def predict(theta, x):
    W1 = theta[:HIDDEN].view(HIDDEN, 1)
    b1 = theta[HIDDEN:2*HIDDEN]
    W2 = theta[2*HIDDEN:3*HIDDEN].view(1, HIDDEN)
    b2 = theta[3*HIDDEN:]
    return F.gelu(x @ W1.T + b1) @ W2.T + b2

The rest of this post is the three-act story of what A−1\mathbf{A}^{-1} is, where it comes from, and why the GELU choice from the previous post is what makes any of this possible.

What Just Happened? From MLE to a Gaussian on the Weights

Act 1: MLE is a MAP with a flat prior

Standard neural-network training minimises the sum of squared errors:

EMLE(w)=12∑n=1N{y(xn,w)−tn}2.E_{\text{MLE}}(\mathbf{w}) = \tfrac{1}{2} \sum_{n=1}^{N} \{y(\mathbf{x}_n, \mathbf{w}) - t_n\}^2.

The key insight is that this is also the log-posterior under a specific Bayesian model. Write the likelihood as Gaussian with precision β\beta:

p(t∣x,w,β)=N(t∣y(x,w),β−1),p(t \mid \mathbf{x}, \mathbf{w}, \beta) = \mathcal{N}(t \mid y(\mathbf{x}, \mathbf{w}), \beta^{-1}),

and place an isotropic Gaussian prior on the weights:

p(w∣α)=N(w∣0,α−1I).p(\mathbf{w} \mid \alpha) = \mathcal{N}(\mathbf{w} \mid \mathbf{0}, \alpha^{-1} \mathbf{I}).

Take the log of p(w∣D)∝p(D∣w,β) p(w∣α)p(\mathbf{w}\mid \mathcal{D}) \propto p(\mathcal{D}\mid \mathbf{w},\beta)\,p(\mathbf{w}\mid \alpha) and you get:

ln⁡p(w∣D)=−α2w⊤w−β2∑n=1N{y(xn,w)−tn}2+const.\ln p(\mathbf{w}\mid \mathcal{D}) = -\frac{\alpha}{2}\mathbf{w}^\top\mathbf{w} - \frac{\beta}{2}\sum_{n=1}^{N}\{y(\mathbf{x}_n,\mathbf{w}) - t_n\}^2 + \text{const}.

Maximising this log-posterior is what practitioners call weight decay or L2 regularisation. The α\alpha is the regularisation coefficient, rebranded. Setting α=0\alpha = 0 recovers plain MLE. A Bayesian neural network is not a new training routine. It is the same training routine with one extra step after convergence.

Act 2: Laplace approximation, a Gaussian over weights

After optimisation, we have wMAP\mathbf{w}_{\text{MAP}}. The true posterior is non-Gaussian because y(x,w)y(\mathbf{x},\mathbf{w}) is non-linear in w\mathbf{w}, so no closed form exists. The trick, due to MacKay (1992), is to Taylor-expand the log-posterior to second order around wMAP\mathbf{w}_{\text{MAP}}. The first derivative vanishes at the mode, so what remains is a quadratic:

ln⁡p(w∣D)≈ln⁡p(wMAP∣D)−12(w−wMAP)⊤A(w−wMAP),\ln p(\mathbf{w}\mid \mathcal{D}) \approx \ln p(\mathbf{w}_{\text{MAP}}\mid \mathcal{D}) - \tfrac{1}{2}(\mathbf{w} - \mathbf{w}_{\text{MAP}})^\top \mathbf{A} (\mathbf{w} - \mathbf{w}_{\text{MAP}}),

where A\mathbf{A} is the Hessian of the negative log-posterior:

A=−∇∇ln⁡p(w∣D,α,β)=αI+βH,\mathbf{A} = -\nabla\nabla \ln p(\mathbf{w}\mid \mathcal{D}, \alpha, \beta) = \alpha \mathbf{I} + \beta \mathbf{H},

and H\mathbf{H} is the Hessian of the sum-of-squared-errors. Exponentiating the quadratic gives a Gaussian approximation to the posterior:

q(w∣D)=N(w∣wMAP,A−1).q(\mathbf{w}\mid \mathcal{D}) = \mathcal{N}(\mathbf{w}\mid \mathbf{w}_{\text{MAP}}, \mathbf{A}^{-1}).

This is called the Laplace approximation. It is exact when the log-posterior is quadratic (linear-Gaussian models) and an increasingly rough approximation when the posterior has heavy tails, skew or multimodality. For a well-initialised neural network sitting in a local basin, it is serviceable.

In code, the Hessian of the SSE is one autograd call:

def sse(theta):
    return 0.5 * ((predict(theta, x) - y) ** 2).sum()

H = hessian(sse, theta_map).detach().numpy()
A = alpha * np.eye(W) + beta * H
A_inv = np.linalg.inv(0.5 * (A + A.T))   # symmetrise before inverting

Think of H\mathbf{H} as curvature of the data likelihood and αI\alpha \mathbf{I} as curvature of the prior. Where the data is informative (large eigenvalues of βH\beta \mathbf{H}), the prior α\alpha barely registers and the posterior is tightly constrained. Where the data is uninformative (tiny eigenvalues), the prior dominates and the posterior stays wide. This is the regularisation vs information trade-off in linear form.

Act 3: Predictive distribution

The predictive distribution is the integral of the likelihood against the posterior:

p(t∣x,D)=∫p(t∣x,w) q(w∣D) dw.p(t\mid \mathbf{x}, \mathcal{D}) = \int p(t\mid \mathbf{x}, \mathbf{w})\, q(\mathbf{w}\mid \mathcal{D})\, \mathrm{d}\mathbf{w}.

This is still intractable because y(x,w)y(\mathbf{x},\mathbf{w}) is non-linear in w\mathbf{w}. The second move is a linearisation around wMAP\mathbf{w}_{\text{MAP}}:

y(x,w)≈y(x,wMAP)+g⊤(w−wMAP),g=∇wy(x,w)∣w=wMAP.y(\mathbf{x}, \mathbf{w}) \approx y(\mathbf{x}, \mathbf{w}_{\text{MAP}}) + \mathbf{g}^\top (\mathbf{w} - \mathbf{w}_{\text{MAP}}), \quad \mathbf{g} = \nabla_\mathbf{w} y(\mathbf{x}, \mathbf{w})\vert_{\mathbf{w}=\mathbf{w}_{\text{MAP}}}.

With a linear-Gaussian integrand, the predictive collapses to a closed-form Gaussian:

p(t∣x,D)=N(t∣y(x,wMAP),σ2(x)),σ2(x)=β−1+g⊤A−1g.p(t\mid \mathbf{x}, \mathcal{D}) = \mathcal{N}(t\mid y(\mathbf{x},\mathbf{w}_{\text{MAP}}), \sigma^2(\mathbf{x})), \quad \sigma^2(\mathbf{x}) = \beta^{-1} + \mathbf{g}^\top \mathbf{A}^{-1} \mathbf{g}.

The variance has two components. β−1\beta^{-1} is the irreducible observation noise, the same one you would get from the MLE fit. g⊤A−1g\mathbf{g}^\top \mathbf{A}^{-1} \mathbf{g} is the new one, and it measures how much the prediction moves under the posterior uncertainty in w\mathbf{w}. Near training data, A−1\mathbf{A}^{-1} is small in the directions g\mathbf{g} points; far from training data, the sensitivity g\mathbf{g} itself becomes large, and the second term dominates.

def predictive_band(theta_map_t, alpha, beta, x_eval):
    A_inv = posterior_covariance(alpha, beta)
    mean = predict_np(theta_map_t.numpy(), x_eval)
    var  = np.empty_like(mean)
    for i, xi in enumerate(x_eval):
        g = jacobian_wrt_theta(theta_map_t, xi)
        var[i] = 1.0 / beta + g @ A_inv @ g
    return mean, np.sqrt(var)

Extend xx well beyond the training support and the band tells the honest story:

The predictive mean extrapolates smoothly but the ±2σ band widens dramatically outside the training support (shaded region). The true sin(2πx) curve is still within the band where the model is allowed to be uncertain.

The mean prediction is exactly what the MAP network would produce. What the Bayesian treatment adds is the band. Inside the support, the band hugs the mean. Outside, it fans open to roughly ±3\pm 3. A reader looking at this plot learns two things the MLE plot refused to tell them: the model is confident in the middle and completely agnostic at the edges.

Going Deeper: The Evidence Framework and γ\gamma

We have so far treated α\alpha and β\beta as given. Setting them by hand is unsatisfying because they are not physical quantities; they are modelling choices. The evidence framework eliminates them by integrating them out, or more practically, by finding values that maximise the marginal likelihood of the data:

ln⁡p(D∣α,β)≈−E(wMAP)−12ln⁡∣A∣+W2ln⁡α+N2ln⁡β−N2ln⁡(2π).\ln p(\mathcal{D}\mid \alpha, \beta) \approx -E(\mathbf{w}_{\text{MAP}}) - \tfrac{1}{2}\ln|\mathbf{A}| + \tfrac{W}{2}\ln\alpha + \tfrac{N}{2}\ln\beta - \tfrac{N}{2}\ln(2\pi).

This is the same evidence expression the evidence-framework post derived for linear regression. The non-linear part of the network only shows up through H\mathbf{H} inside A=αI+βH\mathbf{A} = \alpha\mathbf{I} + \beta\mathbf{H}. Maximising this with respect to α\alpha and β\beta gives MacKay's re-estimation formulas:

αnew=γwMAP⊤wMAP,1βnew=1N−γ∑n=1N{y(xn,wMAP)−tn}2,\alpha_{\text{new}} = \frac{\gamma}{\mathbf{w}_{\text{MAP}}^\top \mathbf{w}_{\text{MAP}}}, \qquad \frac{1}{\beta_{\text{new}}} = \frac{1}{N - \gamma}\sum_{n=1}^{N}\{y(\mathbf{x}_n, \mathbf{w}_{\text{MAP}}) - t_n\}^2,

with γ=∑iλi/(α+λi)\gamma = \sum_i \lambda_i / (\alpha + \lambda_i), where λi\lambda_i are eigenvalues of βH\beta\mathbf{H}. The procedure alternates: fit wMAP\mathbf{w}_{\text{MAP}}, recompute γ\gamma, update α\alpha and β\beta, refit, repeat.

α, β and log evidence across 12 re-estimation steps. α climbs from 0.001 to 0.17, β drops from 69 to around 20, and the log evidence rises from −90 to −21, with a small dip at step 7 caused by alternation being non-monotone.

The starting point is a weak prior (α=10−3\alpha = 10^{-3}) and an aggressive noise assumption (β=1/0.122≈69\beta = 1/0.12^2 \approx 69). The evidence framework pulls both to more sensible values within a few iterations. Small non-monotonicities like the dip at step 7 are expected because re-estimation is not an exact coordinate descent on the evidence (a consequence of ignoring how λi\lambda_i depend on α\alpha).

The quantity γ\gamma is worth sitting with. For a Bayesian linear regression, γ\gamma is exactly the effective number of parameters in the model: directions in weight space where the data has more curvature than the prior contribute ≈1\approx 1, and directions where the prior dominates contribute ≈0\approx 0. For our 37-parameter GELU network, the converged γ\gamma is about 16:

Left: eigenvalues of βH span more than six orders of magnitude on log scale, crossing the prior precision α around index 15. Right: the ratio λ/(α+λ) is the per-direction effective parameter count; summing gives γ ≈ 16 of 37.

Roughly 16 directions in weight space are "constrained by data"; the remaining 21 are "constrained by prior". Running the evidence loop over successive iterations shows the predictive band settling in step by step:

Animation of the predictive band across evidence re-estimation steps, starting from a near-flat prior where the band is wide everywhere, converging to tight bands where data is dense and wide bands in the unobserved gap.

The animation is the evidence framework doing its job. Early frames have a near-flat prior and the network overfits; the posterior reflects that with bizarre uncertainty structure. Late frames show the converged trade-off: γ≈16\gamma \approx 16 effective parameters capture the sinusoidal structure, and the posterior variance concentrates into the meaningful directions.

The Classification Case

For a two-class classification network with a logistic-sigmoid output, there is no β\beta (labels are assumed correct) and the likelihood is Bernoulli rather than Gaussian. The Laplace procedure is identical: find wMAP\mathbf{w}_{\text{MAP}} by minimising cross-entropy plus α2w⊤w\tfrac{\alpha}{2}\mathbf{w}^\top\mathbf{w}, compute the Hessian, approximate the posterior by N(wMAP,A−1)\mathcal{N}(\mathbf{w}_{\text{MAP}}, \mathbf{A}^{-1}). The predictive distribution needs one extra step because a Gaussian convolved with a sigmoid has no closed form. MacKay's probit approximation handles it:

p(t=1∣x,D)=σ ⁣(κ(σa2) b⊤wMAP),p(t=1\mid \mathbf{x}, \mathcal{D}) = \sigma\!\left(\kappa(\sigma_a^2)\,\mathbf{b}^\top \mathbf{w}_{\text{MAP}}\right),

where κ(s)=(1+πs/8)−1/2\kappa(s) = (1 + \pi s / 8)^{-1/2} squashes the activation toward zero in proportion to the posterior variance at that input. Reproduce this and you get classification contours that spread out in unseen regions: the decision boundary stays sharp near the data and the contours fan apart far from it. The notebook includes a faithful implementation on a synthetic two-moons dataset.

When Laplace Fails

The Laplace approximation works when the posterior around wMAP\mathbf{w}_{\text{MAP}} is roughly Gaussian. Three failure modes are worth knowing:

  • Multimodality. Two-layer networks have M! 2MM!\,2^M equivalent modes from permutation and sign-flip symmetries. These are harmless: they all give identical predictions. Genuinely inequivalent modes are the problem. Laplace anchors you to one basin and pretends the others do not exist.
  • Determinant sensitivity. The evidence depends on ln⁡∣A∣\ln|\mathbf{A}|. Small eigenvalues are hard to estimate from finite data, and they dominate the log-determinant. Small numerical errors in the tail of the spectrum can move the evidence by orders of magnitude, which makes model-comparison across architectures fragile.
  • Scale. The Hessian is W×WW \times W. Storing it costs O(W2)O(W^2) memory; inverting it costs O(W3)O(W^3) time. For a 70-billion-parameter transformer, both are hopeless. This is why modern Bayesian deep learning uses tricks like KFAC, Kronecker-factored Laplace, or last-layer-only Laplace. The story is the same; only the block structure imposed on A\mathbf{A} differs.

For the toy net here (W=37W = 37), none of these bite. For any production network, all of them do.

The Foundations: MacKay's Practical Bayesian Framework

The framework here is a restatement of David MacKay's 1992 PhD thesis and the companion paper that emerged from it:

"A Practical Bayesian Framework for Backpropagation Networks", Neural Computation 4(3), 448–472 (1992).

MacKay's thesis was, at the time, a quiet declaration that neural networks were not the mysterious universal approximators their critics caricatured them as. They were probabilistic models whose weights were ordinary random variables, whose outputs had posterior distributions, and whose predictions came with error bars once you sat down and did the integrals. The paper's contribution was practical: show that the Laplace approximation plus the evidence framework gives you all of this at roughly the cost of a few training runs.

Three pieces of machinery make this work:

  1. Backpropagation for gradients. Trained networks are wMAP\mathbf{w}_{\text{MAP}} under a Gaussian prior, which is what regularised least squares gives you.
  2. Backpropagation for the Hessian. The H\mathbf{H} in A=αI+βH\mathbf{A} = \alpha\mathbf{I} + \beta\mathbf{H} is the same Hessian that post used for Gauss-Newton. There is a direct hand-off between second-order optimisation and Laplace Bayesian inference: the object you compute to take a single Newton step is also the object that defines your posterior covariance.
  3. Laplace + linearisation for the predictive. Two approximations, in sequence, turn the intractable marginalisation over w\mathbf{w} into a closed-form Gaussian predictive.

The framework predates variational Bayes (Hinton & van Camp, 1993) and MCMC methods for deep networks by several years. It also predates the practical wave of deep learning by about two decades. MacKay was building Bayesian neural networks while the field was still arguing over whether neural networks were a good idea at all.

Why did it not become the default? Scale. MacKay's demonstrations were on networks with a few dozen to a few hundred weights. The Hessian at that size fits on a desk calculator. At modern scales, you need either Kronecker structure (KFAC-style), layerwise blocking, or last-layer Bayesianism to make Laplace tractable. The idea is identical; the engineering is harder. The recent Laplace redux wave (Daxberger et al., NeurIPS 2021) is explicitly a revival of MacKay's framework with modern approximations to A\mathbf{A}.

Two further references are worth the click. MacKay's original thesis, Bayesian Methods for Adaptive Models (Caltech, 1992), is freely available at inference.org.uk and is an astonishingly readable piece of work. Neal's Bayesian Learning for Neural Networks (1995), which grew out of the same era, took the opposite route (hybrid MCMC instead of Laplace) and showed that infinitely wide Bayesian networks converge to Gaussian processes. That equivalence is what connects BNNs to the GP post on this site.

Interactive Tools

  • Overfitting Explorer: A polynomial regression playground. Watch how complexity inflates variance without a prior; the evidence framework is the principled cure for exactly this pathology.
  • GP Regression Playground: An infinitely wide Bayesian neural network collapses to a Gaussian process (Neal, 1995). Drag the kernel parameters and see the posterior widen in the same way our BNN's ±2σ\pm 2\sigma band widens away from data.
  • Bayes' Theorem Calculator: The posterior-update arithmetic the Laplace approximation is building a quadratic approximation to.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions