Course contents 15 / 15

15 / 15 · Scalable Inference

Bayesian deep learning

Why put a distribution over the weights of a neural network, and four practical ways to approximate it: Bayes by Backprop, MC dropout, deep ensembles and the Laplace approximation.

On this page 10

Take 40 points on [−4,−1][-4, -1] and 40 on [1,4][1, 4], with y=sin⁡xy = \sin x plus noise of standard deviation 0.10.1, and fit a network 1→128→128→11 \to 128 \to 128 \to 1 with ReLU units by Adam on the squared error. Its only notion of uncertainty is the standard deviation of its residuals, 0.0800.080, and it attaches that number to every input.

In the gap, at x=0x = 0, it predicts 0.400.40 where sin⁡0=0\sin 0 = 0, five of its standard deviations away. Beyond the data it is worse. At x=6x = 6 it predicts −2.31-2.31 where sin⁡6=−0.28\sin 6 = -0.28, and at x=−7x = -7 it predicts 4.224.22 where sin⁡(−7)=−0.66\sin(-7) = -0.66. A ReLU network continues linearly outside its training range, and nothing in its output says that it is guessing.

How can a network report that it does not know? Black-box variational inference fitted posteriors over latent variables with a network inside the likelihood; here the unknowns are the weights of the network itself.

Why put uncertainty in the weights#

Let f(x;w)f(x; w) be the network with weights w∈RPw \in \mathbb R^P, trained on data D\mathcal D. Many weight vectors fit 80 points equally well; they agree where there are data and disagree in the gap. The Bayesian answer keeps all of them, weighted by the posterior, and averages their predictions:

p(y∣x,D)=∫p(y∣x,w) p(w∣D) dw≈1T∑t=1Tp(y∣x,wt),\begin{aligned} p(y \mid x, \mathcal D) &= \int p(y \mid x, w)\, p(w \mid \mathcal D)\, dw \\ &\approx \frac1T \sum_{t=1}^T p(y \mid x, w_t), \end{aligned}

where w1,…,wTw_1, \dots, w_T are samples from q(w)q(w), an approximation of the posterior. For regression with noise variance σ2\sigma^2, p(y∣x,w)=N(y∣f(x;w),σ2)p(y \mid x, w) = \mathcal N\big(y \mid f(x; w), \sigma^2\big), and the law of total variance splits the predictive variance in two:

Var⁡[y∣x,D]=Ew[σ2]+Var⁡w[f(x;w)],\operatorname{Var}[y \mid x, \mathcal D] = \mathbb E_{w}\big[\sigma^2\big] + \operatorname{Var}_{w}\big[f(x; w)\big],

with both moments under the posterior. The first term, the noise, is aleatoric uncertainty and does not shrink with more data. The second, epistemic uncertainty, is the disagreement between plausible networks. It should be small near the training data and large where there are none, and it should shrink as data accumulate.

Bayesian linear regression and Gaussian processes compute this term exactly. For a network, the posterior over PP weights, with PP in the millions, has no closed form and many modes. Some are copies: permuting the hidden units of a layer together with their weights computes the same function, so every mode of our network is one of (128!)2(128!)^2 relabelled copies. Even Hamiltonian Monte Carlo (HMC), the reference method since Neal (1996), is affordable only for small networks: each of its leapfrog steps needs a gradient over the whole data set, and a chain needs thousands of them.

Figure

A predictive distribution from samples of the weights

A predictive distribution from samples of the weightsOn the left, three ways to define a distribution over weights: a Gaussian for every weight (Bayes by Backprop), random masks of units (MC dropout) and several trained networks (a deep ensemble). Five weight settings are taken from it; each is run on the input x = 0 from the gap in the data and predicts −0.28, 0.58, 0.07, 0.58 and 0.11. On the right, their mean 0.21 and the standard deviation 0.336: the square root of the spread of the networks, 0.1070, plus the noise variance, 0.0057.Bayes by Backpropw ~ N(μ, σ²) per weightMC dropoutrandom masks of unitsdeep ensembleM trained networks1w₁w₂w₃w₄w₅T = 5 weight settings2f(x; w)x = 0-0.280.580.070.580.11f(0; wₜ)3mean = 0.21over the 5 passesstd = 0.336√(0.1070 model + 0.0057 noise)Var y = E[σ²] + Var[f]4A predictive distribution from samples of the weightsOn the left, three ways to define a distribution over weights: a Gaussian for every weight (Bayes by Backprop), random masks of units (MC dropout) and several trained networks (a deep ensemble). Five weight settings are taken from it; each is run on the input x = 0 from the gap in the data and predicts −0.28, 0.58, 0.07, 0.58 and 0.11. On the right, their mean 0.21 and the standard deviation 0.336: the square root of the spread of the networks, 0.1070, plus the noise variance, 0.0057.Bayes by Backpropw ~ N(μ, σ²) per weightMC dropoutrandom masks of unitsdeep ensembleM trained networks1w₁w₂w₃w₄w₅T = 5 weight settings2f(x; w)x = 0-0.280.580.070.580.11f(0; wₜ)3mean = 0.21over the 5 passesstd = 0.336√(0.1070 model + 0.0057 noise)Var y = E[σ²] + Var[f]4
The five-network ensemble of the Code section at x = 0, in the middle of the gap in the data. MC dropout runs the same steps with 500 random masks, Bayes by Backprop with 500 draws of Gaussian weights. In the gap the predictive variance is almost all spread between networks; on the data it is noise.

In the figure, the five members of an ensemble predict between −0.28-0.28 and 0.580.58 at x=0x = 0. Their variance, 0.1070.107, dwarfs the noise variance, 0.00570.0057, and the predictive standard deviation is 0.3360.336, four times that of the single network.

The posterior matters only through this integral. Wilson and Izmailov (2020) point out that two weight settings that compute almost the same function add almost nothing to the average. A good approximation for prediction is one whose samples differ as functions.

The deep generative models of the next course put their uncertainty elsewhere. The VAE integrates over the latent code zz of each example through its encoder, and a diffusion model over the chain of noisy images between the data and pure noise. Both fit their network weights θ\theta by maximizing a lower bound on log⁡pθ(x)\log p_\theta(x), which returns a single θ\theta: the latents are averaged over, the weights are a point estimate. Neither model says how uncertain its own weights are; the methods below would be needed for that.

Bayes by Backprop#

Bayes by Backprop (Blundell et al., 2015) is black-box variational inference with the reparameterization gradient, applied to the weights; Murphy (2023, Section 17.3.3) calls it stochastic variational inference with a network as the likelihood. The family is a diagonal Gaussian, q(w)=∏jN(wj∣μj,σj2)q(w) = \prod_j \mathcal N(w_j \mid \mu_j, \sigma_j^2), with σj=log⁡(1+eρj)\sigma_j = \log(1 + e^{\rho_j}), so that the standard deviation stays positive for any real ρj\rho_j. The loss is the negative ELBO,

F(μ,ρ)=DKL(q(w) ∥ p(w))−Eq[log⁡p(D∣w)],\mathcal F(\mu, \rho) = D_{\mathrm{KL}}\big(q(w) \,\|\, p(w)\big) - \mathbb E_{q}\big[\log p(\mathcal D \mid w)\big],

estimated with one draw w=μ+log⁡(1+eρ)⊙εw = \mu + \log(1 + e^{\rho}) \odot \varepsilon, ε∼N(0,I)\varepsilon \sim \mathcal N(0, I). Write F~=log⁡q(w)−log⁡p(w)−log⁡p(D∣w)\tilde{\mathcal F} = \log q(w) - \log p(w) - \log p(\mathcal D \mid w) for the sampled loss and g=∂F~/∂wg = \partial \tilde{\mathcal F}/\partial w for its ordinary backpropagation gradient. The chain rule gives the gradients of the variational parameters (their equations 3 and 4):

Δμ=g+∂F~∂μ,Δρ=g⊙ε1+e−ρ+∂F~∂ρ.\begin{aligned} \Delta_\mu &= g + \frac{\partial \tilde{\mathcal F}}{\partial \mu}, \\ \Delta_\rho &= g \odot \frac{\varepsilon}{1 + e^{-\rho}} + \frac{\partial \tilde{\mathcal F}}{\partial \rho} . \end{aligned}

The first terms carry gg back through the sample:

w=μ+log⁡(1+eρ)⊙ε,∂w∂μ=1,∂w∂ρ=ε⊙eρ1+eρ=ε1+e−ρ.\begin{aligned} w &= \mu + \log(1 + e^{\rho}) \odot \varepsilon, \\ \frac{\partial w}{\partial \mu} &= 1, \\ \frac{\partial w}{\partial \rho} &= \varepsilon \odot \frac{e^\rho}{1 + e^\rho} = \frac{\varepsilon}{1 + e^{-\rho}} . \end{aligned}

The second terms differentiate the explicit dependence of log⁡q(w∣μ,ρ)\log q(w \mid \mu, \rho) on μ\mu and ρ\rho at fixed ww. One backward pass serves both gradients; the price is twice the parameters and a noisy gradient.

Worked example. One weight with μ=0.3\mu = 0.3 and ρ=−3\rho = -3 has σ=log⁡(1+e−3)=0.0486\sigma = \log(1 + e^{-3}) = 0.0486. The draw ε=0.5\varepsilon = 0.5 gives w=0.3+0.0486⋅0.5=0.3243w = 0.3 + 0.0486 \cdot 0.5 = 0.3243, and the factor in Δρ\Delta_\rho is 0.5/(1+e3)=0.02370.5/(1 + e^{3}) = 0.0237. Against the prior N(0,1)\mathcal N(0, 1), by the closed form derived in the VAE note, this weight costs

DKL=log⁡1σ+σ2+μ22−12=3.0244+0.0462−0.5=2.571 nats.\begin{aligned} D_{\mathrm{KL}} &= \log\frac1\sigma + \frac{\sigma^2 + \mu^2}{2} - \frac12 \\ &= 3.0244 + 0.0462 - 0.5 = 2.571 \text{ nats}. \end{aligned}

A network with a million such weights pays millions of nats of KL, which the likelihood of the data has to justify; weights the data do not need are pushed back towards the prior.

The prior matters in practice. Blundell et al. use a scale mixture of two zero-mean Gaussians per weight, π N(0,σ12)+(1−π) N(0,σ22)\pi\, \mathcal N(0, \sigma_1^2) + (1 - \pi)\, \mathcal N(0, \sigma_2^2) with σ1>σ2\sigma_1 > \sigma_2 and σ2≪1\sigma_2 \ll 1: a heavy tail with a spike near zero. Its KL has no closed form and is estimated from the same samples. They found that fitting the prior’s parameters to the data made results worse, so they fixed them by validation.

With MM mini-batches per epoch, each batch loss carries a share of the KL, for example 1MDKL−Eq[log⁡p(Di∣w)]\tfrac1M D_{\mathrm{KL}} - \mathbb E_q[\log p(\mathcal D_i \mid w)], so that the losses of an epoch sum to F\mathcal F (their Section 3.4): for independent examples log⁡p(D∣w)=∑i=1Mlog⁡p(Di∣w)\log p(\mathcal D \mid w) = \sum_{i=1}^M \log p(\mathcal D_i \mid w), and the MM shares of the KL add up to one KL. One weight sample per mini-batch is shared by all its examples, which correlates their gradients. The local reparameterization trick (Kingma, Salimans and Welling, 2015) samples the pre-activations of each example instead. A pre-activation b=∑jajwjb = \sum_j a_j w_j is a linear combination of independent Gaussian weights, so b∼N(∑jajμj,∑jaj2σj2)b \sim \mathcal N\big(\sum_j a_j \mu_j, \sum_j a_j^2 \sigma_j^2\big) can be drawn directly, with fresh noise for every example; Kingma et al. show that this lowers the variance of the gradient at no extra cost.

On MNIST with two hidden layers of 1200 ReLU units, Blundell et al. report these test errors (their Table 1):

MethodTest error
SGD1.88%1.88\%
SGD with dropout1.36%1.36\%
Bayes by Backprop, Gaussian prior2.04%2.04\%
Bayes by Backprop, scale-mixture prior1.32%1.32\%

With a plain Gaussian prior, Bayes by Backprop was worse than unregularized SGD; the prior made the difference. Each iteration was about twice as slow as dropout. Dropping the 95% of weights with the smallest ratio ∣μj∣/σj\lvert \mu_j \rvert / \sigma_j left the error at 1.29%1.29\% (their Table 2).

MC dropout as approximate variational inference#

Dropout zeroes each unit with probability pp during training. Gal and Ghahramani (2016) read it as variational inference. Their family sets the weight matrix of layer ii to Wi=Midiag⁡(zi)W_i = M_i \operatorname{diag}(z_i), where MiM_i is a learned matrix and the entries of ziz_i are independent Bernoulli variables that keep a unit with probability 1−p1 - p. A draw from qq is a network with some input units of each layer removed.

They show that the dropout loss with L2 weight decay λ\lambda equals, up to a constant factor, a one-sample Monte Carlo estimate of the negative ELBO for this qq under a Gaussian prior. The model precision is then τ=(1−p) l2/(2Nλ)\tau = (1 - p)\, l^2/(2 N \lambda) for a prior length-scale ll; their equation 7 writes the same with the keep probability.

The correspondence is easy to see in outline. Drawing a mask is drawing a weight matrix from qq, so the dropout loss on one mask is a one-sample, reparameterized estimate of −Eq[log⁡p(D∣w)]-\mathbb E_q[\log p(\mathcal D \mid w)]. The KL term to the Gaussian prior is not finite for this qq; the authors replace each Bernoulli component by a narrow Gaussian and, for many hidden units, the KL becomes a squared-norm penalty on MiM_i weighted by the keep probability, which is weight decay. The full argument is in the appendix of Gal and Ghahramani (2016), and the next subsection discusses its weak points.

The practical consequence is MC dropout, short for Monte Carlo dropout: keep dropout on at test time, run TT stochastic forward passes, and use their mean and variance,

E[y∣x]≈1T∑t=1Tf(x;wt)=fˉ(x),Var⁡[y∣x]≈τ−1+1T∑t=1Tf(x;wt)2−fˉ(x)2.\begin{aligned} \mathbb E[y \mid x] &\approx \frac1T \sum_{t=1}^T f(x; w_t) = \bar f(x), \\ \operatorname{Var}[y \mid x] &\approx \tau^{-1} + \frac1T \sum_{t=1}^T f(x; w_t)^2 - \bar f(x)^2 . \end{aligned}

The second formula is the law of total variance again: noise plus the spread of the sampled networks. MC dropout costs nothing at training time and TT forward passes at test time. In the experiment, with p=0.1p = 0.1 and 500 passes, its predictive standard deviation, with the residual noise variance of the fit in place of τ−1\tau^{-1}, grows from 0.100.10 on the data to 0.140.14 in the gap and 0.200.20 to 0.250.25 beyond the data.

The debate#

Optional depth: why MC dropout is an approximate posterior only in a weak sense. The rest of the note does not depend on it.

The variational objective is not well defined. A qq whose draws set whole columns of WiW_i exactly to zero puts its mass on a set of measure zero under a Gaussian prior, so DKL(q ∥ p)D_{\mathrm{KL}}(q \,\|\, p) is infinite. The finite KL of the derivation comes from a limit with a small Gaussian around each mixture component. Hron, Matthews and Ghahramani (2018) make this precise and propose a quasi-KL divergence that stays finite.

The approximation also does not concentrate. The dropout rate is a hyperparameter fixed before training, and the data never change it. Osband, Aslanides and Cassirer (2018), Lemma 1, observe that the trained dropout distribution is unchanged when every data point is duplicated, whereas a posterior from twice the data would be narrower. Murphy (2023, Section 17.3.1) adds that as the data grow, a true posterior collapses to a point while the dropout distribution keeps dropping units with the same probability. Learning the rate, as in concrete dropout (Gal, Hron and Kendall, 2017), addresses this only partly.

Used as a heuristic, MC dropout still widens predictions where the data are thin, at almost no cost. In a large comparison under dataset shift, Ovadia et al. (2019) found it ahead of temperature scaling and of last-layer methods on CIFAR-10 and ImageNet, and consistently behind deep ensembles.

Deep ensembles#

A deep ensemble (Lakshminarayanan, Pritzel and Blundell, 2017) trains MM networks independently, from different random initializations and with different shuffling of the data, and treats them as a uniform mixture. For regression each network may output a mean μm(x)\mu_m(x) and a variance σm2(x)\sigma_m^2(x), trained by the Gaussian negative log-likelihood, a proper scoring rule. The mixture is summarized by its mean and its variance, which is the second moment minus the squared mean; each member’s second moment is σm2+μm2\sigma_m^2 + \mu_m^2:

μ∗(x)=1M∑m=1Mμm(x),σ∗2(x)=1M∑m=1M(σm2(x)+μm2(x))−μ∗2(x).\begin{aligned} \mu_*(x) &= \frac1M \sum_{m=1}^M \mu_m(x), \\ \sigma_*^2(x) &= \frac1M \sum_{m=1}^M \big(\sigma_m^2(x) + \mu_m^2(x)\big) - \mu_*^2(x) . \end{aligned}

The recommended default is M=5M = 5. Adversarial training is optional, and training on bootstrap samples, as in bagging, made results worse than random initialization alone: each member then sees only about 63% of the distinct points, since a point is missed by all nn draws with probability (1−1/n)n→e−1=0.37(1 - 1/n)^n \to e^{-1} = 0.37 (bagging note).

Ensembles are not derived from a posterior, yet Wilson and Izmailov (2020) argue that they approximate Bayesian model averaging better than most methods that are. Each member sits in a different basin of the loss, and members from different basins compute different functions, which is what the average needs. A diagonal Gaussian or a Laplace approximation describes one basin, where the networks are often nearly redundant. MultiSWAG, their refinement, also fits a Gaussian within each member’s basin, so that the average runs both across and within basins.

The costs are MM trainings and MM forward passes, which can be reduced afterwards by distilling the ensemble into one network. In the experiment, five networks trained on the squared error have a predictive standard deviation of 0.080.08 on the data and 0.340.34 in the gap, the widest of the three models there.

The Laplace approximation for networks#

The Laplace approximation of the course fits a Gaussian at the mode: q(w)=N(wMAP,H−1)q(w) = \mathcal N\big(w_{\text{MAP}}, H^{-1}\big), with HH the Hessian of the negative log posterior at the MAP weights. For networks it goes back to MacKay (1992), who also used the evidence of this Gaussian to choose the weight decay. Two obstacles made it unpopular, and both have been worked around (Daxberger et al., 2021).

The Hessian is P×PP \times P. It is replaced by a positive semidefinite approximation, the generalized Gauss–Newton matrix or the Fisher, with diagonal or Kronecker-factored structure (KFAC, Ritter, Botev and Barber, 2018). Or it is computed only for the last layer, where it is small: with the other layers frozen as features, the last-layer Laplace approximation of a regression network is Bayesian linear regression on those features. There it is exact: the output is linear in the last-layer weights, so with a Gaussian likelihood and a Gaussian prior the log posterior is quadratic, and a Gaussian fitted at its mode is the posterior itself.

Sampling weights and pushing them through the network predicts poorly with these approximations. The reason is that the Gauss–Newton matrix is the exact Hessian of the network linearized at wMAPw_{\text{MAP}}, so the Gaussian is a posterior for that linear model, not for the network (Immer, Korzepa and Bauer, 2021). A linearized predictive uses the matching model. With the Jacobian J(x)=∂f(x;w)/∂wJ(x) = \partial f(x; w)/\partial w at wMAPw_{\text{MAP}} and w∼N(wMAP,Σ)w \sim \mathcal N(w_{\text{MAP}}, \Sigma),

f(x;w)≈f(x;wMAP)+J(x) (w−wMAP),f(x;w)∼N(f(x;wMAP),  J(x) Σ J(x)⊤),\begin{aligned} f(x; w) &\approx f(x; w_{\text{MAP}}) + J(x)\,(w - w_{\text{MAP}}), \\ f(x; w) &\sim \mathcal N\big(f(x; w_{\text{MAP}}),\; J(x)\, \Sigma\, J(x)^\top\big), \end{aligned}

because a linear map of a Gaussian is Gaussian. For the last layer the expansion is exact.

Its main practical advantage is that it is post hoc: a network trained in the usual way gets uncertainty afterwards, at the cost of one curvature computation. Like Bayes by Backprop, it describes one mode.

Sampling the weights with noisy gradients#

The methods so far approximate the posterior by a fixed family. Sampling avoids that, at the price of time. Stochastic-gradient Langevin dynamics (SGLD) of Welling and Teh (2011) adds Gaussian noise to stochastic gradient ascent on the log posterior:

Δwt=ϵt2 g^t+ηt,g^t=∇log⁡p(wt)+NB∑i∈St∇log⁡p(yi∣xi,wt),ηt∼N(0,ϵtI).\begin{aligned} \Delta w_t &= \frac{\epsilon_t}{2}\, \hat g_t + \eta_t, \\ \hat g_t &= \nabla \log p(w_t) + \frac NB \sum_{i \in S_t} \nabla \log p(y_i \mid x_i, w_t), \\ \eta_t &\sim \mathcal N(0, \epsilon_t I) . \end{aligned}

It is the Langevin update with a mini-batch gradient scaled by N/BN/B, as in SVI. Why the mini-batch noise stops mattering: the gradient error enters the step multiplied by ϵt/2\epsilon_t/2, so its variance scales as ϵt2\epsilon_t^2, while the injected noise has variance ϵt\epsilon_t; their ratio goes to zero with the step. As the steps shrink, the discretization error of the Langevin update shrinks too, and Welling and Teh argue that the Metropolis–Hastings acceptance rate tends to one, so the correction can be dropped. The precise statement: with steps meeting the Robbins–Monro conditions, a smooth log posterior and bounded moments of the iterates, step-weighted averages of a test function along the chain converge to its posterior expectation (Teh, Thiery and Vollmer, 2016). The HSE course derives it from Langevin dynamics; Murphy (2023, Section 12.7) covers the preconditioned variants used for networks. Its samples are correlated and cover the modes slowly, and the predictive averages over many saved weight vectors.

Calibration and inputs far from the data#

A classifier is calibrated when, among the inputs to which it assigns probability 0.80.8, a share of 0.80.8 belongs to the class; the logistic regression note defines the reliability diagram and the expected calibration error. Modern networks are often overconfident: on CIFAR-100, the average confidence of a 110-layer ResNet is well above its accuracy, while that of a 5-layer LeNet matches it (Guo et al., 2017, Figure 1). Within the training distribution one scalar fixes most of this: temperature scaling divides the logits by a TT fitted on validation data. It cannot single out inputs unlike the training data: one TT rescales every logit vector alike, and it never changes which class wins. That is where averaging over weights is supposed to help.

Far from the data, single networks are confidently wrong. A ReLU network is piecewise linear with finitely many linear pieces, so a ray x=t ux = t\,u eventually stays in one piece, where the logits are t Vu+ct\, V u + c for a fixed matrix VV and vector cc. If one component of VuV u exceeds the others, its softmax probability tends to 1 as t→∞t \to \infty. So almost every ReLU classifier becomes arbitrarily confident far enough from its training data (Hein, Andriushchenko and Bitterwolf, 2019, Lemma 3.1 and Theorem 3.1). The regression shows the same mechanism in one dimension.

Figure

Uncertainty where there are no data

Uncertainty where there are no dataThree panels with the data on −4 to −1 and 1 to 4, the true function sin x, and the prediction as mean ± 2 standard deviations from −7 to 7. Deterministic network: a band of constant width, standard deviation 0.080 everywhere. MC dropout: 0.10 on the data, 0.14 in the gap and 0.20 to 0.25 beyond the data. Ensemble: 0.08 on the data, 0.34 in the gap, 0.12 at x = 6 and 0.51 at x = −7. At x = 6 the means of the three models are off sin x by 25, 7 and 17 of their standard deviations.gap-2024-606deterministic networkgap-2024-606MC dropout, p = 0.1gap-2024-606ensemble of 5 networksUncertainty where there are no dataThree panels with the data on −4 to −1 and 1 to 4, the true function sin x, and the prediction as mean ± 2 standard deviations from −7 to 7. Deterministic network: a band of constant width, standard deviation 0.080 everywhere. MC dropout: 0.10 on the data, 0.14 in the gap and 0.20 to 0.25 beyond the data. Ensemble: 0.08 on the data, 0.34 in the gap, 0.12 at x = 6 and 0.51 at x = −7. At x = 6 the means of the three models are off sin x by 25, 7 and 17 of their standard deviations.gap-2024-606deterministic networkgap-2024-606MC dropout, p = 0.1gap-2024-606ensemble of 5 networks
A 1 → 128 → 128 → 1 ReLU network, 80 points from y = sin x plus noise of standard deviation 0.1; bands are the predictive mean ± 2 standard deviations, noise included. The gap in the data is shaded; the dashed curve is sin x. Compare the band widths in the gap and at x = 6.

Predictive standard deviations, and the error of the mean at x=6x = 6 in units of the model’s own standard deviation:

ModelOn the dataIn the gapAt x=6x = 6At x=−7x = -7Error at x=6x = 6
deterministic network0.0800.0800.0800.0800.0800.0800.0800.0802.042.04, 25 std
MC dropout0.100.100.140.140.200.200.250.251.361.36, 7 std
deep ensemble0.080.080.340.340.120.120.510.512.042.04, 17 std

Both approximations widen their bands where the data end, the ensemble four times in the gap, but not nearly enough beyond the data: all three means extrapolate linearly, and every model is wrong at x=6x = 6 by many of its own standard deviations. The approximations are better than one network and still overconfident out of distribution. Large studies tell the same story at scale: under increasing dataset shift, calibration degrades for every method, and deep ensembles degrade the least (Ovadia et al., 2019). The table describes one small run; on other problems the order can differ.

The true posterior of a network can be checked only on small problems with long HMC runs, so an approximation is judged by its predictions: calibration, held-out likelihood, behaviour under shift. And an isotropic Gaussian prior on the weights induces a prior over functions that is poorly understood, while the predictive depends on it.

Choosing an approximation#

Bayes by BackpropMC dropoutDeep ensembleLaplace
Distribution over weightsdiagonal GaussianBernoulli masks of trained weightsMM trained networksGaussian at the MAP
Extra training costabout 2× per step, 2× parametersnoneMM trainingsone curvature computation
Prediction costTT passesTT passesMM passeslinearized, or TT passes
Modes coveredoneoneseveralone

Of the four, only the Laplace approximation can be added to a network that was trained in the usual way without dropout. When training several times is affordable, the ensemble was the most reliable under dataset shift among the methods Ovadia et al. compared, which did not include the Laplace approximation.

What you should remember#

  • Predictive variance = noise + spread of plausible networks; only the spread grows where the data end.
  • Bayes by Backprop: BBVI with reparameterization on a diagonal Gaussian over weights, σ=log⁡(1+eρ)\sigma = \log(1 + e^\rho); its prior matters.
  • MC dropout: dropout on at test time, TT passes; cheap, useful, and a posterior only in a weak sense.
  • Deep ensembles: M=5M = 5 networks from different initializations cover several modes; the strongest under shift.
  • Laplace: a Gaussian at the trained weights, post hoc, with a structured Hessian and a linearized predictive.
  • All of them remain overconfident far from the data.

Code#

One weight of Bayes by Backprop, then the experiment: a deterministic network, MC dropout and a deep ensemble on the regression with a gap, with a small network, backpropagation and Adam written in NumPy. It prints the predictive mean and standard deviation on the data (x=±2.5x = \pm 2.5), in the gap (x=0x = 0) and beyond the data (x=6x = 6 and x=−7x = -7). Seeds are fixed; exact numbers can vary across platforms and library versions. The script runs in about 5 seconds.

import numpy as np

# 0. one weight of Bayes by Backprop: sigma = softplus(rho), a reparameterized draw, and its KL to the prior N(0, 1)
mu_w, rho_w, eps_w = 0.3, -3.0, 0.5
sigma_w = np.log1p(np.exp(rho_w))
kl = np.log(1 / sigma_w) + (sigma_w ** 2 + mu_w ** 2) / 2 - 0.5
print(round(sigma_w, 4), round(mu_w + sigma_w * eps_w, 4), round(eps_w / (1 + np.exp(-rho_w)), 4), round(kl, 3))
# 0.0486 0.3243 0.0237 2.571

# 1. data with a gap: 40 points on [-4, -1] and 40 on [1, 4], y = sin(x) + noise of standard deviation 0.1
rng = np.random.default_rng(0)
x = np.concatenate([rng.uniform(-4, -1, 40), rng.uniform(1, 4, 40)])
y = np.sin(x) + 0.1 * rng.normal(size=x.size)
X, Y = x[:, None], y[:, None]
grid = np.linspace(-7, 7, 57)[:, None]          # step 0.25, the grid of the figure
at = [18, 38, 28, 52, 0]                         # the printed points: x = -2.5, 2.5, 0, 6, -7
XG = np.vstack([X, grid])                        # predictions on the training points and on the grid

# 2. a 1 -> 128 -> 128 -> 1 ReLU network, with optional (inverted) dropout after each hidden layer
def init(seed, sizes=(1, 128, 128, 1)):          # uniform in +-1/sqrt(fan_in) for weights and biases
    r = np.random.default_rng(seed)
    return [r.uniform(-1, 1, s) / np.sqrt(m) for m, n in zip(sizes[:-1], sizes[1:]) for s in ((m, n), (n,))]

def forward(w, x, p=0.0, r=None):
    """Returns the output, the input of every layer and the ReLU-and-dropout mask of every hidden layer."""
    hs, masks = [x], []
    for i in range(0, len(w) - 2, 2):
        z = hs[-1] @ w[i] + w[i + 1]
        mask = (z > 0) * ((r.random(z.shape) >= p) / (1 - p) if p else 1.0)   # ReLU, then dropout
        masks.append(mask); hs.append(z * mask)
    return hs[-1] @ w[-2] + w[-1], (hs, masks)

def grad(w, x, y, p=0.0, r=None):
    """Gradient of the mean squared error by backpropagation, last layer first."""
    out, (hs, masks) = forward(w, x, p, r)
    g, grads = 2 * (out - y) / len(x), []
    for j in range(len(hs) - 1, -1, -1):        # layer j has input hs[j] and weights w[2j], w[2j + 1]
        grads = [hs[j].T @ g, g.sum(0)] + grads
        if j:
            g = (g @ w[2 * j].T) * masks[j - 1]
    return grads

def train(seed, p=0.0, weight_decay=0.0, steps=3000, lr=3e-3):
    """Full-batch Adam on the squared error; weight decay is added to the gradient, as an L2 penalty."""
    w, r = init(seed), np.random.default_rng(seed + 100)
    m1, m2 = [np.zeros_like(a) for a in w], [np.zeros_like(a) for a in w]
    for t in range(1, steps + 1):
        grads = grad(w, X, Y, p, r)
        for k, a in enumerate(w):
            gk = grads[k] + weight_decay * a
            m1[k] = 0.9 * m1[k] + 0.1 * gk; m2[k] = 0.999 * m2[k] + 0.001 * gk ** 2
            a -= lr * (m1[k] / (1 - 0.9 ** t)) / (np.sqrt(m2[k] / (1 - 0.999 ** t)) + 1e-8)
    return w

def report(name, mean, var_model, noise_var):
    std = np.sqrt(var_model + noise_var).ravel()
    print(f'{name:13}', 'mean', np.round(mean.ravel()[at], 2), 'std', np.round(std[at], 3))

print('sin(x)       ', np.round(np.sin(grid.ravel()[at]), 2))
n = len(X)
# 3. a deterministic network: its only uncertainty is the noise variance estimated from its residuals
det = forward(train(0), XG)[0]
report('deterministic', det[n:], 0 * det[n:], ((det[:n] - Y) ** 2).mean())

# 4. MC dropout, p = 0.1: dropout stays on at test time; 500 stochastic passes give the mean and the model variance
w_mc, r = train(0, p=0.1, weight_decay=1e-4), np.random.default_rng(7)
S = np.stack([forward(w_mc, XG, 0.1, r)[0] for _ in range(500)])
noise = ((S[:, :n].mean(0) - Y) ** 2).mean()     # noise variance from the training residuals of the mean
report('MC dropout', S[:, n:].mean(0), S[:, n:].var(0), noise)

# 5. a deep ensemble: five networks from different random initializations; var(0) is the 1/M of the mixture
P = np.stack([forward(train(k), XG)[0] for k in range(1, 6)])
report('ensemble', P[:, n:].mean(0), P[:, n:].var(0), ((P[:, :n].mean(0) - Y) ** 2).mean())
print('members at x = 0:', np.round(P[:, n + 28, 0], 2), 'variance', round(P[:, n + 28, 0].var(), 4),
      'noise', round(((P[:, :n].mean(0) - Y) ** 2).mean(), 4))
# sin(x)        [-0.6   0.6   0.   -0.28 -0.66]
# deterministic mean [-0.57  0.56  0.4  -2.31  4.22] std [0.08 0.08 0.08 0.08 0.08]
# MC dropout    mean [-0.58  0.59  0.12 -1.64  2.01] std [0.104 0.102 0.136 0.203 0.245]
# ensemble      mean [-0.57  0.57  0.21 -2.32  3.82] std [0.078 0.077 0.336 0.123 0.509]
# members at x = 0: [-0.28  0.58  0.07  0.58  0.11] variance 0.107 noise 0.0057

The course in one paragraph#

Bayesian methods treat everything unknown as a random variable and answer every question with a distribution. The course followed what that costs and how to pay it, one section at a time.

The first section, Bayesian Modelling, set up the approach: the posterior as prior times likelihood, conjugate priors that keep it in closed form, and the evidence that compares models without a validation set.

The second, Bayesian Linear Models, applied it to linear models: Bayesian linear regression with its predictive variance, the relevance vector machine whose priors switch features off, and the Laplace approximation for classification, where conjugacy ends.

The third, Latent Variables and Approximate Inference, met posteriors without formulas: EM and Bayesian PCA for latent variables, variational inference that optimizes a lower bound, and Gibbs sampling that samples instead.

The fourth, Nonparametric and Topic Models, let the model grow with the data: Gaussian processes over functions and Dirichlet processes over partitions, and LDA, a topic model fitted by both of the previous section’s methods.

The fifth, Scalable Inference, made inference fit large data and any model: stochastic variational inference with mini-batches and natural gradients, black-box variational inference with Monte Carlo gradients and the VAE, and this note’s approximate posteriors over the weights of networks.

The Generative Models course builds on exactly these tools. The variational autoencoder and its variants are amortized variational inference, HMC and NUTS are the samplers that Gibbs sampling led to, and diffusion models are trained with an evidence lower bound on a chain of latent variables.

References#