AI Logic

Uncertainty Estimation

MC Dropout

Updated:

How MC dropout works. The left side shows the flow of running the same input forward T times with a different dropout mask each time and computing the mean and variance; the right side compares the spread of T predictions for an input close to the training data and one far from it

Background and Overview

MC dropout (Monte Carlo dropout) is a method that keeps dropout enabled at inference time, runs many forward passes on the same input, and uses the mean of the predictions as the answer and their spread as the uncertainty. In 2016, Gal and Ghahramani showed that training with dropout amounts to an approximation of Bayesian inference, and derived the method from that result.

An ordinary neural network returns just one answer for one input and does not say "how confident" it is. The softmax output of a classifier looks like a probability, but as the paper points out, reading it as a measure of confidence is a mistake, because the softmax output can be close to 1 even for inputs far from the training data.

The principled way to handle uncertainty is a Bayesian neural network, which holds each weight as a probability distribution rather than a single value. However, methods such as Bayes by Backprop keep a mean and a variance for every weight, which doubles the number of parameters and slows down training.

MC dropout uses a model trained with ordinary dropout as is. Neither the training method nor the model architecture changes; only the following two things change at inference.

  • Dropout is not switched off, and units are dropped at random on every pass.
  • The same input is passed forward TT times, and the TT predictions are aggregated.

As an analogy, instead of asking one expert once, the same question is put to TT experts who each think slightly differently. If all their answers agree, the answer can be trusted; if the answers diverge, it becomes clear that "the model is not confident about this question." Each change in the units dropped by dropout yields a slightly different network (expert).

Theory

In the Bayesian view, the prediction for a new input x∗\boldsymbol{x}^* is the average over all weights ω\boldsymbol{\omega} that are plausible given the training data X,Y\boldsymbol{X}, \boldsymbol{Y} (Eq. (2) in the paper).

p(y∗∣x∗,X,Y)=∫p(y∗∣x∗,ω) p(ω∣X,Y) dωp(\boldsymbol{y}^* \mid \boldsymbol{x}^*, \boldsymbol{X}, \boldsymbol{Y}) = \int p(\boldsymbol{y}^* \mid \boldsymbol{x}^*, \boldsymbol{\omega}) \, p(\boldsymbol{\omega} \mid \boldsymbol{X}, \boldsymbol{Y}) \, d\boldsymbol{\omega}

Here p(ω∣X,Y)p(\boldsymbol{\omega} \mid \boldsymbol{X}, \boldsymbol{Y}) is the distribution of the weights after seeing the training data (the posterior). For deep networks, this posterior cannot be computed exactly.

The paper therefore approximates the posterior with the following distribution q(ω)q(\boldsymbol{\omega}).

Wi=Mi⋅diag([zi,j]j=1Ki−1),zi,j∼Bernoulli(pi)\boldsymbol{W}_i = \boldsymbol{M}_i \cdot \mathrm{diag}\bigl([z_{i,j}]_{j=1}^{K_{i-1}}\bigr), \qquad z_{i,j} \sim \mathrm{Bernoulli}(p_i)

Mi\boldsymbol{M}_i is the learned weight matrix of layer ii, zi,jz_{i,j} is a random variable taking the value 0 or 1, and Ki−1K_{i-1} is the number of units in the previous layer. When zi,j=0z_{i,j} = 0, unit jj of the previous layer is dropped. In other words, drawing one set of weights from q(ω)q(\boldsymbol{\omega}) is the same as creating one dropout mask.

The paper shows that the loss of ordinary training with dropout and L2 regularization (weight decay) corresponds to minimizing the KL divergence between this q(ω)q(\boldsymbol{\omega}) and the posterior of a deep Gaussian process (Eqs. (1)–(4) in the paper). The result holds regardless of network depth or activation function, but it assumes that dropout is applied before every weight layer.

In the paper, pip_i is the probability of keeping a unit. The p in PyTorch's nn.Dropout(p) is the probability of dropping a unit, so set pi=1−pp_i = 1 - p when applying the formulas.

Computing the Predictive Mean and Uncertainty

Inference proceeds as follows (left side of the figure above).

  1. Train a network with dropout in the usual way (using a dropout probability and weight decay).
  2. Keep dropout enabled at inference and run TT forward passes on the same input x∗\boldsymbol{x}^*, using a different mask (Wt\boldsymbol{W}^t) each time.
  3. Use the mean of the TT outputs as the prediction.
  4. Use the spread of the TT outputs as the uncertainty.

The predictive mean is given by the following equation (Eq. (6) in the paper). The paper calls this estimate MC dropout.

Eq(y∗∣x∗)(y∗)≈1T∑t=1Ty^∗(x∗,W1t,…,WLt)\mathbb{E}_{q(\boldsymbol{y}^* \mid \boldsymbol{x}^*)}(\boldsymbol{y}^*) \approx \frac{1}{T} \sum_{t=1}^{T} \hat{\boldsymbol{y}}^*\bigl(\boldsymbol{x}^*, \boldsymbol{W}_1^t, \dots, \boldsymbol{W}_L^t\bigr)

y^∗(x∗,W1t,…,WLt)\hat{\boldsymbol{y}}^*(\boldsymbol{x}^*, \boldsymbol{W}_1^t, \dots, \boldsymbol{W}_L^t) is the output of the forward pass with the tt-th mask, and LL is the number of layers.

For regression, the predictive variance is the sample variance of the TT outputs plus τ−1\tau^{-1}. τ\tau is the model precision (the inverse of the observation noise variance) and is determined from the keep probability pp, the prior length scale ll, the number of data points NN, and the weight decay coefficient λ\lambda by the following equation (Eq. (7) in the paper).

τ=p l22Nλ\tau = \frac{p\, l^2}{2 N \lambda}

For example, if T=5T = 5 passes on some input give (2.1,2.3,1.9,2.2,2.0)(2.1, 2.3, 1.9, 2.2, 2.0), the prediction is the mean 2.1 and the sample variance is 0.02. If an input far from the training data gives (1.2,3.4,2.0,4.1,1.8)(1.2, 3.4, 2.0, 4.1, 1.8), the mean is 2.5 but the sample variance is a large 1.16, indicating that this prediction is hard to trust.

For classification, the TT softmax outputs are averaged to obtain the class probabilities. Uncertainty is measured by the entropy of the averaged probabilities or by the "fraction of the TT passes that answered something other than the most frequent class" (the variation ratio). For example, if 3 of 5 passes answer "5" and 2 answer "7," the variation ratio is 1−3/5=0.41 - 3/5 = 0.4.

MC dropout can be applied as is to any existing model trained with dropout. Neither the model architecture nor the training method changes. The TT forward passes can be computed together by stacking TT copies of the input into a single batch.

Findings from the Paper's Experiments

The paper examines the uncertainty of MC dropout on three kinds of tasks: regression, classification, and reinforcement learning.

ExperimentResult
Regression (CO₂ concentration at the Mauna Loa Observatory, extrapolation)Standard dropout (inference that scales the weights by pp) confidently predicted unreasonable values at points far from the training data. MC dropout showed large uncertainty (standard deviation) at the same points, behaving similarly to a Gaussian process
Classification (MNIST, LeNet, dropout probability 0.5)12 images of the digit "1," rotated little by little, were each passed forward 100 times. The prediction changed from 1 → 5 → 7, and around the images where the class switched, the softmax outputs became very widely scattered
Regression benchmarks (10 datasets)Compared with variational inference (VI) and probabilistic backpropagation (PBP), MC dropout matched or outperformed them in both RMSE and predictive log-likelihood on every dataset except for RMSE on Yacht (where PBP was better). For example, the RMSE on Boston Housing was 4.32 for VI, 3.01 for PBP, and 2.97 for MC dropout
Reinforcement learning (Q-network)Thompson sampling using dropout uncertainty needed only 25 batches to exceed a reward of 1, faster than the 175 batches of ε-greedy

The regression experiments also report that the shape of the uncertainty depends on the activation function. In a ReLU network, the uncertainty grew the farther the input was from the training data, while in a tanh network it leveled off at a constant size. The paper explains that which Gaussian process a dropout network approximates is determined by the combination of activation function and weight regularization.

The number of forward passes TT was set to 1000 for the figures, but the paper reports that the mean and uncertainty could be estimated reasonably well even with T=10T = 10.

Practical Caveats and Comparison with Other Methods

Keep the following points in mind when using MC dropout.

  • Inference costs TT times as much. Training cost does not change, but each input requires TT forward passes. A larger TT gives a more stable estimate but is slower.
  • Enable only dropout. Calling model.train() in PyTorch also puts batch normalization into its training behavior (using batch statistics). Call model.eval() and then switch only the dropout layers back to training mode (see the code example).
  • The magnitude of the uncertainty depends on the choice of dropout probability and weight decay. The τ−1\tau^{-1} added to the regression variance also cannot be computed without fixing the prior length scale ll. In the paper's benchmarks, τ\tau is chosen by Bayesian optimization of the validation log-likelihood.
  • The approximation can be coarse. The paper itself states that the approximate predictive distribution is highly multimodal, and the mean and variance capture only part of it.

The differences from other methods for estimating uncertainty are as follows.

MethodTrainingInferenceCharacteristics
MC dropoutOrdinary dropout training (once)TT forward passesWorks as is with existing models. The easiest option
Bayes by BackpropLearns a distribution over weights (mean and variance); twice the parametersSample weights several times and run forward passesLearns the weight distribution directly. Training is expensive
Deep ensemblesTrain MM separate modelsForward passes through MM modelsTraining cost and memory are both MM times larger
Temperature scalingTune a single temperature after trainingOne forward passOnly calibrates probabilities; does not estimate the spread of predictions

An extension of the same idea to RNNs is Variational Dropout (RNN), which uses the same mask across time steps.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm

'''
Image classification task on MNIST
Train with dropout, then estimate uncertainty with MC dropout at inference
'''

# Hyperparameters
batch_size = 64       # Batch size
epochs = 5            # Number of epochs
learning_rate = 1e-3  # Learning rate
weight_decay = 1e-5   # Weight decay (L2 regularization)
drop_prob = 0.5       # Probability of dropping a unit
num_samples = 50      # Number of forward passes T at inference

# 'cuda' if available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Dataset and loaders
transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])

train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)

# Model (dropout before every weight layer)
model = nn.Sequential(
  nn.Flatten(),
  nn.Dropout(0.2),
  nn.Linear(28 * 28, 512), nn.ReLU(),
  nn.Dropout(drop_prob),
  nn.Linear(512, 512), nn.ReLU(),
  nn.Dropout(drop_prob),
  nn.Linear(512, 10)
).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)

# Training loop (same as ordinary dropout training)
for epoch in tqdm(range(epochs)):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()


# Keep only the dropout layers active at inference (batch norm etc. stay in eval mode)
def enable_dropout(model):
  model.eval()
  for m in model.modules():
    if isinstance(m, nn.Dropout):
      m.train()


# MC dropout: run T forward passes and average the softmax outputs
@torch.no_grad()
def mc_predict(model, x, T):
  enable_dropout(model)
  probs = torch.stack([torch.softmax(model(x), dim=1) for _ in range(T)])  # [T, B, 10]
  mean = probs.mean(dim=0)                                       # predictive probabilities
  entropy = -(mean * torch.log(mean + 1e-12)).sum(dim=1)         # predictive entropy (uncertainty)
  return mean, entropy


# Evaluation: compare uncertainty (entropy) between correct and incorrect predictions
correct = 0
total = 0
ent_correct, ent_wrong = [], []
for images, labels in test_loader:
  images, labels = images.to(device), labels.to(device)
  mean, entropy = mc_predict(model, images, num_samples)
  predicted = mean.argmax(dim=1)
  hit = predicted == labels
  correct += hit.sum().item()
  total += labels.size(0)
  ent_correct.append(entropy[hit].cpu())
  ent_wrong.append(entropy[~hit].cpu())

print(f"MC Dropout Accuracy: {100 * correct / total:.2f}%")
print(f"Mean entropy (correct): {torch.cat(ent_correct).mean():.3f}")
print(f"Mean entropy (incorrect): {torch.cat(ent_wrong).mean():.3f}")

FAQ

Q. How large should the number of forward passes T be?
A.

There is no fixed value; it is chosen as a trade-off between computation time and estimate stability. The paper uses T = 1000 for its figures but reports that the mean and uncertainty could be estimated reasonably well even with T = 10. The T forward passes can be computed together by stacking T copies of the input into a single batch.

Q. Can it be used on a model trained without dropout?
A.

No. MC dropout is based on the idea that training with dropout yields an approximation of the posterior over weights. Dropping units only at inference in a model that did not use dropout during training does not produce uncertainty in this sense.

Q. How does it differ from ordinary dropout inference?
A.

Ordinary inference switches dropout off, scales the weights down by the keep probability (in PyTorch, the outputs are scaled up during training instead), and runs a single forward pass. This approximates the average of T passes with one pass. MC dropout actually runs T forward passes, so in addition to the mean it also yields the spread (uncertainty). In the paper's regression benchmarks, the MC dropout mean achieved a lower RMSE than ordinary inference.

References

  1. Gal, Y., & Ghahramani, Z. (2016). Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning. Proceedings of the 33rd International Conference on Machine Learning (ICML 2016), PMLR 48, 1050–1059. arXiv:1506.02142.
  2. Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I., & Salakhutdinov, R. (2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting. Journal of Machine Learning Research, 15, 1929–1958.