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 band around every prediction.
Quick Win: A BNN in One Picture
Fit a two-layer GELU network with 12 hidden units (37 weights and biases) to 25 noisy observations of . Leave a gap around the origin and no training data beyond , so the model has regions where a sensible posterior should admit uncertainty.

The MLE and MAP panels collapse the network to a single and output one number per . The Bayesian panel uses the same network, the same architecture, the same activation, but replaces the point estimate with a Gaussian posterior and marginalises at prediction time. The red band is the resulting 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 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:
The key insight is that this is also the log-posterior under a specific Bayesian model. Write the likelihood as Gaussian with precision :
and place an isotropic Gaussian prior on the weights:
Take the log of and you get:
Maximising this log-posterior is what practitioners call weight decay or L2 regularisation. The is the regularisation coefficient, rebranded. Setting 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 . The true posterior is non-Gaussian because is non-linear in , so no closed form exists. The trick, due to MacKay (1992), is to Taylor-expand the log-posterior to second order around . The first derivative vanishes at the mode, so what remains is a quadratic:
where is the Hessian of the negative log-posterior:
and is the Hessian of the sum-of-squared-errors. Exponentiating the quadratic gives a Gaussian approximation to the posterior:
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 as curvature of the data likelihood and as curvature of the prior. Where the data is informative (large eigenvalues of ), the prior 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:
This is still intractable because is non-linear in . The second move is a linearisation around :
With a linear-Gaussian integrand, the predictive collapses to a closed-form Gaussian:
The variance has two components. is the irreducible observation noise, the same one you would get from the MLE fit. is the new one, and it measures how much the prediction moves under the posterior uncertainty in . Near training data, is small in the directions points; far from training data, the sensitivity 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 well beyond the training support and the band tells the honest story:

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 . 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
We have so far treated and 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:
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 inside . Maximising this with respect to and gives MacKay's re-estimation formulas:
with , where are eigenvalues of . The procedure alternates: fit , recompute , update and , refit, repeat.

The starting point is a weak prior () and an aggressive noise assumption (). 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 depend on ).
The quantity is worth sitting with. For a Bayesian linear regression, is exactly the effective number of parameters in the model: directions in weight space where the data has more curvature than the prior contribute , and directions where the prior dominates contribute . For our 37-parameter GELU network, the converged is about 16:

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:

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: 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 (labels are assumed correct) and the likelihood is Bernoulli rather than Gaussian. The Laplace procedure is identical: find by minimising cross-entropy plus , compute the Hessian, approximate the posterior by . The predictive distribution needs one extra step because a Gaussian convolved with a sigmoid has no closed form. MacKay's probit approximation handles it:
where 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 is roughly Gaussian. Three failure modes are worth knowing:
- Multimodality. Two-layer networks have 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 . 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 . Storing it costs memory; inverting it costs 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 differs.
For the toy net here (), 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:
- Backpropagation for gradients. Trained networks are under a Gaussian prior, which is what regularised least squares gives you.
- Backpropagation for the Hessian. The in 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.
- Laplace + linearisation for the predictive. Two approximations, in sequence, turn the intractable marginalisation over 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 .
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 band widens away from data.
- Bayes' Theorem Calculator: The posterior-update arithmetic the Laplace approximation is building a quadratic approximation to.
Related Posts
For gradient-based posterior sampling, the Hamiltonian Monte Carlo tutorial compares trajectories, step sizes and sampling behaviour.
Backprop, Jacobians, Hessians: Why First-Order Wins: The direct prequel. The Hessian used here as posterior precision is the same Hessian that ran Gauss-Newton there. Same object, two uses.
Bayesian Model Comparison: The Evidence Framework: Where the evidence framework was introduced for linear regression. This post adds the Hessian of a non-linear network to the same machinery.
From MLE to Bayesian Inference: MLE as MAP with a flat prior, MAP as the tip of a posterior iceberg. The mental model this post relies on throughout.
Gaussian Process Regression from Scratch: The non-parametric cousin BNNs converge to in the infinite-width limit.
Backpropagation from First Principles: The gradient machinery every step of this post rests on.
Relevance Vector Machine vs SVM in Python: The same evidence-framework hyperparameter optimisation, applied to a kernel model where it drives weights to exactly zero for sparsity.
Conformal Prediction: 90% Coverage, 29% Where It Counts: Prediction intervals with no prior and no likelihood, whose average coverage follows from exchangeability alone.








