809. Calibrate a classifier with temperature scaling
Why it matters Calibrated confidence decides when an LLM classifier or router should abstain or escalate to a human.
Modern networks are often overconfident: they say 99% when they are right 80% of the time. Temperature scaling divides the logits by one number T > 0 chosen on a validation set. It changes confidence without changing any argmax prediction.
Write fit_temperature(logits, labels, temps). logits is (n, C), labels a length-n list of class ids, temps a list of candidate T values. For each T compute the mean negative log likelihood of softmax(logits / T) at the true labels (use a stable log-softmax). Return (best_T, best_nll) for the T with the lowest NLL (ties: the first in temps).
def fit_temperature(logits, labels, temps)Example 1
Input: fit_temperature([[2.0, 0.0], [0.0, 2.0]], [0, 1], [1.0, 2.0])
Output: (1.0, 0.1269)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Loop over candidate temperatures and score each one.
Hint 2
Use log-softmax with the row max subtracted so logits like 1000 do not overflow.
Hint 3
Keep the first T when two give the same NLL.
Common mistakes
- Multiplying by T instead of dividing.
- Computing softmax then log, which overflows or gives log(0) on large logits.
Understand the idea
Dividing logits by T > 1 flattens the softmax and lowers confidence; T < 1 sharpens it. The argmax never changes, so accuracy is untouched. The T with the lowest validation NLL is the best calibrated in the likelihood sense.
logits [2, 0] with true class 0 at T = 1: NLL = log(1 + e^-2) = 0.127.
NLL(T) = mean(-log_softmax(z / T)[y]); pick the minimum