AI Logic

Uncertainty Estimation

Bayes by Backprop

Updated:

How Bayes by Backprop works. Left: one training step, in which a set of weights is sampled from the mean and width parameters and standard normal noise, passed through the network, and used to compute the variational free energy. Right: an ordinary network whose weights are single values compared with a Bayes by Backprop network that holds a distribution for each weight

Background and Overview

Bayes by Backprop is a method that represents each weight of a neural network not as a single value but as a probability distribution (a mean and a width per weight), and learns that distribution with backpropagation. Blundell et al. proposed it in 2015 as a training procedure that approximates the posterior over the weights with variational inference.

An ordinary network finds only one set of weights that best fits the training data. As a result, it is prone to overfitting and tends to make confident predictions even where data is scarce. Giving the weights a distribution makes it possible to express uncertainty such as "any value in this range is fine for this weight." Sampling weights from the distribution at every prediction amounts to averaging over a collection (ensemble) of networks with slightly different weights.

The paper gives three reasons for putting uncertainty on the weights.

  • Regularization: The term that pulls the weight distribution toward the prior suppresses overfitting.
  • Cheap model averaging: With only twice the parameters, predictions are averaged over infinitely many networks.
  • Exploration: In bandit problems, a type of reinforcement learning, uncertain weights encourage exploration.

As an analogy, instead of a single expert saying "the answer is 3.2," each weight carries an answer with a range: "somewhere between 3.0 and 3.4, with 3.2 the most likely."

Theory

Bayesian inference computes the distribution of the weights after seeing the training data D\mathcal{D} (the posterior) P(w∣D)P(\boldsymbol{w} \mid \mathcal{D}), and predicts for a new input x^\hat{\boldsymbol{x}} by taking the expectation over the weights.

P(y^∣x^)=EP(w∣D)[P(y^∣x^,w)]P(\hat{y} \mid \hat{\boldsymbol{x}}) = \mathbb{E}_{P(\boldsymbol{w} \mid \mathcal{D})}\bigl[P(\hat{y} \mid \hat{\boldsymbol{x}}, \boldsymbol{w})\bigr]

This expectation corresponds to an ensemble of infinitely many networks, but it cannot be computed for networks of practical size. Instead, a tractable distribution q(w∣θ)q(\boldsymbol{w} \mid \theta) with parameters θ\theta is introduced, and the θ\theta that minimizes the KL divergence to the posterior is sought (variational inference). The loss to minimize is the following, called the variational free energy (Eq. (1) in the paper).

F(D,θ)=KL[q(w∣θ) ∥ P(w)]−Eq(w∣θ)[log⁡P(D∣w)]\mathcal{F}(\mathcal{D}, \theta) = \mathrm{KL}\bigl[q(\boldsymbol{w} \mid \theta) \,\|\, P(\boldsymbol{w})\bigr] - \mathbb{E}_{q(\boldsymbol{w} \mid \theta)}\bigl[\log P(\mathcal{D} \mid \boldsymbol{w})\bigr]

The first term is the complexity cost, which pulls the weight distribution toward the prior P(w)P(\boldsymbol{w}); the second is the likelihood cost, which fits the data. Balancing the two fits the data while keeping the weights simple.

The paper approximates this loss by Monte Carlo, using weights w(i)\boldsymbol{w}^{(i)} sampled from qq (Eq. (2) in the paper).

F(D,θ)≈∑i=1nlog⁡q(w(i)∣θ)−log⁡P(w(i))−log⁡P(D∣w(i))\mathcal{F}(\mathcal{D}, \theta) \approx \sum_{i=1}^{n} \log q(\boldsymbol{w}^{(i)} \mid \theta) - \log P(\boldsymbol{w}^{(i)}) - \log P(\mathcal{D} \mid \boldsymbol{w}^{(i)})

For qq, an independent Gaussian is used for each weight. Each weight has two parameters, a mean μ\mu and a parameter ρ\rho that sets the width, and the standard deviation is σ=log⁡(1+exp⁡(ρ))\sigma = \log(1 + \exp(\rho)) (so that σ\sigma is never negative whatever the value of ρ\rho). One training step proceeds as follows (Section 3.2 of the paper; left of the figure above).

  1. Sample noise from the standard normal distribution, ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(0, \boldsymbol{I}).
  2. Form the weights as w=μ+log⁡(1+exp⁡(ρ))∘ϵ\boldsymbol{w} = \boldsymbol{\mu} + \log(1 + \exp(\boldsymbol{\rho})) \circ \boldsymbol{\epsilon} (∘\circ is the element-wise product).
  3. Let θ=(μ,ρ)\theta = (\boldsymbol{\mu}, \boldsymbol{\rho}).
  4. Compute the loss f(w,θ)=log⁡q(w∣θ)−log⁡P(w)P(D∣w)f(\boldsymbol{w}, \theta) = \log q(\boldsymbol{w} \mid \theta) - \log P(\boldsymbol{w}) P(\mathcal{D} \mid \boldsymbol{w}).
  5. Compute the gradient for the mean, Δμ\Delta_\mu, and for the width parameter, Δρ\Delta_\rho, with Eqs. (3) and (4) below.
  6. With learning rate α\alpha, update μ←μ−αΔμ\boldsymbol{\mu} \leftarrow \boldsymbol{\mu} - \alpha \Delta_\mu and ρ←ρ−αΔρ\boldsymbol{\rho} \leftarrow \boldsymbol{\rho} - \alpha \Delta_\rho.
Δμ=∂f(w,θ)∂w+∂f(w,θ)∂μ,Δρ=∂f(w,θ)∂wϵ1+exp⁡(−ρ)+∂f(w,θ)∂ρ\Delta_\mu = \frac{\partial f(\boldsymbol{w}, \theta)}{\partial \boldsymbol{w}} + \frac{\partial f(\boldsymbol{w}, \theta)}{\partial \boldsymbol{\mu}}, \qquad \Delta_\rho = \frac{\partial f(\boldsymbol{w}, \theta)}{\partial \boldsymbol{w}} \frac{\boldsymbol{\epsilon}}{1 + \exp(-\boldsymbol{\rho})} + \frac{\partial f(\boldsymbol{w}, \theta)}{\partial \boldsymbol{\rho}}

The ∂f/∂w\partial f / \partial \boldsymbol{w} that appears in both equations is exactly the gradient computed by ordinary backpropagation. In other words, both the mean and the width can be learned simply by shifting and scaling the ordinary backpropagation gradient. This is where the method gets its name.

Writing the weights as μ+σ∘ϵ\boldsymbol{\mu} + \boldsymbol{\sigma} \circ \boldsymbol{\epsilon} and moving the randomness into ϵ\boldsymbol{\epsilon} is the same idea as the reparameterization trick used in the VAE. The paper notes that the difference is that it applies the trick to the weights, which are far more numerous, rather than to hidden units.

Prior and Minibatch Weighting

Prior: The paper proposes a scale mixture prior that mixes two zero-mean Gaussians with different variances (Eq. (7) in the paper).

P(w)=∏jπ N(wj∣0,σ12)+(1−π) N(wj∣0,σ22)P(\boldsymbol{w}) = \prod_j \pi \, \mathcal{N}(w_j \mid 0, \sigma_1^2) + (1 - \pi) \, \mathcal{N}(w_j \mid 0, \sigma_2^2)

Here σ1>σ2\sigma_1 > \sigma_2 and σ2≪1\sigma_2 \ll 1. The wide first component gives the prior heavier tails than a plain Gaussian, while the narrow second component concentrates many weights near 0. π\pi, σ1\sigma_1, and σ2\sigma_2 are shared by all weights, kept fixed during training, and chosen on validation data.

The paper reports that learning the prior parameters jointly through the gradient of the loss did not work well. The few prior parameters move faster than the many weight distributions, so the prior adapts to the poor weights of early training. Keep the prior fixed and choose it on validation data.

Because the KL divergence for this prior has no closed form, the paper computes the loss with the Monte Carlo approximation above (Eq. (2)). It reports that even for combinations where the KL can be written in closed form, the Monte Carlo approximation never performed worse.

Ordinary training can also be explained from the viewpoint of priors. Placing a Gaussian prior on the weights and choosing the single most probable set of weights gives L2 regularization (weight decay), and placing a Laplace prior gives L1 regularization (Section 2 of the paper). Bayes by Backprop differs in that it seeks the whole distribution rather than a single set of weights.

Minibatch weighting: When the training data is split into MM minibatches D1,…,DM\mathcal{D}_1, \dots, \mathcal{D}_M, the complexity cost is distributed across the minibatches (Eq. (9) in the paper).

Fiπ(Di,θ)=πi KL[q(w∣θ) ∥ P(w)]−Eq(w∣θ)[log⁡P(Di∣w)]\mathcal{F}_i^\pi(\mathcal{D}_i, \theta) = \pi_i \, \mathrm{KL}\bigl[q(\boldsymbol{w} \mid \theta) \,\|\, P(\boldsymbol{w})\bigr] - \mathbb{E}_{q(\boldsymbol{w} \mid \theta)}\bigl[\log P(\mathcal{D}_i \mid \boldsymbol{w})\bigr]

The πi\pi_i are weights that sum to 1; setting all of them to 1/M1/M recovers the full loss (Eq. (1)). The paper reports that πi=2M−i2M−1\pi_i = \frac{2^{M-i}}{2^M - 1} works well. The complexity cost dominates in the first minibatches of an epoch, and the data dominates in the later ones.

Computing Predictions and Uncertainty

At prediction time, several sets of weights are sampled from the learned distribution q(w∣θ)q(\boldsymbol{w} \mid \theta), a forward pass is run with each, and the outputs are averaged. This approximates the expectation EP(w∣D)\mathbb{E}_{P(\boldsymbol{w} \mid \mathcal{D})} above. The spread of the outputs across the sampled weights is the uncertainty of the prediction.

In the paper's regression experiment, an ordinary network shrank its uncertainty toward 0 in regions without training data and confidently committed to one particular function. With Bayes by Backprop, the prediction interval widened where there was no data, expressing that many extrapolations are plausible.

The learned width σ\sigma also serves as a measure of how important a weight is. The paper showed that setting weights to 0 in order of increasing ∣μi∣/σi|\mu_i| / \sigma_i (signal-to-noise ratio) barely reduces predictive performance (see the next section).

Findings from the Paper's Experiments

MNIST classification: Test error was compared for fully connected networks with two hidden layers of ReLU units (Table 1 in the paper). The networks were trained on 50,000 images, with 10,000 held out as validation data.

MethodHidden unitsWeightsTest error
SGD (no regularization)12002.4m1.88%
SGD + dropout12002.4m1.36%
Bayes by Backprop (Gaussian prior)12002.4m2.04%
Bayes by Backprop (scale mixture prior)12002.4m1.32%
SGD + dropout8001.3m1.33%
Bayes by Backprop (scale mixture prior)8001.3m1.34%

With the scale mixture prior, the error was on par with dropout. With the Gaussian prior, it stayed at about the level of unregularized SGD. In the learning curves, SGD dropped quickly and then overfit, while Bayes by Backprop and dropout dropped at about the same rate. However, one iteration of Bayes by Backprop takes about twice as long as one of dropout. After 600 epochs, Bayes by Backprop reached a lower error than dropout.

Weight pruning: In the 1200-unit network, weights were removed in order of increasing signal-to-noise ratio ∣μi∣/σi|\mu_i| / \sigma_i (Table 2 in the paper).

Proportion removedRemaining weightsTest error
0%2.4m1.24%
75%600k1.24%
95%120k1.29%
98%48k1.39%

Removing 95% of the weights barely hurt performance, while removing 98% hurt it noticeably. The paper points out that, unlike knowledge distillation, no retraining is needed: pruning follows from the properties of the learned distribution.

Bandit problem (mushroom data): In a task of choosing whether to eat a mushroom and receiving a reward, Thompson sampling, which selects actions with sampled weights, was used. It achieved lower cumulative regret (reward missed) than ε-greedy (ε = 0%, 1%, 5%), explored from the start, and quickly converged to a nearly perfect policy.

Practical Caveats

Keep the following points in mind when using Bayes by Backprop.

  • Twice the parameters and slower training. Each weight has a μ\mu and a ρ\rho, so the number of parameters doubles. On MNIST in the paper, one iteration took about twice as long as with dropout.
  • The choice of prior strongly affects the results. On MNIST in the paper, the Gaussian prior fell short of dropout, while the scale mixture prior matched it. Choose π\pi, σ1\sigma_1, and σ2\sigma_2 on validation data.
  • Weight the per-minibatch complexity cost correctly. If the KL term is added for every minibatch without dividing by the number of minibatches, the regularization becomes MM times too strong.
  • Sample weights at inference as well. Custom layers keep sampling weights even after model.eval() in PyTorch. It is possible to predict once using only the mean μ\mu, but then no uncertainty is obtained.

The paper itself notes that variational methods are known to underestimate uncertainty (although the paper's experiments showed no problem of insufficient exploration). The assumption of an independent Gaussian for each weight is an approximation that cannot represent correlations between weights. Read the resulting uncertainty as an approximation, not the exact posterior.

Comparison with Other Methods

Other methods for estimating uncertainty compare as follows.

MethodTrainingInferenceCharacteristics
Bayes by BackpropLearns a distribution over weights (mean and width) with variational inference; twice the parametersSample weights several times and run forward passesDirectly approximates the weight posterior; any prior can be chosen
MC dropoutOrdinary dropout training (once)TT forward passesWorks as is with existing models; the easiest option
Deep ensemblesTrain MM separate modelsForward passes through MM modelsNo Bayesian inference; MM times the training cost and memory
SWAGAfter ordinary training, continue SGD and collect the mean and covariance of the weightsSample weights several times and run forward passesBuilds a weight distribution without changing how the model is trained
Temperature scalingTune a single temperature after trainingOne forward passOnly calibrates probabilities; does not estimate the spread of predictions

Rules of thumb for choosing:

  • When the weight distribution itself is needed (for example, to prune by weight importance or to drive exploration in a bandit), Bayes by Backprop is a good fit.
  • To keep an existing training procedure unchanged, MC dropout or SWAG is easier.
  • As a regularizer that adds noise to the weights rather than randomly dropping them, DropConnect is another candidate to compare.

PyTorch example

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

"""
A small implementation of Bayes by Backprop (Blundell et al., 2015)
Each weight has a mean μ and a ρ, with σ = log(1 + exp(ρ)) (Section 3.2)
The prior is a scale mixture of two Gaussians (Eq. (7)); the loss is the Monte Carlo approximation of Eq. (2)
"""

PI, SIGMA1, SIGMA2 = 0.5, math.exp(-0), math.exp(-6)  # Candidates in the paper: π∈{1/4,1/2,3/4}, −log σ1∈{0,1,2}, −log σ2∈{6,7,8}


def log_gaussian(x, mu, sigma):
  return -0.5 * math.log(2 * math.pi) - torch.log(sigma) - (x - mu) ** 2 / (2 * sigma ** 2)


def log_scale_mixture_prior(w):
  p1 = torch.exp(log_gaussian(w, 0.0, torch.tensor(SIGMA1)))
  p2 = torch.exp(log_gaussian(w, 0.0, torch.tensor(SIGMA2)))
  return torch.log(PI * p1 + (1 - PI) * p2 + 1e-30).sum()


class BayesLinear(nn.Module):
  def __init__(self, in_features, out_features):
    super().__init__()
    self.w_mu = nn.Parameter(torch.empty(out_features, in_features).uniform_(-0.1, 0.1))
    self.w_rho = nn.Parameter(torch.full((out_features, in_features), -5.0))
    self.b_mu = nn.Parameter(torch.zeros(out_features))
    self.b_rho = nn.Parameter(torch.full((out_features,), -5.0))
    self.log_q = 0.0      # log q(w|θ) (value at the most recently sampled weights)
    self.log_prior = 0.0  # log P(w)

  def forward(self, x):
    w_sigma = F.softplus(self.w_rho)          # σ = log(1 + exp(ρ))
    b_sigma = F.softplus(self.b_rho)
    w = self.w_mu + w_sigma * torch.randn_like(w_sigma)  # w = μ + σ ∘ ε (sampled every time, including at inference)
    b = self.b_mu + b_sigma * torch.randn_like(b_sigma)
    self.log_q = log_gaussian(w, self.w_mu, w_sigma).sum() + log_gaussian(b, self.b_mu, b_sigma).sum()
    self.log_prior = log_scale_mixture_prior(w) + log_scale_mixture_prior(b)
    return F.linear(x, w, b)


class BayesMLP(nn.Module):
  def __init__(self, in_dim=784, hidden=400, out_dim=10):
    super().__init__()
    self.layers = nn.ModuleList([BayesLinear(in_dim, hidden), BayesLinear(hidden, hidden), BayesLinear(hidden, out_dim)])

  def forward(self, x):
    x = x.flatten(1)
    for i, layer in enumerate(self.layers):
      x = layer(x)
      if i < len(self.layers) - 1:
        x = F.relu(x)
    return x

  def complexity_cost(self):
    # log q(w|θ) − log P(w): a one-sample estimate of KL[q || P]
    return sum(l.log_q - l.log_prior for l in self.layers)


def elbo_loss(model, x, y, num_batches, n_samples=1):
  """Eq. (8): split the complexity cost into 1/M (M is the number of minibatches) and add the likelihood cost"""
  loss = 0.0
  for _ in range(n_samples):
    logits = model(x)
    nll = F.cross_entropy(logits, y, reduction="sum")  # −log P(D_i | w)
    loss = loss + model.complexity_cost() / num_batches + nll
  return loss / n_samples


@torch.no_grad()
def predict(model, x, n_samples=10):
  """Sample n_samples sets of weights and average the softmax probabilities"""
  probs = torch.stack([F.softmax(model(x), dim=1) for _ in range(n_samples)])  # [S, B, K]
  mean = probs.mean(dim=0)
  entropy = -(mean * torch.log(mean + 1e-12)).sum(dim=1)  # predictive entropy (uncertainty)
  return mean, entropy


# Usage
# model = BayesMLP()
# optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# for x, y in train_loader:
#   loss = elbo_loss(model, x, y, num_batches=len(train_loader))
#   optimizer.zero_grad(); loss.backward(); optimizer.step()
# mean, entropy = predict(model, x_test)

FAQ

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

Both run forward passes with slightly different weights at every prediction and average the outputs. MC dropout reuses ordinary dropout training and creates the variation in weights by dropping units. Bayes by Backprop learns a mean and a width for each weight and samples weights from that distribution. Bayes by Backprop holds an explicit weight distribution, but it doubles the number of parameters and requires changing the training procedure.

Q. Why use $\rho$ instead of learning $\sigma$ directly?
A.

The standard deviation σ\sigma must be positive. With σ=log⁡(1+exp⁡(ρ))\sigma = \log(1 + \exp(\rho)) (softplus), ρ\rho can be any real number and can be updated by unconstrained gradient descent. The gradient for ρ\rho is the sum of the ordinary backpropagation gradient ∂f/∂w\partial f / \partial \boldsymbol{w} multiplied by ϵ/(1+exp⁡(−ρ))\epsilon / (1 + \exp(-\rho)) and the direct gradient with respect to ρ\rho (Eq. (4) in the paper).

Q. How many sets of weights should be sampled at inference?
A.

The paper does not fix the number for inference, but for training it chose among averages of 1, 2, 5, and 10 samples on validation data, and it used the average of 2 samples in the bandit experiment. Sampling more makes the estimate more stable, but inference time grows proportionally.

References

  1. Blundell, C., Cornebise, J., Kavukcuoglu, K., & Wierstra, D. (2015). Weight Uncertainty in Neural Networks. Proceedings of the 32nd International Conference on Machine Learning (ICML 2015), JMLR W&CP 37. arXiv:1505.05424.