Sub topic 13
Temperature scaling for neural networks
This chapter assumes you know softmax, logits (the raw scores before softmax), negative log-likelihood (NLL, which is log loss), and how to hold out a validation set.
Why neural networks need it
Modern deep networks tend to be overconfident. They are trained for many epochs with NLL, so the logits keep growing even after accuracy stops improving. The ranking of classes stays good, but a "0.99" prediction may be right only 90% of the time.
Platt scaling fits a slope and an intercept. Temperature scaling is the one-parameter version for softmax outputs. It divides every logit by a single positive number T:
p = softmax(z / T)
- T > 1 softens the distribution and reduces confidence.
- T < 1 sharpens it.
- T = 1 changes nothing.
What it does and does not change
Dividing all logits by the same positive number never changes which logit is largest. The predicted class, and therefore accuracy, stays identical. Only the confidence changes. This is the main advantage over isotonic regression or per-class methods. You cannot hurt accuracy, and with one parameter the overfitting risk is very small.
The cost is flexibility. One number cannot fix a model that is overconfident in some regions and underconfident in others.
Fitting T
Fit T by minimizing NLL on held-out logits. Optimizing log T keeps T positive. The function below searches T between about 0.05 and 20.
import numpy as np
from scipy.optimize import minimize_scalar
from scipy.special import log_softmax, softmax
def fit_temperature(logits, labels):
logits = np.asarray(logits, dtype=float)
labels = np.asarray(labels, dtype=int)
def nll(log_t):
t = np.exp(log_t)
log_p = log_softmax(logits / t, axis=1)
return -log_p[np.arange(len(labels)), labels].mean()
result = minimize_scalar(nll, bounds=(-3.0, 3.0), method="bounded")
return float(np.exp(result.x))
def nll_of(logits, labels, t=1.0):
log_p = log_softmax(logits / t, axis=1)
return -log_p[np.arange(len(labels)), labels].mean()
rng = np.random.default_rng(0)
n, k = 6000, 4
true_logits = rng.normal(size=(n, k)) * 1.5
probs = softmax(true_logits, axis=1)
labels = np.array([rng.choice(k, p=p) for p in probs])
# Simulate an overconfident network: logits inflated by a factor of 3.
logits = true_logits * 3.0
val_logits, test_logits = logits[:3000], logits[3000:]
val_labels, test_labels = labels[:3000], labels[3000:]
T = fit_temperature(val_logits, val_labels)
print("fitted T:", round(T, 2))
print("test NLL before:", nll_of(test_logits, test_labels))
print("test NLL after :", nll_of(test_logits, test_labels, T))
calibrated = softmax(test_logits / T, axis=1)
same_class = np.array_equal(calibrated.argmax(axis=1), test_logits.argmax(axis=1))
print("predictions unchanged:", same_class)Because the logits were inflated by 3, the fitted T should come out near 3. The test NLL should drop and the predictions should stay the same.
Common mistakes
- Fitting T on training data. The network is already overconfident there, so T will come out too small. Use a validation set the network never trained on.
- Reusing the test set. Tune T on validation data and report results on separate test data.
- Applying T to probabilities. T divides logits. If you only have probabilities, take their log first. This is equivalent up to a constant that softmax removes.
- Expecting a fix for shift. A T fitted on one distribution can be wrong on another.
Exercise
A network gets 92% accuracy on the test set. After temperature scaling with T = 2.3, what happens to the accuracy, and why? What does T > 1 do to the confidence of the predictions?
Show answer
Accuracy stays 92%. Dividing every logit by the same positive number keeps the largest logit largest, so each predicted class is unchanged. Because T > 1, the softmax output becomes flatter, so the top probability gets lower. This corrects overconfidence.