Uncertainty in Neural Networks
Deep ensembles, MC dropout and Bayesian neural networks.
A classifier that is 99% sure of a wrong answer is worse than one that says it does not know. This lesson separates the two kinds of uncertainty and measures them, proves that ReLU networks become arbitrarily confident far from their training data and that a little Bayesian treatment of the last layer cures it, compares the practical approximations (Laplace, variational inference, MC dropout, SWAG, deep ensembles), and checks which of them hold up when the data shift.
What you’ll learn
- Decompose the predictive entropy into an aleatoric and an epistemic part, and compute both for an ensemble.
- Prove that a ReLU classifier's confidence tends to 1 along almost every ray, and derive the bound that a Gaussian last layer places on it.
- Derive the Laplace approximation and the probit approximation of its predictive distribution, and explain MC dropout, variational inference and SWAG as alternatives.
- Compare deep ensembles with Bayesian approximations under dataset shift, and place conformal prediction as a distribution-free complement.
Two kinds of uncertainty, measured
A Bayesian predicts by averaging over plausible parameters, , in practice an average over samples or ensemble members, . Two sources of uncertainty mix in (Kendall & Gal, 2017; Hüllermeier & Waegeman, 2021). Aleatoric uncertainty is the noise each model predicts in given , which more data cannot remove. Epistemic uncertainty is disagreement among the plausible models, which more data shrinks. Information theory separates them exactly.
Treat as a random variable drawn from the posterior (or uniformly from the ensemble) and as drawn from . The mutual information between them is the drop in entropy from knowing :
Rearranged, the entropy of the averaged prediction splits into the average entropy of the members and their mutual information with the label:
The epistemic term is an average divergence from the consensus, so it is zero exactly when all members agree, however uncertain each one is:
A two-member ensemble classifies an input into two classes. Member 1 predicts , member 2 predicts . How large is the epistemic part, the mutual information, in nats?
Show the answer
0.37
The average is , with entropy . Each member's entropy is . The mutual information is . Had both members predicted , the total entropy would be the same , but all of it aleatoric: same output, very different situation.
Far from the data: ReLU networks are overconfident
The ray meets each convex region in an interval, and finitely many intervals cover , so one of them is unbounded: from some on, the ray stays in a single region , where the logits are affine in :
Let maximize over the rows of . Since no matrix has two identical rows, ties happen only on the hyperplanes , finitely many over all the regions' matrices, a set of measure zero; so for almost every the maximizer is unique.
Every exponent below then contains times a negative number and tends to :
Dividing the logits by a temperature changes the rate, not the limit, so recalibration cannot help: walk far enough from the data in almost any direction and the network becomes certain. Kristiadi, Hein & Hennig (2020) showed that being "a bit Bayesian" fixes this. Keep the ReLU feature map and put a Gaussian on the last-layer weights of a binary classifier.
The logit is then Gaussian with mean and variance . Approximating the sigmoid by a scaled probit, , makes the average computable (MacKay, 1992):
ReLU features are piecewise affine too, so along a ray eventually . The mean grows like and the standard deviation does as well, so their ratio converges:
The confidence is , with the adjusted logit. Cauchy–Schwarz and bound the limit uniformly over directions, so with positive definite the confidence stays bounded away from 1 (Kristiadi et al., 2020, Theorem 2.4):
A ReLU classifier is recalibrated with temperature . What happens to its confidence on inputs as , for a generic direction ?
- It still tends to 1, only more slowly
- It tends to
- It stays bounded below
- It tends to 0
Show the answer
A. It still tends to 1, only more slowly
The logits grow linearly in ; dividing them by divides the slope by 3 but the gap between the top logit and the rest still diverges, so the softmax still tends to a one-hot vector. Bounding the limit needs uncertainty that grows with the logits, such as a Gaussian over the last layer.
Approximating the posterior
A Bayesian neural network places a prior on the weights and predicts with the posterior . MacKay (1992) approximated it with a Gaussian around the most probable weights, and Neal (1996) sampled it with Hamiltonian Monte Carlo and showed that wide one-hidden-layer networks with suitably scaled Gaussian priors tend to Gaussian processes. For modern networks the posterior is high-dimensional and multimodal, and every practical method approximates it.
Expand the log posterior to second order around the maximum a posteriori weights , where its gradient vanishes:
Exponentiating gives a Gaussian posterior centered at the trained weights, with the inverse curvature as covariance: flat directions of the loss become uncertain directions of the weights.
For a network, the exact Hessian can be indefinite away from a true optimum, so one uses the generalized Gauss–Newton matrix, built from the Jacobians of the logits and the loss Hessian with respect to the logits, plus the prior precision . It is positive semidefinite by construction:
Practical variants keep only the last layer, or a Kronecker-factored or diagonal , and predict with a linearized network and the probit approximation or with samples. Daxberger et al. (2021) found such Laplace approximations competitive with more popular alternatives at a fraction of their cost; they are fitted after training, which itself is left unchanged.
| Method | What it approximates the posterior with | Cost | Caveats |
|---|---|---|---|
| Laplace (MacKay, 1992; Daxberger et al., 2021) | Gaussian at the trained weights, covariance from curvature | one training run plus a curvature estimate | local: one mode |
| Variational, "Bayes by Backprop" (Blundell, Cornebise, Kavukcuoglu & Wierstra, 2015) | factorized Gaussian fitted by maximizing the ELBO with the reparameterization trick | about twice the parameters; noisy gradients | mean-field families underestimate correlations; hard to scale |
| MC dropout (Gal & Ghahramani, 2016) | the dropout distribution, read as variational inference | stochastic forward passes at test time | the quality of the implied posterior is debated |
| SWAG (Maddox, Izmailov, Garipov, Vetrov & Wilson, 2019) | Gaussian from the SGD iterates: their mean plus a low-rank-plus-diagonal covariance | little beyond training | local: one mode |
| Hamiltonian Monte Carlo (Neal, 1996; Izmailov et al., 2021) | samples, asymptotically exact | orders of magnitude more compute | a reference standard more than a practical tool |
| Deep ensembles (Lakshminarayanan, Pritzel & Blundell, 2017) | networks trained from different random initializations | training runs | not derived from Bayes, yet spans several modes |
MC dropout is the cheapest of these to try. Leave dropout switched on at test time, run stochastic forward passes and average them; how much the passes disagree (for instance, the mutual-information term of the first step's decomposition, with the passes as members) is the epistemic signal. Gal & Ghahramani (2016) justified it as variational inference with a Bernoulli family over the weights.
That reading has been contested: a Bernoulli approximation is singular with respect to a continuous posterior, which leaves the variational objective ill-defined without a reinterpretation (Hron, Matthews & Ghahramani, 2018). As a practical baseline it holds up: on the CIFAR-10 and ImageNet shift benchmarks of Ovadia et al. (2019), dropout consistently did better than temperature scaling and last-layer methods, though deep ensembles did best.
How good is the exact posterior? Wenzel et al. (2020) found that for some image classifiers a "cold" posterior with , which overcounts the data, predicted better than the Bayes posterior itself. Izmailov, Vikram, Hoffman & Wilson (2021) then ran full-batch HMC on modern architectures: Bayesian model averaging outperformed standard training and deep ensembles in distribution, they found little evidence of a cold-posterior effect once data augmentation was accounted for, and the Bayesian networks generalized surprisingly poorly under domain shift. How much of each effect comes from the posterior itself, and how much from the prior, the likelihood and augmentation, is still debated.
Ensembles, shift and guarantees
A deep ensemble trains copies of a network from different random initializations and averages their predicted distributions. Lakshminarayanan, Pritzel & Blundell (2017) found it gave calibrated uncertainty as good as or better than approximate Bayesian networks, with higher uncertainty on out-of-distribution inputs. Fort, Hu & Lakshminarayanan (2019) explained the diversity: different random initializations end in different modes, which make different predictions, whereas weights sampled along one training trajectory or from a subspace around it cluster within a single mode in function space. Wilson & Izmailov (2020) read deep ensembles as an approximation to Bayesian model averaging across modes.
Ovadia et al. (2019) benchmarked the methods on dataset shift of increasing severity. Uncertainty quality degraded with shift for every method. Calibration on in-distribution data did not carry over; temperature scaling, well calibrated on the test set and under small shifts, was clearly beaten by methods that account for epistemic uncertainty as the shift grew. Deep ensembles did best across most metrics, and as few as five members may suffice.
Why do deep ensembles from different random initializations often give better uncertainty than samples drawn around a single trained network (as in SWAG or a local Laplace approximation)?
- Ensembles have more parameters per member
- Different initializations reach different modes that disagree in their predictions, while local samples stay within one mode
- Ensembles are trained with a proper Bayesian prior
- Averaging always increases accuracy, which improves uncertainty
Show the answer
B. Different initializations reach different modes that disagree in their predictions, while local samples stay within one mode
Epistemic uncertainty is disagreement among plausible models. Fort et al. found that random initializations explore functionally different modes, whereas weights sampled near one solution, though far apart in weight space, make similar predictions, so they understate the disagreement.
All of these methods give uncertainty estimates without guarantees. Conformal prediction supplies a guarantee for any model: using calibration data held out from training, it builds prediction sets with whenever calibration and test data are exchangeable. The guarantee is marginal (on average over inputs, not for each one), and it needs exchangeability, which shift breaks, so it complements epistemic uncertainty rather than replacing it. Conformal Prediction proves it.
Key takeaways
- Total predictive entropy splits exactly into the members' average entropy (aleatoric) and the mutual information between label and parameters (epistemic), which is zero when the members agree.
- A ReLU network's softmax tends to a one-hot vector along almost every ray, whatever the temperature; a Gaussian last layer bounds the limiting confidence by .
- Laplace approximations use with a Gauss–Newton curvature; variational inference, MC dropout and SWAG are other local approximations, and HMC is the expensive reference.
- Deep ensembles capture disagreement across modes and were the most robust under dataset shift in large benchmarks; conformal prediction adds marginal coverage guarantees under exchangeability.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the decomposition , which term measures epistemic uncertainty, and when is it zero?
- The total entropy; it is zero when the prediction is one-hot
- The expected entropy; it is zero when every member is certain
- The mutual information; it is zero exactly when all members make the same prediction
- Neither; epistemic uncertainty cannot be measured from predictions
Show the answer
C. The mutual information; it is zero exactly when all members make the same prediction
The mutual information equals the average KL divergence of the members from their consensus, so it vanishes exactly when they agree, whether or not they are individually confident.
In the Laplace approximation, what is the covariance of the Gaussian posterior?
- The inverse of the Hessian of the negative log posterior at the MAP weights
- The Hessian of the negative log posterior itself
- The empirical covariance of the training inputs
- The identity times the prior variance
Show the answer
A. The inverse of the Hessian of the negative log posterior at the MAP weights
Near its maximum the log posterior is approximately quadratic with curvature ; exponentiating a quadratic with curvature gives a Gaussian with covariance . High curvature means a well-determined direction and low variance.
According to Ovadia et al.'s (2019) benchmark, what happens to a network that was temperature-scaled on in-distribution validation data when the test data shift increasingly?
- It stays calibrated, because the temperature was fitted carefully
- Its calibration degrades, and methods that account for epistemic uncertainty, such as deep ensembles, do increasingly better
- Its accuracy stays constant
- It becomes underconfident on all shifted data
Show the answer
B. Its calibration degrades, and methods that account for epistemic uncertainty, such as deep ensembles, do increasingly better
Uncertainty quality degraded with shift for every method, and in-distribution calibration did not carry over. Temperature scaling did well on i.i.d. data and small shifts but was outperformed by ensembles and other methods that model epistemic uncertainty as the shift grew.
What does split conformal prediction guarantee, and under what assumption?
- Correct coverage for every individual input, under any distribution
- Calibrated probabilities, if the model is Bayesian
- Coverage of at least on average over inputs, if calibration and test data are exchangeable
- Lower test error, if the calibration set is large
Show the answer
C. Coverage of at least on average over inputs, if calibration and test data are exchangeable
The guarantee is marginal and holds for any model, provided the calibration and test points are exchangeable. Shift can break it, which is why it complements rather than replaces epistemic uncertainty.
Further reading
- B. Lakshminarayanan, A. Pritzel & C. Blundell, "Simple and scalable predictive uncertainty estimation using deep ensembles," NeurIPS (2017).
- Y. Gal & Z. Ghahramani, "Dropout as a Bayesian approximation: representing model uncertainty in deep learning," ICML (2016).
- M. Hein, M. Andriushchenko & J. Bitterwolf, "Why ReLU networks yield high-confidence predictions far away from the training data and how to mitigate the problem," CVPR (2019).
- A. Kristiadi, M. Hein & P. Hennig, "Being Bayesian, even just a bit, fixes overconfidence in ReLU networks," ICML (2020).
- Y. Ovadia, E. Fertig, J. Ren, Z. Nado, D. Sculley, S. Nowozin, J. Dillon, B. Lakshminarayanan & J. Snoek, "Can you trust your model's uncertainty? Evaluating predictive uncertainty under dataset shift," NeurIPS (2019).