Sub topic 13
Temperature scaling for neural networks
This chapter assumes you know logistic regression, the sigmoid and softmax functions, and the idea of a held-out validation split. It also assumes you have read the earlier chapters on log loss, reliability diagrams, and fitting a calibrator without leaking data.
Why neural networks need a simple fix
Modern deep networks are often accurate but overconfident. They keep training after the training set is fit, and log loss keeps rewarding larger logits on examples that are already right. The logits grow, softmax saturates, and the model reports 0.99 on predictions that are right only 90% of the time.
Platt scaling fits a slope and an intercept. Isotonic regression fits a step function. Both are flexible, and on a network with thousands of classes or a small validation set, that flexibility can overfit. Temperature scaling is the smallest correction that still addresses the main failure. It has one parameter.
The method
A network produces a logit vector z for each input. Softmax turns it into probabilities:
pk = exp(zk) / sumj exp(zj)
Temperature scaling divides every logit by one positive number T before the softmax:
pk = exp(zk / T) / sumj exp(zj / T)
The effect depends on T:
| Value of T | Effect on probabilities | Typical use |
|---|---|---|
| T > 1 | Softer, closer to uniform, lower confidence | Fixes overconfident networks |
| T = 1 | No change | The original model |
| T < 1 | Sharper, higher confidence | Fixes underconfident models |
Dividing all logits by the same positive number never changes their order. The largest logit stays largest, so the predicted class is the same before and after scaling. Accuracy is unchanged. Only the confidence changes.
This is the multiclass relative of Platt scaling. In the binary case it is Platt scaling with the intercept fixed at 0 and the slope equal to 1/T.
Fitting T
You fit T by minimizing the negative log-likelihood (NLL, the same as log loss) on a held-out validation set. The network weights stay frozen. Because log loss is a proper scoring rule, the minimizer is the temperature that makes the probabilities most honest on average.
The function below optimizes log T instead of T. This keeps T positive without a constraint, and the search is symmetric around no change (log T = 0).
import numpy as np
from scipy.optimize import minimize_scalar
from scipy.special import log_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))The bounds (-3, 3) allow T between about 0.05 and 20. The NLL is convex in 1/T, so a one-dimensional bounded search finds the minimum reliably. If the result lands at a bound, something is wrong with the inputs, such as logits that are already probabilities.
Using it end to end
The next script is self-contained. It simulates an overconfident three-class model by multiplying well-behaved logits by 3, fits T on a validation half, and checks log loss and accuracy on a test half. It reuses fit_temperature from above.
import numpy as np
from scipy.optimize import minimize_scalar
from scipy.special import log_softmax, softmax
def fit_temperature(logits, labels):
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 make_data(n, rng):
labels = rng.integers(0, 3, size=n)
base = rng.normal(size=(n, 3))
base[np.arange(n), labels] += 1.5
return base * 3.0, labels # the factor 3 makes the model overconfident
def log_loss_from_logits(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)
val_logits, val_labels = make_data(5000, rng)
test_logits, test_labels = make_data(5000, rng)
t = fit_temperature(val_logits, val_labels)
print("fitted T:", round(t, 2))
for name, temp in (("before", 1.0), ("after", t)):
probs = softmax(test_logits / temp, axis=1)
acc = (probs.argmax(axis=1) == test_labels).mean()
conf = probs.max(axis=1).mean()
nll = log_loss_from_logits(test_logits, test_labels, temp)
print(f"{name}: accuracy {acc:.3f}, mean confidence {conf:.3f}, log loss {nll:.3f}")Expect a fitted T near 3, because the logits were inflated by that factor. Accuracy is identical in the two rows. Mean confidence drops toward accuracy, and test log loss falls.
Applying it to a real network
In PyTorch or TensorFlow, the workflow is the same:
- Train the network on the training split. Use early stopping or model selection on a separate split if you need it.
- Run the frozen network on a calibration split and save the raw logits (the values before softmax) with the labels.
- Call
fit_temperatureon those saved arrays. - At inference time, divide logits by
Tbefore softmax. StoreTwith the model artifact.
You do not need to retrain or touch the weights. Fitting takes milliseconds on saved logits.
What it does not fix
Temperature scaling changes confidence by one global factor. That has limits:
- Shape errors. If the model is overconfident in one probability range and underconfident in another, a single
Tcannot fix both. Isotonic regression or a richer method handles this better, given enough data. - Per-class bias. One
Tis shared by all classes. If one class is systematically overpredicted,Twill not correct it. Vector scaling and matrix scaling add per-class parameters, but they bring back the overfitting risk. - Ranking. It preserves the argmax and the ranking of logits within a row. Across examples, the ranking by confidence is also preserved, so AUC-style discrimination metrics for the top class do not change.
- Distribution shift. A
Tfitted on validation data is only valid for similar data. See the chapter on shift and monitoring.
Common errors
- Applying
Tto probabilities instead of logits. Dividing probabilities byTdoes nothing useful. Work from logits, or convert probabilities withnp.logfirst. - Passing already-softmaxed output to
fit_temperature. The fit will pushTto a bound. - Calibrating after label smoothing or mixup without checking. These training tricks already change confidence, and the fitted
Tmay be below 1. - Fitting on a tiny validation set. One parameter is cheap, but a few hundred examples still give a noisy
T. Use at least a few thousand when you can, or cross-validate the fit.
Exercise
A trained network has 91% test accuracy and a fitted temperature of T = 2.4 on validation data. After you divide the logits by 2.4, what happens to test accuracy, and what does the value of T tell you about the original model?
Show answer
Test accuracy stays at 91%, because dividing all logits by the same positive number does not change which class has the largest logit. T > 1 means the original model was overconfident: softening the logits reduces its confidence to match how often it is actually correct.
Exercise
A colleague fits T on the same data used to train the network and reports T = 1.02 with a perfect reliability diagram on that data. Why is this not good evidence of calibration?
Show answer
The network has already fit its training data, so its training logits are not representative of its behavior on new inputs, and the fitted T is near 1 for that reason. Calibration must be fitted on a held-out calibration split and evaluated on a separate test split.