AI Logic

Uncertainty Estimation

Temperature Scaling

Updated:

How temperature scaling works. Left: the flow from the input through the network, the logits, division by the temperature T, and the softmax to calibrated probabilities, along with the step that sets T on validation data. Right: bar charts of the probabilities of four classes when the same logits go through the softmax with T = 1 and T = 2

Background and Overview

Temperature scaling brings the probabilities output by a model closer to its actual accuracy simply by dividing the logits of a trained classifier by a single number (the temperature TT) before applying the softmax. Guo et al. proposed it in 2017 as a fix after showing that the probabilities of modern neural networks are skewed toward overconfidence.

A classifier outputs a probability (confidence) along with the predicted class. If the confidence can be trusted, it can drive decisions such as "send only low-confidence predictions to a human" or "give priority to information from other sensors." For that, about 80 out of 100 predictions with confidence 0.8 need to be correct. This property is called being calibrated. The paper defines perfect calibration as follows (Eq. (1) in the paper).

P(Y^=Y∣P^=p)=p,∀p∈[0,1]P\bigl(\hat{Y} = Y \mid \hat{P} = p\bigr) = p, \quad \forall p \in [0, 1]

Y^\hat{Y} is the predicted class, P^\hat{P} its confidence, and YY the true class.

Comparing a 5-layer LeNet with a 110-layer ResNet on CIFAR-100, the paper showed that the average confidence of LeNet is nearly equal to its accuracy, whereas ResNet, despite its higher accuracy, has an average confidence far above its accuracy (it is overconfident). As an analogy, it is like a weather forecast that says "90% chance of rain" every day when it actually rains only half the time. Even if it is right often, the numbers themselves cannot be trusted.

Temperature scaling corrects this mismatch after training. The model's weights stay unchanged and only a single TT is chosen on validation data, so it can be added to any model afterward.

Theory

Temperature scaling is the simplest multiclass extension of Platt scaling, a calibration method for binary classification. The procedure is as follows (left of the figure above).

  1. Train the model as usual (with T=1T = 1).
  2. Pass validation data not used for training through the trained model and collect the logits zi\boldsymbol{z}_i and labels yiy_i. The model's weights stay fixed.
  3. Choose a single T>0T > 0 that minimizes the negative log-likelihood (NLL, the same as cross-entropy) on the validation data when the logits are divided by TT and passed through the softmax.
  4. At inference, divide the logits by TT before the softmax.

After temperature scaling, the confidence is given by the following (Eq. (9) in the paper).

q^i=max⁡k σSM(zi/T)(k)\hat{q}_i = \max_k \, \sigma_{\mathrm{SM}}(\boldsymbol{z}_i / T)^{(k)}

σSM\sigma_{\mathrm{SM}} is the softmax, zi\boldsymbol{z}_i the logit vector of sample ii, and kk the class index. TT is a single number shared by all classes.

The NLL minimized in step 3 is the following (Eq. (6) in the paper), where π^(yi∣xi)\hat{\pi}(y_i \mid \boldsymbol{x}_i) is the probability the model assigns to the true class.

L=−∑i=1nlog⁡π^(yi∣xi)\mathcal{L} = -\sum_{i=1}^{n} \log \hat{\pi}(y_i \mid \boldsymbol{x}_i)

The probabilities change with TT as follows.

  • T>1T > 1: The softmax becomes flatter and the probabilities decrease (the output entropy increases). Overconfident models are corrected in this direction.
  • T=1T = 1: The original probabilities are unchanged.
  • T→∞T \to \infty: The probabilities of all classes approach 1/K1/K (KK is the number of classes), the state of maximum uncertainty.
  • T→0T \to 0: The probability of the largest class approaches 1.

Dividing all logits by the same number does not change which class has the largest logit. Therefore, the predicted class does not change, and neither does the accuracy. Only the level of confidence changes. On the right of the figure above, dividing the same logits by T=2T = 2 leaves the top class unchanged while its probability drops from 0.64 to 0.44.

Temperature scaling uses the same form of equation as the temperature that flattens the softmax in knowledge distillation. The difference is the purpose: knowledge distillation flattens the probabilities for training, while temperature scaling chooses TT on validation data to match the probabilities to the accuracy.

Measuring Miscalibration

Whether the probabilities are calibrated is checked by dividing the predictions into several intervals (bins) by confidence and comparing the "average confidence" with the "accuracy" in each bin.

  1. Divide the predictions by confidence into MM bins of equal width. The mm-th bin is (m−1M,mM]\bigl(\frac{m-1}{M}, \frac{m}{M}\bigr], and the set of samples falling into it is BmB_m.
  2. For each bin, compute the accuracy acc(Bm)\mathrm{acc}(B_m) and the average confidence conf(Bm)\mathrm{conf}(B_m).
  3. Average the difference between the two, weighted by the number of samples in each bin.

This value is called the ECE (Expected Calibration Error) (Eq. (3) in the paper).

ECE=∑m=1M∣Bm∣n∣acc(Bm)−conf(Bm)∣\mathrm{ECE} = \sum_{m=1}^{M} \frac{|B_m|}{n} \bigl| \mathrm{acc}(B_m) - \mathrm{conf}(B_m) \bigr|

nn is the number of samples. For a perfectly calibrated model, the ECE is 0. A plot of per-bin accuracy as bars against confidence is called a reliability diagram; if the bars lie on the diagonal, the model is calibrated.

The paper also uses two other measures.

  • MCE (Maximum Calibration Error): The maximum of the per-bin gap ∣acc(Bm)−conf(Bm)∣|\mathrm{acc}(B_m) - \mathrm{conf}(B_m)| (Eq. (5) in the paper). It looks at the worst-case mismatch.
  • NLL: The negative sum of the log probabilities of the true classes (Eq. (6) in the paper). It measures the quality of the predictive distribution as a whole.

The ECE depends on the number of bins MM and how the bins are defined. The paper computes it with M=15M = 15. When comparing values with other reports, use the same number of bins. The paper also notes that the MCE is very sensitive to the binning and is not suitable when there is little test data.

Why Networks Become Overconfident and Why One Number Fixes It

While stating that causation cannot be established, the paper identifies three factors strongly associated with overconfidence (Section 3 and Figure 2 of the paper).

  • Model capacity: For ResNet on CIFAR-100, making the network deeper or wider lowered the error but sharply raised the ECE. The paper explains that even after the network classifies almost all training data correctly, raising the confidence of its predictions still lowers the NLL, so higher-capacity models become more overconfident.
  • Batch normalization: In a 6-layer convolutional network, adding batch normalization slightly improved accuracy but worsened calibration.
  • Less weight decay: In a 110-layer ResNet, calibration got worse as weight decay was reduced. Even when weight decay was increased beyond the value that gave the best accuracy, calibration kept improving.

The paper also shows that during training, the error keeps falling even while the test NLL overfits. After the learning rate was lowered on CIFAR-100, the test error dropped from 29% to 27% during the stretch in which the NLL was getting worse. In other words, the network trades off the quality of its probabilities for higher accuracy.

The paper gives two reasons why a single number can correct this mismatch.

  • The mismatch has a simple form: The coefficients learned by vector scaling, which learns a separate coefficient for each class, turned out nearly identical, giving almost the same solution as temperature scaling. From this, the paper states that "network miscalibration is intrinsically low dimensional."
  • It is the maximum-entropy solution: The supplementary material shows that, under the constraints that "the probabilities sum to 1" and "the average logit of the true class equals the probability-weighted average logit," the form of the probabilities that maximizes the output entropy coincides with the temperature scaling equation.

Since choosing TT is a one-variable convex optimization, the paper notes that conjugate gradient finds it in about 10 iterations, in well under a second on an ordinary computer.

Findings from the Paper's Experiments

The paper compared calibration methods on image classification (6 datasets) and document classification (4 datasets). The following table shows ECE (%, M=15M = 15) excerpted from Table 1 of the paper. Lower means better calibrated.

DatasetModelUncalibratedHistogram binningIsotonic regressionVector scalingMatrix scalingTemperature scaling
CIFAR-100ResNet-11016.532.664.991.3225.491.26
CIFAR-100DenseNet-4010.372.684.511.0921.871.18
CIFAR-10ResNet-1104.60.580.810.881.00.83
ImageNetResNet-1525.484.364.772.23–1.86
BirdsResNet-509.194.345.223.021.131.85
20 NewsDAN (3 layers)8.023.65.524.619.14.11
ReutersDAN (3 layers)0.851.751.150.661.580.91

(See CIFAR-10/100, ImageNet, and DenseNet. Matrix scaling did not converge on ImageNet.)

The table shows the following.

  • Most models are not calibrated. The uncalibrated ECE was 4–10% in many cases. This happens in convolutional, recurrent, and fully connected networks alike.
  • With just one parameter, temperature scaling gave the lowest or near-lowest ECE in many cases. The paper concludes that it outperformed the other methods on the image tasks and was on par with them on the document tasks. There are cases, however, where histogram binning is lower, such as ResNet-110 on CIFAR-10 and 20 News.
  • More parameters do not mean better results. Because the number of parameters in matrix scaling grows with the square of the number of classes, it overfit the validation data on datasets with 100 or more classes and became worse than no calibration.
  • It does not help models that are already calibrated. Reuters had an ECE below 1% without calibration, and temperature scaling actually made it slightly larger.

For ResNet-110 on CIFAR-100, the NLL also dropped from 1.4978 to 1.0442, and the test error stayed at 27.83% (Tables S2 and S3 of the paper). Binning methods, by contrast, change the predicted classes, and with histogram binning the error rose to 34.78%.

Practical Caveats

Keep the following points in mind when using temperature scaling.

  • Set TT on data not used for training. On the training data, the model is nearly always correct, so the overconfidence does not show. The paper says the same validation set used for hyperparameter tuning is fine.
  • Set TT by NLL, not by accuracy. Since changing TT does not change the predicted class, accuracy cannot be used to choose TT.
  • Optimize only TT, keeping the network's weights fixed. Leave T=1T = 1 during training. In PyTorch, call model.eval() when collecting the logits so that the batch normalization statistics do not change.
  • Keep TT positive. A negative TT reverses the ranking of the classes. Keep it in the positive range, for example by optimizing log⁡T\log T.

Temperature scaling can only correct the confidence on data from the same distribution as the validation data. The paper assumes that the training, validation, and test data come from the same distribution. Also, because temperature scaling does not change the ranking of predictions, the order of high- and low-confidence predictions stays the same as before calibration. Unlike MC dropout or deep ensembles, it does not obtain new uncertainty information from the spread of predictions.

Comparison with Other Methods

Methods that calibrate probabilities after training and other methods for estimating uncertainty compare as follows.

MethodWhat is additionally learnedPredicted classInference costCharacteristics
Temperature scalingA single temperature TTUnchangedOne forward passSimplest and fastest; lowest or near-lowest ECE on many tasks
Vector and matrix scalingCoefficients of a linear transformation of the logits (2K2K, or K2+KK^2 + K)May changeOne forward passMatrix scaling overfits easily when there are many classes
Histogram binning and isotonic regressionPer-bin probabilitiesMay changeOne forward passCalibrates each class separately; predictions may change and accuracy may drop
MC dropoutNothing (uses a model trained with dropout)Determined by the averageTT forward passesDerives uncertainty from the spread of predictions
Deep ensemblesMM separate modelsDetermined by the averageForward passes through MM modelsMM times the training cost and memory

Rules of thumb for choosing:

  • If the only goal is to make the probability values themselves trustworthy, try temperature scaling first. It requires no retraining and does not change accuracy.
  • To make the model say "I don't know" on inputs far from the training data, consider methods that use the spread of predictions, such as MC dropout or deep ensembles. These can also be combined with temperature scaling.

PyTorch example

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

"""
Temperature scaling: keep the trained model's weights fixed and choose a single temperature T that minimizes the NLL on validation data
(Eq. (9) of Guo et al., 2017; optimized with L-BFGS, as in the reference implementation gpleiss/temperature_scaling)
"""


class ModelWithTemperature(nn.Module):
  def __init__(self, model):
    super().__init__()
    self.model = model
    # Learn log T to keep T > 0 (initial value T = 1)
    self.log_temperature = nn.Parameter(torch.zeros(1))

  @property
  def temperature(self):
    return self.log_temperature.exp()

  def forward(self, x):
    logits = self.model(x)
    return logits / self.temperature  # divide the pre-softmax logits by T

  @torch.no_grad()
  def collect_logits(self, loader, device):
    self.model.eval()  # do not change statistics such as batch normalization
    logits, labels = [], []
    for x, y in loader:
      logits.append(self.model(x.to(device)))
      labels.append(y.to(device))
    return torch.cat(logits), torch.cat(labels)

  def set_temperature(self, valid_loader, device="cpu"):
    logits, labels = self.collect_logits(valid_loader, device)
    optimizer = torch.optim.LBFGS([self.log_temperature], lr=0.01, max_iter=200)

    def closure():
      optimizer.zero_grad()
      loss = F.cross_entropy(logits / self.temperature, labels)  # NLL on the validation data
      loss.backward()
      return loss

    optimizer.step(closure)
    print(f"Temperature T = {self.temperature.item():.3f}")
    return self


def expected_calibration_error(logits, labels, n_bins=15):
  """ECE (Eq. (3) in the paper). Split the confidences into n_bins equal-width bins and average the gap from the accuracy"""
  probs = F.softmax(logits, dim=1)
  conf, pred = probs.max(dim=1)
  correct = pred.eq(labels).float()
  bins = torch.linspace(0, 1, n_bins + 1)
  ece = torch.zeros(1)
  for lo, hi in zip(bins[:-1], bins[1:]):
    in_bin = (conf > lo) & (conf <= hi)
    if in_bin.any():
      gap = (correct[in_bin].mean() - conf[in_bin].mean()).abs()
      ece += in_bin.float().mean() * gap
  return ece.item()


# Usage (model is a trained classifier whose output is the pre-softmax logits)
# scaled = ModelWithTemperature(model).set_temperature(valid_loader)
# test_logits, test_labels = scaled.collect_logits(test_loader, "cpu")
# print("ECE (before calibration)", expected_calibration_error(test_logits, test_labels))
# with torch.no_grad():
#   print("ECE (after calibration)", expected_calibration_error(test_logits / scaled.temperature, test_labels))

FAQ

Q. Does temperature scaling improve accuracy?
A.

No. Since all logits are divided by the same TT, the class with the largest logit does not change, and neither does the predicted class. Only the level of the probabilities changes. In the paper as well, for ResNet-110 on CIFAR-100, the test error stayed at 27.83% before and after temperature scaling.

Q. What values does $T$ typically take?
A.

For overconfident models, T>1T > 1, which flattens the probabilities. The value depends on the model and data, so it is set each time by the NLL on validation data. The paper's supplementary material shows that on CIFAR-100, the selected TT grows larger as training progresses and the output entropy decreases.

Q. How does it differ from the temperature in [knowledge distillation](/model-compression/knowledge-distillation)?
A.

The equation has the same form: the logits are divided by the temperature before the softmax. In knowledge distillation, the temperature is used during training to flatten the teacher model's probabilities and pass fine-grained information to the student model. Temperature scaling sets a single temperature on validation data after training, to match the probabilities to the accuracy.

References

  1. Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. (2017). On Calibration of Modern Neural Networks. Proceedings of the 34th International Conference on Machine Learning (ICML 2017), PMLR 70. arXiv:1706.04599.
  2. gpleiss/temperature_scaling (PyTorch implementation by the paper's authors)