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 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 is MAP with a Gaussian prior (the topic The Bayesian approach), so the network is and nothing more. Give a regression network two outputs, a mean and a noise variance , and fit it to noisy observations of 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 for the coin:
Its variance splits by the law of total variance, with both moments taken over :
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 (the topic Bayesian linear regression). For a network neither term has a closed form, because has none.
The rest of the topic is four ways to approximate , 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 positive while stays unconstrained:
Each weight now has two trainable numbers, and , so the network doubles in size. The loss is the negative ELBO (the topic Variational inference):
The expectation is estimated with the reparameterization , , often with a single sample per step. The data term is a sum over objects, so on a minibatch of objects it is rescaled exactly as in the topic Stochastic variational inference:
With the prior on every weight, the KL is a sum over weights of
It pulls each mean to zero, like weight decay, and each towards : 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 weight vectors from and average the predictions as in the previous block. The costs: twice the parameters; noisy gradients, because one 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 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 , a learned matrix with randomly zeroed columns. The variational parameters are the matrices ; the dropout rate 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 forward passes with fresh masks and treats the outputs as samples from . With the noise precision , as in Bayesian linear regression,
This is the decomposition of the first block again: noise plus the spread of networks.
MC dropout costs nothing extra in training and forward passes at prediction, which explains its popularity. The debate is about what really is. The family is tiny, and its shape is set by rather than learned: the dropout rate does not respond to the data. A true posterior concentrates as 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 .
Deep ensembles
A deep ensemble (Lakshminarayanan et al., 2017) skips the posterior altogether. Train networks, typically , from different random initializations. Each outputs a mean and a variance and is trained by the Gaussian negative log-likelihood. Predict with the uniform mixture
Its mean and variance follow from the mixture moments:
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 , 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 describes the neighbourhood of one basin. An ensemble covers several modes crudely; VI covers one mode carefully. The price is 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 , then set with at . 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. is with 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 :
where is the second derivative of the negative log-likelihood with respect to the output: for Gaussian regression, 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 of the penultimate layer frozen, last-layer Laplace for regression is exactly Bayesian linear regression from topic 4: .
Predictions use the linearization , which turns the Gaussian over weights into a Gaussian over outputs:
This works better than pushing weight samples through the nonlinear network. For a binary classifier the output is a logit with mean and variance , and the probit approximation of topic 6 finishes the job:
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 , a fraction 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 as weights:
Modern deep classifiers are usually overconfident. The cheapest repair is temperature scaling: replace by with a single 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 it eventually stays in one linear region and its logits grow linearly in . The top softmax probability then tends to for almost every direction : the network becomes arbitrarily confident exactly where it knows least. A constant 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 with Gaussian noise added at each step of size :
As decays, the injected noise (variance ) dominates the minibatch noise (variance of order ), 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 | passes | one |
| MC dropout | Bernoulli masks (VI) | none if trained with dropout | passes | one |
| Deep ensemble | none; MAP networks | trainings | passes | several |
| Laplace | Gaussian at | none; a Hessian after training | one pass + Jacobian | one |
| SGLD | MCMC samples | one long noisy run | passes | can move between, slowly |
The practical reading: if retraining is off the table, use (last-layer) Laplace; if you can afford 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 ; the posterior predictive with a uniform prior says . 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 . 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.
Answers are saved on the server and tied to this browser until you sign in.