A classifier can pick the same winning label at two very different confidence levels. That matters when a downstream interface displays the probability or when a review workflow uses it as a score. Temperature scaling adjusts the probabilities without retraining the classifier. This example fits one positive temperature to frozen logits by minimizing mean negative log-likelihood on a small calibration set.

Prerequisites and fixture

Use Python 3.12 with no third-party packages. Save the following as temperature.py. Each row has an ordered logit vector and the zero-based index of its true class. The model always favors class zero in this fixture, but one of the three labels is actually class one. The fixture is intentionally small enough to inspect by hand.

from math import exp, fsum, isfinite, log

def nll(rows, t):
    if not rows or not isfinite(t) or t < 1e-6:
        raise ValueError("need examples and T >= 1e-6")
    losses = []
    for z, y in rows:
        if (len(z) < 2 or type(y) is not int or not 0 <= y < len(z)
                or not all(isfinite(x) and abs(x) <= 1e6 for x in z)):
            raise ValueError("invalid logits or label")
        peak = max(z)
        shifted = [(x - peak) / t for x in z]
        losses.append(log(fsum(exp(x) for x in shifted)) - shifted[y])
    return fsum(losses) / len(losses)

rows = [((10, 4), 0), ((10, 4), 1), ((10, 4), 0)]
grid = [0.5, 1, 2, 4, 8, 16]
best = min(grid, key=lambda t: nll(rows, t))
assert best == 8 and nll(rows, best) < nll(rows, 1)
assert nll([((10000, 9994), y) for _, y in rows], best) == nll(rows, best)
assert max(range(2), key=lambda i: rows[0][0][i] / best) == 0
try:
    nll(rows, 0)
except ValueError:
    pass
else:
    raise AssertionError("zero temperature accepted")
print(f"T={best}, NLL {nll(rows, 1):.4f} -> {nll(rows, best):.4f}")

Run and interpret the result

python3 temperature.py
T=8, NLL 2.0025 -> 0.6369

Dividing both logits by 8 narrows the gap from 6 to 0.75, which makes the incorrect prediction less confident. The two correct predictions also become less confident. Negative log-likelihood captures that tradeoff because it charges each example according to the probability assigned to its actual label. The numeric bounds in the helper are defensive limits for this example, not requirements of temperature scaling.

Subtracting the row maximum preserves the softmax ratios and leaves one exact zero before exponentiation. Its exponential is 1, so the sum is not zero even if distant alternatives underflow. The loss subtracts the shifted true-class logit rather than taking the logarithm of a rounded probability. A positive divisor preserves within-row logit order, so temperature scaling cannot repair a wrong winning label.

Apply it to a real evaluation

Capture logits and labels with the same immutable class vocabulary. Set aside calibration examples separately from training and final test data. Choose the temperature on calibration examples and compare the frozen choice against T=1 on the untouched test set. If the chosen value is at the edge of the search grid, expand or refine the grid on calibration data. Do not expand it repeatedly based on final test loss. If confidence remains uneven across classes or slices, inspect those slices separately. One scalar cannot fix every kind of miscalibration.

Guo et al., On Calibration of Modern Neural Networks · Java Samples AI tutorials