KatInterview

Probability Calibration via Temperature Scaling: Derive and Code It

Machine LearningModel answer
MediumModel answerMachine Learningcalibrationsoftmaxgradient-descent

Last 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.

  1. 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.
  2. 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.
  3. (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.