The problem
A model that is overconfident says 98% when it is right only 75% of the time. Temperature scaling (Guo et al., 2017) is the simplest fix: divide every logit by one number before the softmax. With the probabilities get softer. It does not change which logit is largest, so the predictions, and the accuracy, stay exactly the same: only the confidences change. is chosen on a held-out validation set, to minimize the NLL (negative log-likelihood, section 2).
Example. Eight examples; the logits are or and every prediction has confidence . The right classes make the model right on 6 of 8: accuracy .
confidence NLL 1 2 5 (the best) At the best temperature the confidence is exactly the accuracy.
Finding : golden-section search
The NLL as a function of has one minimum here. Golden-section search finds the minimum of such a function by shrinking an interval that contains it:
- evaluate two interior points and , with ;
- if the minimum is to the left of : set ; otherwise set ;
- repeat; after
itersiterations return .
Each iteration shrinks the interval to of its length. After 60 iterations it is of the original.
What to implement
nll(logits, labels, T): the mean negative log-likelihood ofsoftmax(logits / T)against integerlabels, computed stably.fit_temperature(logits, labels, lo=0.05, hi=10.0, iters=60): golden-section search on .confidences(logits, T): the maximum softmax probability of each row at temperature .
Requirements
- Stable log-softmax (subtract the row maximum).