Simple Algorithm
Machine Learning · Convergence · 28 min

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, p(y∣x,D)=∫p(y∣x,θ) p(θ∣D) dθp(y\mid\mathbf x,\data)=\int p(y\mid\mathbf x,\boldsymbol\theta)\,p(\boldsymbol\theta\mid\data)\,d\boldsymbol\theta, in practice an average over MM samples or ensemble members, pˉ(y∣x)=1M∑mp(y∣x,θm)\bar p(y\mid\mathbf x)=\frac1M\sum_mp(y\mid\mathbf x,\boldsymbol\theta_m). Two sources of uncertainty mix in pˉ\bar p (Kendall & Gal, 2017; Hüllermeier & Waegeman, 2021). Aleatoric uncertainty is the noise each model predicts in yy given x\mathbf x, which more data cannot remove. Epistemic uncertainty is disagreement among the plausible models, which more data shrinks. Information theory separates them exactly.

DerivationThe entropy decomposition
  1. I(y;θ∣x,D)=H[pˉ(⋅∣x)]−Eθ[H[p(⋅∣x,θ)]]I(y;\boldsymbol\theta\mid\mathbf x,\data)=H\big[\bar p(\cdot\mid\mathbf x)\big]-\E_{\boldsymbol\theta}\Big[H\big[p(\cdot\mid\mathbf x,\boldsymbol\theta)\big]\Big]

    Treat θ\boldsymbol\theta as a random variable drawn from the posterior (or uniformly from the ensemble) and yy as drawn from p(y∣x,θ)p(y\mid\mathbf x,\boldsymbol\theta). The mutual information between them is the drop in entropy from knowing θ\boldsymbol\theta:

  2. H[pˉ]⏟total=EθH[p(⋅∣x,θ)]⏟aleatoric+I(y;θ∣x,D)⏟epistemic\underbrace{H\big[\bar p\big]}_{\text{total}}=\underbrace{\E_{\boldsymbol\theta}H\big[p(\cdot\mid\mathbf x,\boldsymbol\theta)\big]}_{\text{aleatoric}}+\underbrace{I(y;\boldsymbol\theta\mid\mathbf x,\data)}_{\text{epistemic}}

    Rearranged, the entropy of the averaged prediction splits into the average entropy of the members and their mutual information with the label:

  3. I(y;θ∣x,D)=Eθ DKL(p(⋅∣x,θ) ∥ pˉ(⋅∣x)) ≥ 0I(y;\boldsymbol\theta\mid\mathbf x,\data)=\E_{\boldsymbol\theta}\,\KL\big(p(\cdot\mid\mathbf x,\boldsymbol\theta)\,\big\|\,\bar p(\cdot\mid\mathbf x)\big)\ \ge\ 0

    The epistemic term is an average divergence from the consensus, so it is zero exactly when all members agree, however uncertain each one is:

Predict before you look

A two-member ensemble classifies an input into two classes. Member 1 predicts (0.9,0.1)(0.9,0.1), member 2 predicts (0.1,0.9)(0.1,0.9). How large is the epistemic part, the mutual information, in nats?

Show the answer

0.37

The average is (0.5,0.5)(0.5,0.5), with entropy ln⁡2≈0.693\ln2\approx0.693. Each member's entropy is −0.9ln⁡0.9−0.1ln⁡0.1≈0.325-0.9\ln0.9-0.1\ln0.1\approx0.325. The mutual information is 0.693−0.325≈0.3680.693-0.325\approx0.368. Had both members predicted (0.5,0.5)(0.5,0.5), the total entropy would be the same 0.6930.693, but all of it aleatoric: same output, very different situation.

Far from the data: ReLU networks are overconfident

DerivationProof
  1. f(αx)=αVtx+atfor all α≥βf(\alpha\mathbf x)=\alpha V_t\mathbf x+\mathbf a_t\qquad\text{for all }\alpha\ge\beta

    The ray {αx:α≥0}\{\alpha\mathbf x:\alpha\ge0\} meets each convex region in an interval, and finitely many intervals cover [0,∞)[0,\infty), so one of them is unbounded: from some β\beta on, the ray stays in a single region QtQ_t, where the logits are affine in α\alpha:

  2. Let k⋆k^\star maximize vk⊤x\mathbf v_k^\top\mathbf x over the rows vk\mathbf v_k of VtV_t. Since no matrix has two identical rows, ties happen only on the hyperplanes (vk−vj)⊤x=0(\mathbf v_k-\mathbf v_j)^\top\mathbf x=0, finitely many over all the regions' matrices, a set of measure zero; so for almost every x\mathbf x the maximizer is unique.

  3. softmax⁡k⋆(f(αx))=11+∑j≠k⋆exp⁡(α(vj−vk⋆)⊤x+at,j−at,k⋆) → α→∞  1\softmax_{k^\star}\big(f(\alpha\mathbf x)\big)=\frac1{1+\sum_{j\ne k^\star}\exp\big(\alpha(\mathbf v_j-\mathbf v_{k^\star})^\top\mathbf x+a_{t,j}-a_{t,k^\star}\big)}\ \xrightarrow{\ \alpha\to\infty\ }\ 1

    Every exponent below then contains α\alpha times a negative number and tends to −∞-\infty:

Dividing the logits by a temperature TT 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 φ(x)\boldsymbol\varphi(\mathbf x) and put a Gaussian N(μ,Σ)\mathcal N(\boldsymbol\mu,\Sigma) on the last-layer weights of a binary classifier.

DerivationA Gaussian last layer bounds the confidence
  1. p(y=1∣x)=E[σ(a)]≈σ(m1+πs2/8)p(y=1\mid\mathbf x)=\E\big[\sigma(a)\big]\approx\sigma\Big(\frac{m}{\sqrt{1+\pi s^2/8}}\Big)

    The logit a=w⊤φa=\mathbf w^\top\boldsymbol\varphi is then Gaussian with mean m=μ⊤φm=\boldsymbol\mu^\top\boldsymbol\varphi and variance s2=φ⊤Σφs^2=\boldsymbol\varphi^\top\Sigma\boldsymbol\varphi. Approximating the sigmoid by a scaled probit, σ(a)≈Φ(π/8 a)\sigma(a)\approx\Phi(\sqrt{\pi/8}\,a), makes the average computable (MacKay, 1992):

  2. μ⊤(αu+c)1+π8(αu+c)⊤Σ(αu+c) → α→∞  μ⊤uπ8 u⊤Σu(u≠0)\frac{\boldsymbol\mu^\top(\alpha\mathbf u+\mathbf c)}{\sqrt{1+\frac\pi8(\alpha\mathbf u+\mathbf c)^\top\Sigma(\alpha\mathbf u+\mathbf c)}}\ \xrightarrow{\ \alpha\to\infty\ }\ \frac{\boldsymbol\mu^\top\mathbf u}{\sqrt{\frac\pi8\,\mathbf u^\top\Sigma\mathbf u}}\qquad(\mathbf u\ne\mathbf 0)

    ReLU features are piecewise affine too, so along a ray eventually φ(αx)=αu+c\boldsymbol\varphi(\alpha\mathbf x)=\alpha\mathbf u+\mathbf c. The mean grows like α\alpha and the standard deviation does as well, so their ratio converges:

  3. lim⁡α→∞σ(∣z(αx)∣)≤σ(∥μ∥π8λmin⁡(Σ))<1\lim_{\alpha\to\infty}\sigma\big(\abs{z(\alpha\mathbf x)}\big)\le\sigma\Big(\frac{\norm{\boldsymbol\mu}}{\sqrt{\frac\pi8\lambda_{\min}(\Sigma)}}\Big)<1

    The confidence is σ(∣z∣)\sigma(\abs z), with z=m/1+πs2/8z=m/\sqrt{1+\pi s^2/8} the adjusted logit. Cauchy–Schwarz and u⊤Σu≥λmin⁡(Σ)∥u∥2\mathbf u^\top\Sigma\mathbf u\ge\lambda_{\min}(\Sigma)\norm{\mathbf u}^2 bound the limit uniformly over directions, so with Σ\Sigma positive definite the confidence stays bounded away from 1 (Kristiadi et al., 2020, Theorem 2.4):

Check your understanding

A ReLU classifier is recalibrated with temperature T=3T=3. What happens to its confidence on inputs αx\alpha\mathbf x as α→∞\alpha\to\infty, for a generic direction x\mathbf x?

  1. It still tends to 1, only more slowly
  2. It tends to 1/K1/K
  3. It stays bounded below 1−1/T1-1/T
  4. It tends to 0
Show the answer

A. It still tends to 1, only more slowly

The logits grow linearly in α\alpha; dividing them by TT 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 p(θ)p(\boldsymbol\theta) on the weights and predicts with the posterior p(θ∣D)∝p(D∣θ) p(θ)p(\boldsymbol\theta\mid\data)\propto p(\data\mid\boldsymbol\theta)\,p(\boldsymbol\theta). 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.

DerivationThe Laplace approximation
  1. log⁡p(θ∣D)≈log⁡p(θMAP∣D)−12(θ−θMAP)⊤Λ (θ−θMAP),Λ=−∇2log⁡p(θ∣D)∣θMAP\log p(\boldsymbol\theta\mid\data)\approx\log p(\boldsymbol\theta_{\mathrm{MAP}}\mid\data)-\tfrac12(\boldsymbol\theta-\boldsymbol\theta_{\mathrm{MAP}})^\top\Lambda\,(\boldsymbol\theta-\boldsymbol\theta_{\mathrm{MAP}}),\qquad\Lambda=-\nabla^2\log p(\boldsymbol\theta\mid\data)\big|_{\boldsymbol\theta_{\mathrm{MAP}}}

    Expand the log posterior to second order around the maximum a posteriori weights θMAP\boldsymbol\theta_{\mathrm{MAP}}, where its gradient vanishes:

  2. p(θ∣D)≈N(θMAP, Λ−1)p(\boldsymbol\theta\mid\data)\approx\mathcal N\big(\boldsymbol\theta_{\mathrm{MAP}},\,\Lambda^{-1}\big)

    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.

  3. Λ≈∑i=1nJi⊤HiJi+τI\Lambda\approx\sum_{i=1}^nJ_i^\top H_iJ_i+\tau I

    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 JiJ_i of the logits and the loss Hessian Hi=diag⁡(pi)−pipi⊤H_i=\diag(\mathbf p_i)-\mathbf p_i\mathbf p_i^\top with respect to the logits, plus the prior precision τ\tau. It is positive semidefinite by construction:

  4. Practical variants keep only the last layer, or a Kronecker-factored or diagonal Λ\Lambda, 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.

MethodWhat it approximates the posterior withCostCaveats
Laplace (MacKay, 1992; Daxberger et al., 2021)Gaussian at the trained weights, covariance from curvatureone training run plus a curvature estimatelocal: one mode
Variational, "Bayes by Backprop" (Blundell, Cornebise, Kavukcuoglu & Wierstra, 2015)factorized Gaussian fitted by maximizing the ELBO with the reparameterization trickabout twice the parameters; noisy gradientsmean-field families underestimate correlations; hard to scale
MC dropout (Gal & Ghahramani, 2016)the dropout distribution, read as variational inferenceTT stochastic forward passes at test timethe 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 covariancelittle beyond traininglocal: one mode
Hamiltonian Monte Carlo (Neal, 1996; Izmailov et al., 2021)samples, asymptotically exactorders of magnitude more computea reference standard more than a practical tool
Deep ensembles (Lakshminarayanan, Pritzel & Blundell, 2017)MM networks trained from different random initializationsMM training runsnot derived from Bayes, yet spans several modes

MC dropout is the cheapest of these to try. Leave dropout switched on at test time, run TT 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 p(θ∣D)1/Tp(\boldsymbol\theta\mid\data)^{1/T} with T<1T<1, 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 MM 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.

Check your understanding

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)?

  1. Ensembles have more parameters per member
  2. Different initializations reach different modes that disagree in their predictions, while local samples stay within one mode
  3. Ensembles are trained with a proper Bayesian prior
  4. 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 C(x)C(\mathbf x) with Pr⁡(y∈C(x))≥1−α\Pr\big(y\in C(\mathbf x)\big)\ge1-\alpha 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 σ(∥μ∥/π8λmin⁡(Σ))\sigma\big(\norm{\boldsymbol\mu}/\sqrt{\frac\pi8\lambda_{\min}(\Sigma)}\big).
  • Laplace approximations use N(θMAP,Λ−1)\mathcal N(\boldsymbol\theta_{\mathrm{MAP}},\Lambda^{-1}) 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.

Question 1

In the decomposition H[pˉ]=EθH[p(⋅∣x,θ)]+I(y;θ∣x,D)H[\bar p]=\E_{\boldsymbol\theta}H[p(\cdot\mid\mathbf x,\boldsymbol\theta)]+I(y;\boldsymbol\theta\mid\mathbf x,\data), which term measures epistemic uncertainty, and when is it zero?

  1. The total entropy; it is zero when the prediction is one-hot
  2. The expected entropy; it is zero when every member is certain
  3. The mutual information; it is zero exactly when all members make the same prediction
  4. 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.

Question 2

In the Laplace approximation, what is the covariance of the Gaussian posterior?

  1. The inverse of the Hessian of the negative log posterior at the MAP weights
  2. The Hessian of the negative log posterior itself
  3. The empirical covariance of the training inputs
  4. 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 Λ\Lambda; exponentiating a quadratic with curvature Λ\Lambda gives a Gaussian with covariance Λ−1\Lambda^{-1}. High curvature means a well-determined direction and low variance.

Question 3

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?

  1. It stays calibrated, because the temperature was fitted carefully
  2. Its calibration degrades, and methods that account for epistemic uncertainty, such as deep ensembles, do increasingly better
  3. Its accuracy stays constant
  4. 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.

Question 4

What does split conformal prediction guarantee, and under what assumption?

  1. Correct coverage for every individual input, under any distribution
  2. Calibrated probabilities, if the model is Bayesian
  3. Coverage of at least 1−α1-\alpha on average over inputs, if calibration and test data are exchangeable
  4. Lower test error, if the calibration set is large
Show the answer

C. Coverage of at least 1−α1-\alpha on average over inputs, if calibration and test data are exchangeable

The guarantee Pr⁡(y∈C(x))≥1−α\Pr(y\in C(\mathbf x))\ge1-\alpha 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).