Probability Calibration via Temperature Scaling: Derive and Code It
Machine LearningModel answerLast updated
Derive the NLL gradient with respect to a single temperature scalar, then implement a numerically stable optimizer and calibrated inference function in Python.
Setup
You have a trained softmax classifier whose weights are fully frozen. For a given input, the network produces a logit vector z(x) ∈ ℝᴷ. Temperature scaling adjusts the confidence of those predictions by dividing every logit by a single positive scalar T before the softmax:
p_i(x; T) = exp(z_i(x) / T) / Σ_j exp(z_j(x) / T)
T is the only free parameter. It is learned on a held-out validation set — never on training data.
What you need to do
Part 1 — Derive the objective and its gradient.
- Write the mean negative log-likelihood (NLL) over a validation set of N labeled examples as a function of T. Use z_n to denote the logit vector for example n and y_n for its true class label.
- Differentiate the NLL with respect to T and simplify. Show all steps. Explain what the gradient tells you about when T should increase versus decrease.
- (Bonus) Show that the NLL is convex in β = 1/T and state what that implies for optimization.
Part 2 — Implement it.
Write the following three functions in Python (NumPy only, no deep learning frameworks):
fit_temperature(logits, labels)— learns T by minimizing the NLL on a validation set. T must remain strictly positive throughout.calibrate(logits, T)— applies a learned T to a new batch of logits and returns calibrated probabilities.expected_calibration_error(probs, labels)— computes ECE across equal-width confidence bins, for use as an evaluation metric (not as the optimization target).
Requirements:
- Use numerically stable log-softmax (subtract the row max before exponentiating).
- Enforce T > 0 throughout optimization.
- The optimizer should handle convergence gracefully and clip T to a reasonable range.
Part 3 — Edge cases and trade-offs.
Discuss at least two failure modes or practical considerations. For instance: what goes wrong if the validation set is perfectly classified? When would temperature scaling be insufficient and what would you try instead?
Hints
Hint 1
Temperature scaling only rescales logits — think about what that means for the argmax. Accuracy before and after should be identical. If your implementation changes predictions, something is wrong.
Hint 2
To keep T positive, do not optimize T directly. Instead optimize u = log T and recover T = exp(u). The chain rule gives dL/du = T · dL/dT, and u is unconstrained.
Hint 3
The gradient of the log-sum-exp term with respect to T involves the expected value of the logits under the current softmax distribution. Differentiating log Σ_j exp(z_j/T) with respect to T gives −(1/T²) Σ_j p_j z_j. Combine this with the derivative of the true-class term and you get a clean expression involving z_{y_n} minus the model's expected logit.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Derivation
The NLL objective
Let z_n ∈ ℝᴷ be the logit vector for the n-th validation example with true label y_n. The mean NLL over N examples is:
L(T) = −(1/N) Σ_n log p_{y_n}(x_n; T)
= (1/N) Σ_n [ −z_{n,y_n}/T + log Σ_j exp(z_{n,j}/T) ]
The first term is the true-class logit contribution; the second is the log-partition function.
Gradient with respect to T
Differentiate term by term for a single example:
True-class term:
d/dT (−z_{n,y}/T) = z_{n,y} / T²
Log-partition term (chain rule, noting d(z_j/T)/dT = −z_j/T²):
d/dT log Σ_j exp(z_{n,j}/T) = Σ_j p_{n,j} · (−z_{n,j}/T²)
= −E_{p_n}[z_n] / T²
Combining and averaging over N:
dL/dT = (1 / (N T²)) Σ_n ( z_{n,y_n} − E_{p_n}[z_n] )
Interpretation. The gradient is the average gap between the true-class logit and the logit the model expects under its own distribution.
- If true-class logits consistently exceed the model's expectation, dL/dT > 0, so gradient descent pushes T down — sharpening an underconfident model.
- If the model assigns too much probability mass to high-logit classes, the expectation exceeds the true-class logit, dL/dT < 0, and T rises — softening an overconfident model. This is the typical case for large neural nets.
Bonus: convexity in β = 1/T
Substituting β = 1/T:
L(β) = (1/N) Σ_n [ −β z_{n,y_n} + log Σ_j exp(β z_{n,j}) ]
This is a sum of a linear function (convex) and log-sum-exp of a linear function (convex), so L(β) is convex in β. Its second derivative equals (1/N) Σ_n Var_{p_n}(z_n) ≥ 0. Any local minimum is global, and 1-D Newton or L-BFGS converges in very few steps.
Part 2 — Implementation
import numpy as np
def _log_softmax(x):
"""Numerically stable row-wise log-softmax."""
m = x.max(axis=1, keepdims=True)
s = x - m
return s - np.log(np.exp(s).sum(axis=1, keepdims=True))
def _nll_and_grad(logits, labels, T):
"""Return (mean NLL, dNLL/dT) at temperature T."""
logits = np.asarray(logits, dtype=np.float64)
labels = np.asarray(labels, dtype=np.int64)
n = logits.shape[0]
idx = np.arange(n)
logp = _log_softmax(logits / T)
p = np.exp(logp)
nll = -logp[idx, labels].mean()
z_true = logits[idx, labels] # z_{n, y_n}
z_expected = (p * logits).sum(axis=1) # E_{p_n}[z_n]
grad_T = (z_true - z_expected).mean() / T**2
return nll, grad_T
def fit_temperature(logits, labels, T_init=1.0, lr=0.5,
max_iter=1000, tol=1e-8, T_min=1e-2, T_max=1e2):
"""
Learn T > 0 by minimizing NLL on the provided validation set.
Optimizes u = log T (unconstrained) with gradient descent
and Armijo backtracking line search.
"""
u = np.log(T_init)
u_lo, u_hi = np.log(T_min), np.log(T_max)
loss, grad_T = _nll_and_grad(logits, labels, np.exp(u))
for _ in range(max_iter):
T = np.exp(u)
g = T * grad_T # dL/du via chain rule
if abs(g) < tol:
break
step = lr
while True: # Armijo backtracking
u_new = np.clip(u - step * g, u_lo, u_hi)
new_loss, new_grad_T = _nll_and_grad(logits, labels, np.exp(u_new))
if new_loss <= loss - 1e-4 * step * g * g or step < 1e-12:
break
step *= 0.5
if abs(loss - new_loss) < tol:
u, loss, grad_T = u_new, new_loss, new_grad_T
break
u, loss, grad_T = u_new, new_loss, new_grad_T
return float(np.exp(u))
def calibrate(logits, T):
"""Return calibrated probabilities by applying temperature T to raw logits."""
logits = np.asarray(logits, dtype=np.float64)
return np.exp(_log_softmax(logits / T))
def expected_calibration_error(probs, labels, n_bins=15):
"""
ECE for evaluating calibration quality.
Use this for reporting — not as the optimization target.
"""
conf = probs.max(axis=1)
correct = (probs.argmax(axis=1) == labels).astype(float)
bins = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
for lo, hi in zip(bins[:-1], bins[1:]):
mask = (conf > lo) & (conf <= hi)
if mask.any():
ece += mask.mean() * abs(correct[mask].mean() - conf[mask].mean())
return ece
Typical usage:
- Run the frozen model on the validation split to collect
val_logitsandval_labels. T = fit_temperature(val_logits, val_labels)— expect T > 1 for overconfident deep nets.- At inference:
probs = calibrate(test_logits, T). - Sanity check: accuracy before and after must be identical; NLL and ECE should both decrease.
Verify the gradient with a central finite difference — interviewers notice this:
eps = 1e-5
L_plus, _ = _nll_and_grad(logits, labels, T + eps)
L_minus, _ = _nll_and_grad(logits, labels, T - eps)
fd_grad = (L_plus - L_minus) / (2 * eps)
# should match grad_T from _nll_and_grad
Part 3 — Edge cases and trade-offs
Perfectly separated validation set. When every example is confidently correct, z_{y_n} > E_{p_n}[z_n] for all n at every T. The gradient is always positive, so gradient descent keeps pushing T toward 0 with no finite minimum. The code handles this by clamping u to [log T_min, log T_max]. The real fix is using a harder or larger validation set.
Numerical stability with small T. As T → 0, logits/T grows large and naïve exp overflows. The max-subtraction trick in _log_softmax keeps this safe regardless of T.
When temperature scaling is not enough. A single scalar fixes overall confidence but cannot correct class-specific miscalibration. If the model is overconfident on class A and underconfident on class B, T finds a compromise that leaves both partially wrong. Alternatives in increasing order of flexibility:
- Vector scaling: one temperature per class. More expressive, but needs a larger validation set.
- Matrix scaling (Platt-style): affine transform of the logit vector before softmax.
- Isotonic regression or histogram binning: non-parametric, works without assumptions on logit structure, but requires many more calibration examples and can overfit small sets.
Distribution shift. A T fit on one data slice may be stale when the input distribution shifts — common in production recommendation or ranking systems. Refit T periodically on a fresh held-out window.
Common mistakes to avoid:
- Fitting T on training data. The model is overfit there; you will get T ≈ 1 or smaller, which is meaningless.
- Forgetting T > 0, or applying T to probabilities instead of logits — both break the math.
- Optimizing ECE directly. It is a binned, non-differentiable metric. NLL is the proper scoring rule to minimize; ECE is only for evaluation.
- Claiming temperature scaling improves accuracy. It cannot, because argmax is invariant to positive rescaling of logits.