Temperature scaling on an all-correct validation set drives T toward zero

I added temperature scaling to a classifier so its probabilities would mean something. On the frozen test set, calibration got much worse: expected calibration error went from 0.162 to 0.452 for one model. The temperatures fitted for three models were all well below 1: 0.31, 0.19 and 0.05.

TL;DR — if every validation sample is classified correctly, the NLL keeps decreasing as T goes to 0, so « fit T by minimizing NLL » has no interior optimum and returns whatever lower bound you gave it. Fit T only when the validation set is big and varied enough (I use at least 30 videos and 3 classes), otherwise keep T = 1 and record why.

The setup

The model is an audio classifier for an Android app: it listens to short windows of sound and outputs one probability per class, and the app averages those probabilities over all windows of a recording (« video ») to rank the likely classes. Temperature scaling is the standard post-hoc fix for overconfidence: divide the logits by a single scalar T before the softmax, with T chosen to minimize negative log-likelihood (NLL) on a held-out validation set. T > 1 softens the probabilities, T < 1 sharpens them. ECE (expected calibration error) measures the gap between stated confidence and observed accuracy; 0 is perfect. My fit ran LBFGS on log T, clamped to [0.05, 50].

The catch: the validation split held only 6 videos, 5 of one class and 1 of another, and the model got all 6 right. The test set was frozen: the same 29 videos for every model.

What I expected

Temperature scaling has one parameter, so I assumed it could not overfit much. Worst case, I thought, a small validation set gives a noisy T somewhere near 1.

What actually happens

Three models, three fitted temperatures, all below 1: 0.31, 0.19, 0.05. The last one is not an optimum, it is the clamp. Every probability got sharper, and the test numbers moved the wrong way:

Model ECE with fitted T ECE with T = 1
first model (fitted T = 0.19) 0.340 0.046
second model (fitted T = 0.31) 0.452 0.162

Because the app averages probabilities per video, sharpening also changed the ranking: the second model’s top-3 macro score on the test (share of videos whose true class is among the top 3, averaged per class) went from 0.506 at T = 1 to 0.456 with T = 0.31. Its reliability curve at T = 1 (confidence 0.28 to 0.64 for accuracy 0 to 0.5) sat fairly close to the diagonal. The gap came from T.

Widening the clamp did not help. With a floor of 0.01, the third fit landed at T = 0.023 and its test ECE went from 0.232 (at the 0.05 floor) to 0.310.

This NumPy script reproduces the drift on a fake 6-sample validation set where every prediction is right, then flips one sample to wrong:

import numpy as np

def nll(logits, y, T):
    z = logits / T
    z = z - z.max(axis=1, keepdims=True)
    logp = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
    return -logp[np.arange(len(y)), y].mean()

rng = np.random.default_rng(0)
y = np.array([0, 0, 0, 0, 0, 1])               # 6 val videos: 5 of one class, 1 of another
logits = rng.normal(size=(6, 4))
logits[np.arange(6), y] += 3.0                 # every one is predicted correctly
assert (logits.argmax(1) == y).all()

grid = np.exp(np.linspace(np.log(0.01), np.log(10), 400))
best = grid[np.argmin([nll(logits, y, T) for T in grid])]
print(f"all correct : best T on [0.01, 10] = {best:.3f}")
for T in [2.0, 1.0, 0.5, 0.31, 0.19, 0.05, 0.01]:
    print(f"  T={T:<5} NLL={nll(logits, y, T) + 0.0:.2e}")

wrong = logits.copy(); wrong[5, [1, 2]] = wrong[5, [2, 1]]   # one video now wrong
best_w = grid[np.argmin([nll(wrong, y, T) for T in grid])]
print(f"one wrong   : best T on [0.01, 10] = {best_w:.3f}")

Output:

all correct : best T on [0.01, 10] = 0.010
  T=2.0   NLL=6.48e-01
  T=1.0   NLL=3.03e-01
  T=0.5   NLL=7.91e-02
  T=0.31  NLL=1.86e-02
  T=0.19  NLL=2.14e-03
  T=0.05  NLL=2.89e-09
  T=0.01  NLL=0.00e+00
one wrong   : best T on [0.01, 10] = 1.624

The « best » T is the edge of the search grid. One wrong sample is enough to produce a real minimum, here above 1.

Mean NLL on a 6-sample validation set as a function of temperature T, log scale. When all 6 are correct (red) the NLL falls monotonically to 0 as T goes to 0.01, so the minimum is the edge of the range. With one of the 6 wrong (blue) the curve has an interior minimum at T = 1.62 and rises to 84 at T = 0.01.

The fix

Gate the fit on the size and diversity of the validation set, fall back to T = 1 (the scale the model was trained at), and write the reason next to the temperature so a later reader knows the value is a default and not a measurement:

import numpy as np

MIN_VIDEOS, MIN_CLASSES, MAX_SHARE = 30, 3, 0.7

def choose_temperature(n_videos, video_classes, fit):
    """video_classes: one label per val video. fit: callable returning the NLL-optimal T."""
    counts = np.bincount(video_classes) if n_videos else np.array([0])
    n_classes = int((counts > 0).sum())
    info = {"n_videos": n_videos, "n_classes": n_classes}
    if n_videos < MIN_VIDEOS:
        return 1.0, {**info, "source": "default", "reason": f"{n_videos} val videos < {MIN_VIDEOS}"}
    if n_classes < MIN_CLASSES:
        return 1.0, {**info, "source": "default", "reason": f"{n_classes} val classes < {MIN_CLASSES}"}
    if counts.max() / n_videos > MAX_SHARE:
        return 1.0, {**info, "source": "default", "reason": "one class owns > 70 % of val videos"}
    return fit(), {**info, "source": "val"}

print(choose_temperature(6, np.array([0, 0, 0, 0, 0, 1]), fit=lambda: "fitted T"))
print(choose_temperature(40, np.arange(40) % 4, fit=lambda: "fitted T"))
(1.0, {'n_videos': 6, 'n_classes': 2, 'source': 'default', 'reason': '6 val videos < 30'})
('fitted T', {'n_videos': 40, 'n_classes': 4, 'source': 'val'})

Count videos, not windows. Any number of windows cut from 6 recordings are still 6 independent samples. The third rule (no class owning more than 70 % of the videos) came out of code review: a validation set of 30 videos that are nearly all one easy class would bring the same problem back. The thresholds are a judgment call, not derived. At the same time I made the validation split grow by routing about 15 % of new recordings, from sources never used for training, into it, so the fit can come back on its own once the set is large enough.

Why it works

With T > 0, dividing the logits by T keeps the argmax. For a correct sample, the true-class logit is the largest, so as T → 0 its softmax probability → 1 and its log-loss → 0. If every sample is correct, the mean NLL is a sum of terms that all decrease toward 0 as T shrinks, and the minimizer runs to whatever lower bound it is given. An optimizer working on log T sees a gradient that never changes sign and walks off.

A wrong sample does the opposite: its true-class logit is not the max, so as T → 0 its probability → 0 and its loss → ∞. Only the balance between confident-correct and confident-wrong samples creates an interior optimum. A validation set with no errors cannot represent that balance, and a small, easy one, like 5 videos of one class and 1 of another, is very likely to have no errors. T = 1 is the safer default. It is not proven calibrated. It is just the scale the cross-entropy training already pushed toward, which is a better bet than a number fitted to nothing.

What I did not test

  • Only plain scalar temperature scaling. Vector scaling and per-group temperatures were left aside because a validation set this small cannot judge them.
  • The 30-video and 3-class thresholds were not tuned. With T = 1 the test ECE drops below 0.15 on the current model, but the test set measures only two classes with at least 5 videos, and one video moves the top-3 score by about 0.05, so these numbers are noisy.
  • I did not check the reverse case, a small validation set where the model is mostly wrong.

Facts

context: post-hoc temperature scaling of a multi-class audio classifier, T fitted by NLL on the validation split
problem: validation set of 6 videos, all predicted correctly; fitted T fell to 0.31, 0.19, 0.05 and test ECE rose (0.162 -> 0.452, 0.046 -> 0.340)
solution: fit T only with >= 30 validation videos, >= 3 classes and no class above 70 %; otherwise keep T = 1 and store the reason with T
verified_on: 2026-10-28
applies_to: any NLL-fitted temperature or Platt-style scaling on a small or error-free calibration set
does_not_apply_to: calibration sets that contain misclassified samples in reasonable numbers

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Retour en haut