Skip to content
BIASED

Bayesian deep learning

Uncertainty in the weights of a neural network: aleatoric and epistemic variance, Bayes by Backprop, MC dropout, deep ensembles, the Laplace approximation and SGLD, calibration and ECE, with what each method costs and what it buys. The course wrap-up.

Why put uncertainty in the weights

The topic Black-box variational inference and the VAE gave us an ELBO gradient for any differentiable model: write the sample as w=μ+σ⊙εw = \mu + \sigma \odot \varepsilon and backpropagate through it. The VAE spent that trick on the latent code of each object. This last topic points the same tools at the weights of a neural network, where the course's question is hardest: millions of uncertain parameters and no closed form for anything.

An ordinary trained network is a point estimate. Training with weight decay λ∥w∥2\lambda \lVert w \rVert^2 is MAP with a Gaussian prior (the topic The Bayesian approach), so the network is w^MAP\hat w_{\text{MAP}} and nothing more. Give a regression network two outputs, a mean f(x;w)f(x; w) and a noise variance σ2(x;w)\sigma^2(x; w), and fit it to noisy observations of y=sin⁡xy = \sin x on two intervals with a gap between them. In the gap and beyond the data it still answers with one curve and roughly the noise level it learned on the data. It has no way to say "I have not seen this".

The Bayesian answer is the posterior predictive, the same object that gave 4/54/5 for the coin:

p(y∣x,D)=∫p(y∣x,w) p(w∣D) dw≈1T∑t=1Tp(y∣x,wt),wt∼p(w∣D).p(y \mid x, D) = \int p(y \mid x, w)\, p(w \mid D)\, dw \approx \frac{1}{T} \sum_{t=1}^{T} p(y \mid x, w_t), \qquad w_t \sim p(w \mid D).

Its variance splits by the law of total variance, with both moments taken over w∼p(w∣D)w \sim p(w \mid D):

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

The first term is aleatoric uncertainty, noise in the data itself. The second is epistemic uncertainty, disagreement between networks that all explain the data. For Bayesian linear regression the same split was 1/β+ϕ(x)⊤SNϕ(x)1/\beta + \phi(x)^\top S_N \phi(x) (the topic Bayesian linear regression). For a network neither term has a closed form, because p(w∣D)p(w \mid D) has none.

The rest of the topic is four ways to approximate p(w∣D)p(w \mid D), plus a fifth that does not try to. Each reuses a tool from this course.

Bayes by Backprop

Bayes by Backprop (Blundell et al., 2015) is black-box VI with the weights as the latent variable. The family is a diagonal Gaussian, with a softplus that keeps every σj\sigma_j positive while ρj\rho_j stays unconstrained:

q(w)=N(μ,diag⁡(σ2)),σ=log⁡(1+eρ).q(w) = \mathcal N\big(\mu, \operatorname{diag}(\sigma^2)\big), \qquad \sigma = \log\big(1 + e^{\rho}\big).

Each weight now has two trainable numbers, μj\mu_j and ρj\rho_j, so the network doubles in size. The loss is the negative ELBO (the topic Variational inference):

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

The expectation is estimated with the reparameterization w=μ+σ⊙εw = \mu + \sigma \odot \varepsilon, ε∼N(0,I)\varepsilon \sim \mathcal N(0, I), often with a single sample per step. The data term is a sum over nn objects, so on a minibatch SS of BB objects it is rescaled exactly as in the topic Stochastic variational inference:

F^=KL(q ∥ p)−nB∑i∈Slog⁡p(yi∣xi,w).\hat F = \mathrm{KL}\big(q \,\|\, p\big) - \frac{n}{B} \sum_{i \in S} \log p(y_i \mid x_i, w).

With the prior N(0,1)\mathcal N(0, 1) on every weight, the KL is a sum over weights of

KL(N(μj,σj2) ∥ N(0,1))=log⁡1σj+σj2+μj22−12.\mathrm{KL}\big(\mathcal N(\mu_j, \sigma_j^2) \,\|\, \mathcal N(0, 1)\big) = \log\frac{1}{\sigma_j} + \frac{\sigma_j^2 + \mu_j^2}{2} - \frac{1}{2}.

It pulls each mean to zero, like weight decay, and each σj\sigma_j towards 11: a weight stays noisy unless the data term pays for precision. The prior matters in practice; Blundell et al. got better results with a scale mixture of two Gaussians than with a single one.

At test time, draw TT weight vectors from qq and average the predictions as in the previous block. The costs: twice the parameters; noisy gradients, because one ε\varepsilon is shared by the whole batch (the local reparameterization trick samples pre-activations instead of weights to decorrelate them); and a factorized Gaussian that hugs one mode and underestimates the spread, the mode-seeking reverse KL from the topic Variational inference.

MC dropout

Dropout multiplies each unit by a random mask zj∼Bernoulli⁡(1−p)z_j \sim \operatorname{Bernoulli}(1 - p) during training. Gal and Ghahramani (2016) showed that training with dropout and weight decay approximately maximizes an ELBO for a specific family: every weight matrix is W=Mdiag⁡(z)W = M \operatorname{diag}(z), a learned matrix MM with randomly zeroed columns. The variational parameters are the matrices MM; the dropout rate pp is fixed by hand and is part of the family.

Read this way, a network trained with dropout already carries an approximate posterior. MC dropout keeps dropout on at test time, runs TT forward passes with fresh masks and treats the outputs ft=f(x;wt)f_t = f(x; w_t) as samples from qq. With the noise precision β\beta, as in Bayesian linear regression,

E[y∣x]≈fˉ=1T∑t=1Tft,Var⁡[y∣x]≈β−1+1T∑t=1Tft2−fˉ 2.\mathbb E[y \mid x] \approx \bar f = \frac{1}{T} \sum_{t=1}^{T} f_t, \qquad \operatorname{Var}[y \mid x] \approx \beta^{-1} + \frac{1}{T} \sum_{t=1}^{T} f_t^2 - \bar f^{\,2}.

This is the decomposition of the first block again: noise plus the spread of networks.

MC dropout costs nothing extra in training and TT forward passes at prediction, which explains its popularity. The debate is about what qq really is. The family is tiny, and its shape is set by pp rather than learned: the dropout rate does not respond to the data. A true posterior concentrates as nn grows; nothing in this family is designed to. So MC dropout often gives useful error bars, but it is a cheap approximation with a Bayesian motivation, not a sampler from p(w∣D)p(w \mid D).

Deep ensembles

A deep ensemble (Lakshminarayanan et al., 2017) skips the posterior altogether. Train MM networks, typically M=5M = 5, from different random initializations. Each outputs a mean μm(x)\mu_m(x) and a variance σm2(x)\sigma_m^2(x) and is trained by the Gaussian negative log-likelihood. Predict with the uniform mixture

p(y∣x)=1M∑m=1MN(y∣μm(x),σm2(x)).p(y \mid x) = \frac{1}{M} \sum_{m=1}^{M} \mathcal N\big(y \mid \mu_m(x), \sigma_m^2(x)\big).

Its mean and variance follow from the mixture moments:

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

Different initializations and minibatch orders are enough diversity. Bagging made the results worse in the original experiments: a bootstrap sample holds only about 63% of the distinct objects, so each member learns from less data.

Nothing here is derived from Bayes' formula: there is no prior, no qq, and the weights of the mixture are uniform, not posterior probabilities. Yet ensembles often approximate the Bayesian model average better than Bayes by Backprop or MC dropout. The loss of a network has many basins that give different functions. Ensemble members land in different basins, while a Gaussian qq describes the neighbourhood of one basin. An ensemble covers several modes crudely; VI covers one mode carefully. The price is MM times the training, storage and prediction.

The Laplace approximation for networks

The Laplace approximation of the topic The Laplace approximation and Bayesian classification works on a network unchanged in principle. Train as usual to get wMAPw_{\text{MAP}}, then set q(w)=N(wMAP,H−1)q(w) = \mathcal N(w_{\text{MAP}}, H^{-1}) with H=−∇2log⁡p(w∣D)H = -\nabla^2 \log p(w \mid D) at wMAPw_{\text{MAP}}. It is the only method here that can be added after training to any network that already exists, with or without dropout.

At network scale two things change. HH is d×dd \times d with dd in the millions, and the exact Hessian of a loss that training never fully minimized can have negative eigenvalues. The standard fix is the generalized Gauss–Newton matrix, which keeps only the part built from first derivatives of the network output Ji=∂f(xi;w)/∂wJ_i = \partial f(x_i; w) / \partial w:

H≈αI+∑i=1nJi⊤ΛiJi,H \approx \alpha I + \sum_{i=1}^{n} J_i^\top \Lambda_i J_i,

where Λi\Lambda_i is the second derivative of the negative log-likelihood with respect to the output: β\beta for Gaussian regression, πi(1−πi)\pi_i(1 - \pi_i) for logistic. It is positive semidefinite by construction, and in practice it is further simplified to a diagonal or Kronecker-factored (KFAC) form, or applied to the last layer only. With the features ϕ(x)\phi(x) of the penultimate layer frozen, last-layer Laplace for regression is exactly Bayesian linear regression from topic 4: H=αI+βΦ⊤Φ=SN−1H = \alpha I + \beta \Phi^\top \Phi = S_N^{-1}.

Predictions use the linearization f(x;w)≈f(x;wMAP)+J(x)(w−wMAP)f(x; w) \approx f(x; w_{\text{MAP}}) + J(x)(w - w_{\text{MAP}}), which turns the Gaussian over weights into a Gaussian over outputs:

f(x;w)∼N(f(x;wMAP),  J(x) H−1J(x)⊤).f(x; w) \sim \mathcal N\big(f(x; w_{\text{MAP}}),\; J(x)\, H^{-1} J(x)^\top\big).

This works better than pushing weight samples through the nonlinear network. For a binary classifier the output is a logit with mean aMAPa_{\text{MAP}} and variance s2s^2, and the probit approximation of topic 6 finishes the job:

p(y=1∣x,D)≈σ(κ(s2) aMAP),κ(s2)=(1+πs2/8)−1/2.p(y = 1 \mid x, D) \approx \sigma\big(\kappa(s^2)\, a_{\text{MAP}}\big), \qquad \kappa(s^2) = \big(1 + \pi s^2 / 8\big)^{-1/2}.

Calibration and inputs far from the data

Uncertainty is useful only if it is honest. A classifier is calibrated if, among the inputs where it reports confidence cc, a fraction cc is classified correctly. A reliability diagram bins test predictions by confidence (the top softmax probability) and plots the accuracy in each bin against the average confidence there; a calibrated model lies on the diagonal. The expected calibration error sums the gaps with the bin sizes nbn_b as weights:

ECE=∑bnbn ∣acc⁡(b)−conf⁡(b)∣.\mathrm{ECE} = \sum_{b} \frac{n_b}{n}\, \big|\operatorname{acc}(b) - \operatorname{conf}(b)\big|.

Modern deep classifiers are usually overconfident. The cheapest repair is temperature scaling: replace softmax⁡(z)\operatorname{softmax}(z) by softmax⁡(z/τ)\operatorname{softmax}(z / \tau) with a single τ>0\tau > 0 fitted by negative log-likelihood on a held-out validation set. ECE alone is easy to game, since a model that always predicts the class frequencies is perfectly calibrated and useless, so report it next to a proper score such as NLL.

Calibration on the test distribution says little about inputs far from the data. A ReLU network is piecewise linear, so along a ray x=t x0x = t\, x_0 it eventually stays in one linear region and its logits grow linearly in tt. The top softmax probability then tends to 11 for almost every direction x0x_0: the network becomes arbitrarily confident exactly where it knows least. A constant τ\tau cannot stop a logit that grows without bound. The approximations of this topic help, but none removes the problem; in comparisons on shifted data, deep ensembles degrade the least.

SGLD and choosing an approximation

The course has one more route, sampling, and it scales too. Stochastic gradient Langevin dynamics (SGLD; Welling and Teh, 2011) is minibatch gradient ascent on log⁡p(w∣D)\log p(w \mid D) with Gaussian noise added at each step of size γt\gamma_t:

Δwt=γt2 g^t+ξt,ξt∼N(0,γtI),g^t=∇log⁡p(wt)+nB∑i∈St∇log⁡p(yi∣xi,wt).\Delta w_t = \frac{\gamma_t}{2}\, \hat g_t + \xi_t, \quad \xi_t \sim \mathcal N(0, \gamma_t I), \quad \hat g_t = \nabla \log p(w_t) + \frac{n}{B} \sum_{i \in S_t} \nabla \log p(y_i \mid x_i, w_t).

As γt\gamma_t decays, the injected noise (variance γt\gamma_t) dominates the minibatch noise (variance of order γt2\gamma_t^2), and the iterates become approximate posterior samples without an MH correction. They are correlated, as in the topic Monte Carlo and Markov chains, and each kept sample is a whole weight vector to store.

Method Distribution over weights Extra training Prediction Modes
Bayes by Backprop diagonal Gaussian (VI) retrain, twice the parameters TT passes one
MC dropout Bernoulli masks (VI) none if trained with dropout TT passes one
Deep ensemble none; MM MAP networks MM trainings MM passes several
Laplace Gaussian at wMAPw_{\text{MAP}} none; a Hessian after training one pass + Jacobian one
SGLD MCMC samples one long noisy run TT passes can move between, slowly

The practical reading: if retraining is off the table, use (last-layer) Laplace; if you can afford MM trainings, an ensemble is the most reliable under shift; if the network already uses dropout, MC dropout is free. All of them remain overconfident far from the data.

The course in one view

The course started with a coin. After three heads in three tosses the MLE says the next toss is heads with probability 11; the posterior predictive with a uniform prior says 4/54/5. A network that answers in an unseen gap with the confidence it learned on the data makes the same mistake at scale: it trusts a single value of its parameters.

The driving question was how to reason and predict when the parameters themselves are uncertain, and what to do when the exact computation is intractable. The answer never changed its target, the predictive integral ∫p(y∣x,θ) p(θ∣D) dθ\int p(y \mid x, \theta)\, p(\theta \mid D)\, d\theta. What changed is how much of it we could afford.

  • Exact. Conjugate priors, the evidence for comparing models, Bayesian linear regression and the RVM: the posterior in closed form.
  • Approximate. When conjugacy broke, the Laplace approximation put a Gaussian at the mode; EM and variational inference replaced the posterior with the best member of a family; Monte Carlo, Metropolis–Hastings and Gibbs sampling traded the bias of a family for noisy, correlated samples. Gaussian processes, Dirichlet processes and LDA applied these tools to priors over functions, partitions and topics.
  • At scale. Stochastic VI took minibatches, black-box VI dropped conjugacy, and this topic pointed both at networks with millions of weights.

Every method here is one of those tools in new clothes: Bayes by Backprop is black-box VI with stochastic minibatches, MC dropout is VI with a fixed family, Laplace for networks is topic 6 with Bayesian linear regression in its last layer, SGLD is MCMC with noisy gradients, and an ensemble is a crude average over models. The approximations get coarser as the models grow, and each is chosen for what it costs and what it buys. The question to ask of any of them stays the same: which posterior does it stand in for, and how far off is it?

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.