AI Logic

Uncertainty Estimation

Deep Ensembles

Updated:

How deep ensembles work. Left: the same input is passed through M independently trained networks, and the mean and variance of each prediction are combined into a mixture distribution. Right: the predictive distributions of five networks and the combined distribution for an input near the training data and an input far from it

Background and Overview

Deep ensembles estimate predictive uncertainty by training MM neural networks of the same architecture from different random initializations and mixing their predictive distributions into a single prediction. Lakshminarayanan et al. proposed the method in 2017 as a way to estimate uncertainty without Bayesian inference.

Even when accurate, neural networks are poor at expressing how much they should trust their own predictions, and they tend to be overconfident. Representative approaches to uncertainty are Bayesian neural networks, which place probability distributions on the weights (such as Bayes by Backprop), and MC dropout. Bayesian neural networks, however, require substantial changes to the training procedure and are computationally heavy.

Deep ensembles can be used with almost no change to ordinary training. The paper proposes a combination of three ingredients.

  • Train with a proper scoring rule: For regression, the network outputs a variance as well as a mean, and the negative log-likelihood (NLL) is used as the loss.
  • Smooth the predictive distribution with adversarial training: Inputs generated by FGSM are also used for training (optional).
  • Form an ensemble: MM networks are trained independently of each other, and their predictions are averaged.

As an analogy, it is like asking MM people who studied separately to solve the same problem. On familiar problems their answers agree, but on unfamiliar ones they diverge. How much they diverge is the uncertainty.

Theory

Deep ensembles are trained as follows (Algorithm 1 in the paper).

  1. Have each network output a probability distribution pθ(y∣x)p_\theta(y \mid \boldsymbol{x}). Use a proper scoring rule (explained below) as the loss.
  2. Initialize the weights θ1,…,θM\theta_1, \dots, \theta_M of the MM networks with different random seeds.
  3. Train the MM networks independently of each other (in parallel). Each network uses the entire training set, in a different order.
  4. (Optional) Generate an adversarial input x′\boldsymbol{x}' for each minibatch and minimize the sum of the losses on the original input and on x′\boldsymbol{x}'.

The defaults recommended by the paper are M=5M = 5 and an adversarial perturbation size ϵ\epsilon of 1% of the input range in each dimension (for example, 2.55 if the input ranges from 0 to 255).

A proper scoring rule is a way of evaluating predictions whose expected value is best when the predictive distribution matches the true distribution. Using the negative of such a rule as the loss drives training toward calibrated probabilities. The cross-entropy (log-likelihood) used for classification and the squared error between the probabilities and the one-hot label (the Brier score) are both proper scoring rules.

In regression, a network usually outputs only a predicted value μ(x)\mu(\boldsymbol{x}) and minimizes the mean squared error. That, however, says nothing about uncertainty. Instead, the final layer outputs two values, a mean μθ(x)\mu_\theta(\boldsymbol{x}) and a variance σθ2(x)>0\sigma^2_\theta(\boldsymbol{x}) > 0, and treating the observation as drawn from that Gaussian, the following negative log-likelihood is minimized (Eq. (1) in the paper).

−log⁡pθ(yn∣xn)=log⁡σθ2(x)2+(y−μθ(x))22σθ2(x)+constant-\log p_\theta(y_n \mid \boldsymbol{x}_n) = \frac{\log \sigma^2_\theta(\boldsymbol{x})}{2} + \frac{\bigl(y - \mu_\theta(\boldsymbol{x})\bigr)^2}{2\sigma^2_\theta(\boldsymbol{x})} + \text{constant}

The variance is made positive by passing the second output through softplus log⁡(1+e(⋅))\log(1 + e^{(\cdot)}), and a small value (for example 10−610^{-6}) is added for numerical stability.

Adversarial inputs are generated with FGSM, which shifts the input slightly in the direction that increases the loss ℓ(θ,x,y)\ell(\theta, \boldsymbol{x}, y).

x′=x+ϵ sign(∇xℓ(θ,x,y))\boldsymbol{x}' = \boldsymbol{x} + \epsilon \, \mathrm{sign}\bigl(\nabla_{\boldsymbol{x}} \ell(\theta, \boldsymbol{x}, y)\bigr)

Deep ensembles do not use bagging, which resamples the data with replacement for each model. In the paper's experiments, bagging hurt performance, because a bootstrap sample contains only about 63% of the original data. The paper reports that differences in random initialization and data order alone gave sufficient diversity among the networks.

Combining the Predictions

The predictions of the MM trained networks are treated as a uniformly weighted mixture (left of the figure above).

p(y∣x)=1M∑m=1Mpθm(y∣x)p(y \mid \boldsymbol{x}) = \frac{1}{M} \sum_{m=1}^{M} p_{\theta_m}(y \mid \boldsymbol{x})
  • Classification: Average the softmax probabilities of the MM networks.
  • Regression: The prediction is a mixture of MM Gaussians. For convenience, this mixture is approximated by a single Gaussian with the same mean and variance.

The mean μ∗\mu_* and variance σ∗2\sigma_*^2 of the mixture are computed as follows (Section 2.4 of the paper).

μ∗(x)=1M∑m=1Mμθm(x),σ∗2(x)=1M∑m=1M(σθm2(x)+μθm2(x))−μ∗2(x)\mu_*(\boldsymbol{x}) = \frac{1}{M} \sum_{m=1}^{M} \mu_{\theta_m}(\boldsymbol{x}), \qquad \sigma_*^2(\boldsymbol{x}) = \frac{1}{M} \sum_{m=1}^{M} \bigl(\sigma^2_{\theta_m}(\boldsymbol{x}) + \mu^2_{\theta_m}(\boldsymbol{x})\bigr) - \mu_*^2(\boldsymbol{x})

σ∗2\sigma_*^2 equals the sum of "the average of each network's variance" and "the spread among the networks' means." The former represents the ambiguity in the data itself, where the answer varies even for the same input; the latter represents the disagreement among the networks.

For example, suppose M=3M = 3 networks all predict a variance of 0.040.04 and predict means of (2.0,2.4,2.2)(2.0, 2.4, 2.2). Then μ∗=2.2\mu_* = 2.2 and σ∗2=0.04+0.027=0.067\sigma_*^2 = 0.04 + 0.027 = 0.067. If, for an input far from the training data, the means split into (1.4,3.0,2.2)(1.4, 3.0, 2.2), μ∗\mu_* is still 2.2, but σ∗2=0.04+0.427=0.467\sigma_*^2 = 0.04 + 0.427 = 0.467 becomes large, showing that this prediction is hard to trust (the right of the figure above illustrates the same idea).

The paper also shows a way to measure the disagreement among networks as the sum of KL divergences between each network's prediction and the ensemble's prediction, ∑mKL(pθm(y∣x) ∥ pE(y∣x))\sum_{m} \mathrm{KL}\bigl(p_{\theta_m}(y \mid \boldsymbol{x}) \,\|\, p_E(y \mid \boldsymbol{x})\bigr), where pEp_E is the ensemble's prediction (the average of the MM networks).

Why Ensembles Capture Uncertainty

The paper explains that deep ensembles capture two kinds of uncertainty.

  • Ambiguity in the data: Training to output a probability distribution with a proper scoring rule makes it possible to express that the answer varies even for the same input (the regression variance σθ2(x)\sigma^2_\theta(\boldsymbol{x})).
  • Model uncertainty: More than one network fits the training data. The MM networks trained from different initializations make similar predictions near the training data but tend to make different predictions far from it. That disagreement is the model uncertainty.

Adversarial training smooths the predictive distribution by raising the likelihood of the correct answer in the immediate neighborhood of the training data (within ϵ\epsilon). The paper explains that smoothing in every direction is computationally expensive and that a random direction does not necessarily increase the loss, whereas the adversarial direction is the one in which the loss grows, which makes it well suited to smoothing.

The paper also discusses how this differs from Bayesian model averaging. Bayesian model averaging assumes that the true model lies within the assumed family of models and softly selects the best model from that family. An ensemble, by contrast, combines models to create a more expressive model, so when the true model lies outside the assumed family, an ensemble can be expected to do better.

Findings from the Paper's Experiments

The paper evaluated deep ensembles on regression, classification, and detection of classes not seen in the training data.

1D regression (y=x3+ϵy = x^3 + \epsilon, 20 points): Outputting a variance and training with the NLL represented uncertainty better than using the spread of the predictions of 5 networks trained with squared error. Forming an ensemble improved the uncertainty further, especially far from the training data.

Regression benchmarks (10 datasets, M=5M = 5): Deep ensembles were compared with probabilistic backpropagation (PBP) and MC dropout (Table 1 in the paper; values are mean ± standard error).

DatasetRMSE: PBPRMSE: MC dropoutRMSE: Deep ensemblesNLL: PBPNLL: MC dropoutNLL: Deep ensembles
Boston housing3.012.973.282.572.462.41
Energy1.801.662.092.041.991.38
Naval propulsion plant0.010.010.00−3.73−3.80−5.63
Protein4.734.364.712.972.892.83
Yacht1.021.111.581.631.551.18

On NLL (lower is better), deep ensembles were best on most of the 10 datasets, and even on Concrete and Wine, where they were not, the gap was small. On RMSE, however, they were slightly worse on some datasets. The paper attributes this to optimizing the NLL rather than the squared error.

Classification (MNIST, SVHN): On MNIST with a 3-layer MLP, adversarial training and more networks substantially improved the error, NLL, and Brier score, and deep ensembles outperformed MC dropout (with the same number of samples) for every MM. On SVHN, adversarial training helped slightly at M=1M = 1, but its effect shrank as MM increased.

ImageNet (Inception network; only the effect of ensembling was studied): Both accuracy and the quality of the uncertainty improved as the number of networks increased.

MMTop-1 error (%)Top-5 error (%)NLLBrier score (×10−3\times 10^{-3})
122.1666.1290.9590.317
220.4625.2740.8670.294
519.1044.6370.8090.280
1018.6754.3640.7890.275

Classes not in the training data: When trained on MNIST and tested on images of letters (NotMNIST), the entropy of the predictions on the unknown classes rose much faster with MM than with MC dropout. MC dropout gave high confidence on some images even for unknown classes. The same trend held when training on SVHN and testing on CIFAR-10. When accuracy was measured only on predictions whose confidence exceeded a threshold, MC dropout had low accuracy even at high thresholds, while deep ensembles were much more robust.

Practical Caveats

Keep the following points in mind when using deep ensembles.

  • Costs grow by a factor of MM. Training and inference compute and the memory for the parameters all increase MM-fold. Because the MM networks are independent, however, they can be trained in parallel. For memory-constrained settings, the paper suggests distilling the ensemble into a single small model.
  • Initialize the networks with different random seeds. Training from the same initialization in the same order yields nearly identical networks with no disagreement.
  • For regression, output both a mean and a variance and train with the NLL. Using only the spread of the predictions of MM networks trained with squared error tends to underestimate uncertainty, as in the paper's 1D regression experiment.
  • Adversarial training is not required. The paper concludes that it helps on some datasets and metrics but is not needed in every case.

Deep ensembles are not an approximation to Bayesian inference. Read the predictive variance not as uncertainty derived from a posterior but as "the disagreement among independently trained networks." Also, no value of MM guarantees that inputs far from the training data will be detected. The paper itself notes that even exact Bayesian model averaging is not necessarily robust to distribution shift.

Comparison with Other Methods

Other methods for estimating uncertainty compare as follows.

MethodTrainingInferenceCharacteristics
Deep ensemblesTrain MM separate models independentlyForward passes through MM modelsSimple to implement and parallelizable; MM times the training and memory cost
MC dropoutOrdinary dropout training (once)TT forward passesWorks as is with existing models; in the paper's experiments, it was sometimes overconfident on unknown classes
Bayes by BackpropLearns a distribution over weights (mean and variance); twice the parametersSample weights several times and run forward passesApproximates the weight posterior with variational inference
SWAGAfter ordinary training, continue SGD and collect the mean and covariance of the weightsSample weights several times and run forward passesBuilds a weight distribution from a single training run
Temperature scalingTune a single temperature after trainingOne forward passOnly calibrates probabilities; does not estimate the spread of predictions

Rules of thumb for choosing:

  • If compute is available and the quality of the uncertainty is the priority, deep ensembles are a strong choice. In the paper's experiments, they outperformed MC dropout.
  • To train only once, consider methods that draw multiple predictions from a single model, such as MC dropout or SWAG.
  • If the only goal is to make the probabilities match accuracy, temperature scaling is enough.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
Deep ensembles (regression): train M networks that output a mean and a variance independently from different initializations,
and combine their predictions as a Gaussian mixture (Algorithm 1 and Section 2.4 of Lakshminarayanan et al., 2017)
"""

M = 5             # number of networks (the paper's recommended default)
epochs = 40
eps_ratio = 0.01  # adversarial perturbation size: 1% of the input range in each dimension


class GaussianMLP(nn.Module):
  """Outputs two values: the mean μ(x) and the variance σ²(x)"""
  def __init__(self, in_dim, hidden=50):
    super().__init__()
    self.body = nn.Sequential(nn.Linear(in_dim, hidden), nn.ReLU())
    self.head = nn.Linear(hidden, 2)

  def forward(self, x):
    out = self.head(self.body(x))
    mean = out[:, 0]
    var = F.softplus(out[:, 1]) + 1e-6  # make it positive with softplus and add a small value for stability
    return mean, var


def nll(mean, var, y):
  # Eq. (1) in the paper (without the constant). torch.nn.GaussianNLLLoss(reduction="mean") gives the same value
  return (0.5 * torch.log(var) + 0.5 * (y - mean) ** 2 / var).mean()


def train_one(model, loader, x_range, adversarial=True):
  optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
  eps = eps_ratio * x_range  # per-dimension ε
  model.train()
  for _ in range(epochs):
    for x, y in loader:
      x = x.clone().requires_grad_(adversarial)
      loss = nll(*model(x), y)
      if adversarial:
        # Generate the adversarial input x' = x + ε sign(∇x loss) with FGSM and add its loss
        grad, = torch.autograd.grad(loss, x, retain_graph=True)
        x_adv = (x + eps * grad.sign()).detach()
        loss = loss + nll(*model(x_adv), y)
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()
  return model


@torch.no_grad()
def ensemble_predict(models, x):
  """Returns the mixture mean μ* and variance σ*²"""
  for m in models:
    m.eval()
  means, vars_ = zip(*[m(x) for m in models])
  means, vars_ = torch.stack(means), torch.stack(vars_)   # [M, B]
  mu = means.mean(dim=0)
  var = (vars_ + means ** 2).mean(dim=0) - mu ** 2
  return mu, var


# Usage (train_loader yields (x, y) minibatches; x_train is the full set of training inputs)
# x_range = x_train.max(dim=0).values - x_train.min(dim=0).values
# models = []
# for m in range(M):
#   torch.manual_seed(m)  # initialize each network with a different random seed
#   models.append(train_one(GaussianMLP(in_dim=x_train.shape[1]), train_loader, x_range))
# mu, var = ensemble_predict(models, x_test)

FAQ

Q. How many networks $M$ should be used?
A.

The paper uses M=5M = 5 as its recommended default. In the ImageNet experiment, as MM grew from 1 to 10, the Top-1 error kept falling from 22.166% to 18.675% and the NLL from 0.959 to 0.789, but the gains gradually diminished. Training and inference costs grow in proportion to MM.

Q. Does classification also require outputting a mean and a variance?
A.

No. In classification, the softmax probabilities are already the predictive distribution, so each network is trained with ordinary cross-entropy (a proper scoring rule) and the MM sets of probabilities are averaged. Outputting a mean and a variance is for regression.

Q. How does it differ from [MC dropout](/uncertainty/mc-dropout)?
A.

MC dropout runs many forward passes through a single network with different dropout masks and averages over many networks that share weights. Deep ensembles train MM networks that share no weights, independently. Deep ensembles cost more, but in the paper's MNIST and SVHN experiments, they outperformed MC dropout at the same MM on error, NLL, and Brier score alike.

References

  1. Lakshminarayanan, B., Pritzel, A., & Blundell, C. (2017). Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles. Advances in Neural Information Processing Systems 30 (NIPS 2017). arXiv:1612.01474.
  2. Goodfellow, I. J., Shlens, J., & Szegedy, C. Explaining and Harnessing Adversarial Examples. arXiv:1412.6572.