Post-Hoc Confidence Calibration with Temperature Scaling
Medium · Machine Learning · Machine Learning Engineer · Technical Screen
Problem Statement
Modern multi-class neural networks frequently rank candidate classes well while reporting overconfident probability estimates. Post-hoc temperature scaling rescales raw class scores (logits) by a single positive scalar T > 0 before converting them into probabilities, preserving the top-ranked class on every input while aligning predicted confidence with empirical accuracy on a validation split.
For a K-class score vector z = [z_0, ..., z_{K-1}] and scalar temperature T > 0, the rescaled class probability for class k in 0..K-1 is:
q_k(z; T) = exp(z_k / T) / sum_{j=0}^{K-1} exp(z_j / T)
Over a validation batch of N examples with score matrix logits of shape (N, K) and ground-truth class indices labels = [y_0, ..., y_{N-1}], the mean negative log-likelihood objective is:
L(T) = -(1 / N) * sum_{n=0}^{N-1} ln q_{y_n}(z_n; T)
Implement the five functions below using Python and NumPy:
softmax(logits: np.ndarray, T: float = 1.0) -> np.ndarray: Return the(N, K)matrix of row-wise rescaled probabilitiesq_k(z_n; T)without overflowing on large score magnitudes (such as1000.0).nll(logits: np.ndarray, labels: Sequence[int], T: float) -> float: Return the mean negative log-likelihoodL(T)across allNrows as a Pythonfloat.nll_grad(logits: np.ndarray, labels: Sequence[int], T: float) -> float: Derive and compute the exact analytical derivativedL / dTat temperatureT.fit_temperature(logits: np.ndarray, labels: Sequence[int], t_min: float = 0.01, t_max: float = 100.0, max_iter: int = 200, tol: float = 1e-7) -> float: MinimiseL(T)over[t_min, t_max]via gradient-based optimisation and return the fitted scalarTin[t_min, t_max].calibrate(logits: np.ndarray, T: float) -> np.ndarray: Map new 2D score rowslogitsto calibrated probability vectors using a fitted temperatureT.
Examples
Example 1
Input:
logits = np.array([[3.0, 0.0]])
labels = [0]
T = 1.5
Output:
softmax(logits, T) -> [[0.88079708, 0.11920292]]
nll(logits, labels, T) -> 0.12692801
nll_grad(logits, labels, T) -> 0.15893723
Explanation: Dividing [3.0, 0.0] by T = 1.5 gives [2.0, 0.0], whose softmax is [e^2 / (e^2 + 1), 1 / (e^2 + 1)] = [0.880797, 0.119203]. The single-row loss is -ln(0.880797) = 0.126928, and the derivative (z_0 - E_q[z]) / T^2 = (3.0 - 2.642391) / 2.25 = 0.158937 is positive because the true class 0 has the larger score.
Example 2
Input:
val_logits = np.array([[3.0, 0.0]] * 5)
val_labels = [0, 0, 0, 0, 1]
Output:
T_opt = fit_temperature(val_logits, val_labels) -> 2.164042
calibrate(np.array([[3.0, 0.0]]), T_opt) -> [[0.8, 0.2]]
Explanation: At T = 1.0, the raw classifier assigns 95.26% probability to class 0, yet class 0 is correct on only 4 of the 5 validation examples (80%). Fitting T raises temperature to 3.0 / ln(4) = 2.164043, reducing mean NLL from 0.648587 to 0.500402 and calibrating [[3.0, 0.0]] to [[0.80, 0.20]] without altering the predicted class 0.
Constraints
logitsmust convert to a non-empty 2D numeric array of shape(N, K)withN >= 1andK >= 1; otherwise raiseValueError.Tmust be strictly positive (T > 0, rejecting0, negative numbers, andNaN); otherwise raiseValueError.labelsmust have lengthN, and every element must be an integer (notboolorfloat) satisfying0 <= y_n < K; otherwise raiseValueError.fit_temperaturerequires finite bounds satisfying0 < t_min < t_max(otherwise raiseValueError) and must return afloatwithin[t_min, t_max].- Use only the Python standard library and NumPy.
Step-by-step walkthrough
Understand the goal: fixing confidence without changing predictions
Suppose a trained classifier inspects an input
xand outputs raw real-valued class scores called logits,z(x) = [z_0, z_1, ..., z_{K-1}]. To turn those scores into probabilities that are positive and add up to1, we pass them through the softmax function. However, modern neural networks are often miscalibrated — when they say "95% confident", they might only be right 75% of the time.Temperature scaling fixes this over- or under-confidence after training using a single positive number
T > 0, learned on a held-out validation set:p_i(x; T) = exp(z_i / T) / sum_j exp(z_j / T)Think of
Tas a contrast knob on the logits before softmax:T > 1shrinks the gaps between logits, softening the distribution toward uniform1 / K(less confident).T < 1stretches the gaps between logits, pushing the top probability closer to1(more confident).T = 1leaves the model's original probabilities untouched.
Because dividing every score in a row by the same positive number
Tpreserves their order (z_a > z_bimpliesz_a / T > z_b / T), the winning classargmax_i p_i(x; T)and the model's top-1 accuracy never change. Only the confidence numbers change:Example row: logits z = [3.0, 0.0] T = 1.0 (uncalibrated): z / T = [3.0, 0.0] -> p = [0.953, 0.047] (winner: class 0) T = 1.5 (softer): z / T = [2.0, 0.0] -> p = [0.881, 0.119] (winner: class 0)In our implementation,
logitsis a 2D array of shape(N, K)(Nexamples,Kclasses),labelsholdsNinteger class indices in[0, K), andfit_temperaturereturns one floatT.Prevent overflow with the log-sum-exp trick
Before computing any loss, we need a numerically safe way to evaluate softmax and its logarithm. If a logit is
1000andT = 1,exp(1000)overflows 64-bit floating point (inf), soinf / infproducesNaN. Similarly, if a tiny probability underflows to0.0, takinglog(0.0)gives-inf.We avoid both failures by subtracting each row's maximum value
m = max_j (z_j / T)from every entry in that row before callingexp(). Subtractingmmultiplies both the numerator and the denominator of softmax byexp(-m), which cancels out:s_i = z_i / T m = max_j s_j log p_i = log( exp(s_i - m) / sum_j exp(s_j - m) ) = (s_i - m) - log( sum_j exp(s_j - m) )Now every shifted value
s_j - mis<= 0, and at least one entry in each row equals0, whose exponential isexp(0) = 1. Neither overflow nor division by zero can happen.def _scaled(logits: np.ndarray, T: float) -> np.ndarray: # Using `not (T > 0)` rejects zero, negative numbers, and NaN in one check. if not (T > 0): raise ValueError("temperature must be positive") # raw_logits: 2D float matrix of shape (N, K), one row of K class scores per example. raw_logits = np.asarray(logits, dtype=float) if raw_logits.ndim != 2 or raw_logits.shape[0] == 0 or raw_logits.shape[1] == 0: raise ValueError("logits must be a non-empty 2D array of shape (N, K)") return raw_logits / T def _log_softmax(logits: np.ndarray, T: float) -> np.ndarray: scaled_logits = _scaled(logits, T) # Subtract each row's maximum before exp() so the largest exponent is exp(0) = 1 (never overflows). row_max = scaled_logits.max(axis=1, keepdims=True) shifted_logits = scaled_logits - row_max log_sum_exp = np.log(np.exp(shifted_logits).sum(axis=1, keepdims=True)) return shifted_logits - log_sum_exp def softmax(logits: np.ndarray, T: float = 1.0) -> np.ndarray: # Exponentiating log-softmax avoids both overflow on large logits and 0/0 = NaN. return np.exp(_log_softmax(logits, T))Formulate the validation negative log-likelihood (NLL)
How do we measure whether
Tproduces honest probabilities? Accuracy is useless here becauseTnever changes which class wins. Instead, we minimise the negative log-likelihood (NLL) (also called cross-entropy loss) on a held-out validation set. NLL is a proper scoring rule, meaning its expected value is strictly minimised when the predicted probabilities match the true underlying frequencies.For one validation example with logits
zand true class indexy, the loss is-log p_y(x; T). Expanding the softmax fraction gives:l(T) = -log( exp(z_y / T) / sum_j exp(z_j / T) ) = -z_y / T + log( sum_j exp(z_j / T) ) L(T) = (1 / N) * sum_{n=0}^{N-1} l_n(T)In code,
_log_softmax(logits, T)already gives us the(N, K)matrix oflog p_k(x_n; T), so we just pick out columny[n]from each rownand negate the average. Notice that we validatelabelsexplicitly first: in NumPy, an invalid label of-1would silently index the last class instead of raising an error, and a float like1.9cast withdtype=intwould silently truncate to1.def _check_labels(logits: np.ndarray, labels: Sequence[int]) -> np.ndarray: raw_logits = np.asarray(logits, dtype=float) if raw_logits.ndim != 2 or raw_logits.shape[0] == 0 or raw_logits.shape[1] == 0: raise ValueError("logits must be a non-empty 2D array of shape (N, K)") num_rows, num_classes = raw_logits.shape if len(labels) != num_rows: raise ValueError("need exactly one label per row of logits") # Validate each label explicitly so booleans, floats (e.g. 1.9), and negative indices (-1) fail loudly. checked_labels = np.empty(num_rows, dtype=int) for idx, label in enumerate(labels): if isinstance(label, bool) or not isinstance(label, (int, np.integer)): raise ValueError("labels must be integers") label_int = int(label) if label_int < 0 or label_int >= num_classes: raise ValueError("labels must be in [0, K)") checked_labels[idx] = label_int return checked_labels def nll(logits: np.ndarray, labels: Sequence[int], T: float) -> float: # y: 1D integer array of shape (N,) holding the true class index in [0, K) for each row. y = _check_labels(logits, labels) # log_probs: 2D array of shape (N, K) where entry (n, k) is log p_k(x_n; T). log_probs = _log_softmax(logits, T) row_indices = np.arange(len(y)) true_log_probs = log_probs[row_indices, y] return float(-np.mean(true_log_probs))Derive the gradient with respect to T
To minimise
L(T)with gradient descent, we differentiatel(T) = -z_y / T + log(sum_j exp(z_j / T))with respect toTone term at a time, usingd/dT (1 / T) = -1 / T^2and the chain rule:Term 1: d/dT [ -z_y / T ] = (-z_y) * (-1 / T^2) = z_y / T^2 Term 2: d/dT [ log( sum_j exp(z_j / T) ) ] = [ 1 / sum_k exp(z_k / T) ] * sum_j [ exp(z_j / T) * (-z_j / T^2) ] = sum_j [ (exp(z_j / T) / sum_k exp(z_k / T)) * (-z_j / T^2) ] = -( sum_j p_j * z_j ) / T^2Adding the two pieces together and averaging over all
Nvalidation rows gives a clean, intuitive formula:dl/dT = ( z_y - sum_j p_j * z_j ) / T^2 = ( z_y - E_p[z] ) / T^2 dL/dT = (1 / N) * sum_{n=0}^{N-1} ( z_{n, y_n} - sum_j p_{n, j} * z_{n, j} ) / T^2Here
E_p[z] = sum_j p_j * z_jis the probability-weighted average logit that the model expects under its current temperatureT:- When the model gets a row right (
z_yis the largest logit),z_y > E_p[z], so that row's gradient is positive — it pullsTdown (sharper confidence). - When the model is confidently wrong (
z_yis smaller thanE_p[z]), that row's gradient is negative — it pushesTup (softer confidence).
Quick numeric check on Example 1 (
z = [3.0, 0.0],y = 0,T = 1.5):z / T = [2.0, 0.0],p = [0.8808, 0.1192],E_p[z] = 0.8808 * 3.0 + 0.1192 * 0.0 = 2.6424, sodl/dT = (3.0 - 2.6424) / 1.5^2 = 0.1589.def nll_grad(logits: np.ndarray, labels: Sequence[int], T: float) -> float: y = _check_labels(logits, labels) z = np.asarray(logits, dtype=float) # probs: 2D array of shape (N, K) holding calibrated class probabilities softmax(z / T). probs = softmax(z, T) row_indices = np.arange(len(y)) # For each row n, dl_n/dT = (z_{n, y_n} - sum_j p_{n, j} * z_{n, j}) / T^2. true_class_logits = z[row_indices, y] expected_logits = np.sum(probs * z, axis=1) return float(np.mean(true_class_logits - expected_logits) / (T * T))- When the model gets a row right (
Why the objective has one clean bowl and two boundary cases
Does
L(T)have tricky local minima where gradient descent could get trapped? Let's reparameterise with inverse temperatureb = 1 / T. Thenl(b) = -b * z_y + log(sum_j exp(b * z_j)), and differentiating twice with respect tobgives:dl/db = E_p[z] - z_y d^2l/db^2 = E_p[z^2] - (E_p[z])^2 = Var_p(z) >= 0Because a variance is never negative,
Lis convex in1 / T. SinceT = 1 / bis strictly decreasing forT > 0,L(T)is unimodal (single-bowl shaped): settingdL/dT = 0matches the average true-class logit to the average expected logit across the validation set:(1 / N) * sum_n z_{n, y_n} = (1 / N) * sum_n E_{p_n}[z_n]Worked closed-form example (Example 2): suppose 5 validation rows all have logits
[3.0, 0.0]and true labels[0, 0, 0, 0, 1](80% actual accuracy, whereas rawT = 1predicts95.3%confidence for class 0). At optimalT*,p_0 = 1 / (1 + exp(-3 / T*))equals0.80, so3 / T* = ln(4)andT* = 3 / 1.3863 = 2.1640.Why does
fit_temperaturetake bounds[t_min, t_max]? Because two extreme validation sets have no finite optimum:- 100% validation accuracy (every
z_{n, y_n}is strictly largest in its row):dL/dT > 0for allT > 0, so NLL keeps shrinking toward0asT -> 0. We stop cleanly att_min. - True class on average below the unweighted mean logit of its row: NLL keeps shrinking toward
log(K)asT -> infinity. We stop cleanly att_max.
- 100% validation accuracy (every
Optimise log(T) with backtracking gradient descent
Running plain gradient descent directly on
Twith a fixed learning rate has two pitfalls: a big negative gradient step can jump toT <= 0(which flips class rankings upside down or crashes), and the curvature changes wildly between smallTand largeT.We solve both cleanly:
- Optimise
log_t = ln(T)instead ofT: every real numberlog_tmaps to a strictly positiveT = exp(log_t) > 0, and keepingTinside[t_min, t_max]is just clippinglog_tto[ln(t_min), ln(t_max)]. By the chain rule:
dL / d(log_t) = (dL / dT) * (dT / d(log_t)) = T * (dL / dT)- Backtracking line search (Armijo rule): we propose a step
log_t - step_size * grad_log_t(clipped to the bounds). Linear Taylor approximation predicts the loss will change bygrad_log_t * (candidate_log_t - log_t) <= 0. If the new loss drops by at least half that predicted amount, we accept the step and doublestep_sizefor the next round (so flat regions are crossed quickly); otherwise we halvestep_sizeand retry. Finally, we clampexp(log_t)to[t_min, t_max]so floating-point rounding inexp(log(t_max))never overshootst_maxby1e-15.
def fit_temperature(logits: np.ndarray, labels: Sequence[int], t_min: float = 0.01, t_max: float = 100.0, max_iter: int = 200, tol: float = 1e-7) -> float: if not (0 < t_min < t_max and math.isfinite(t_max)): raise ValueError("need 0 < t_min < t_max with finite bounds") z = np.asarray(logits, dtype=float) y = _check_labels(z, labels) # Optimise log_t = log(T) so every unconstrained step corresponds to a positive T = exp(log_t). log_t_min = math.log(t_min) log_t_max = math.log(t_max) log_t = min(max(0.0, log_t_min), log_t_max) # start at T = 1.0 when inside [t_min, t_max] current_T = min(max(math.exp(log_t), t_min), t_max) current_loss = nll(z, y, current_T) step_size = 1.0 for _ in range(max_iter): current_T = min(max(math.exp(log_t), t_min), t_max) # Chain rule: dL/d(log_t) = dL/dT * dT/d(log_t) = T * dL/dT. grad_log_t = current_T * nll_grad(z, y, current_T) if abs(grad_log_t) < tol: break # Backtracking line search: shrink step_size until the NLL decreases enough (Armijo condition). while True: unclipped_log_t = log_t - step_size * grad_log_t candidate_log_t = min(max(unclipped_log_t, log_t_min), log_t_max) candidate_T = min(max(math.exp(candidate_log_t), t_min), t_max) candidate_loss = nll(z, y, candidate_T) predicted_change = grad_log_t * (candidate_log_t - log_t) if candidate_loss <= current_loss + 0.5 * predicted_change: break step_size /= 2.0 # If candidate_log_t did not move, we are pinned against t_min or t_max with gradient pointing outward. if candidate_log_t == log_t: break log_t = candidate_log_t current_loss = candidate_loss # Double step_size so the optimiser crosses flat high-temperature regions in a few steps. step_size *= 2.0 # Clamp once more so float rounding in exp(log(t_max)) never exceeds t_max by 1 ULP. return min(max(math.exp(log_t), t_min), t_max)- Optimise
Trace gradient descent and calibrate new predictions
Let's trace
fit_temperaturestarting atT = 1.0(log_t = 0.0) on Example 2 ([[3.0, 0.0]] * 5with labels[0, 0, 0, 0, 1]):iter T NLL dL/d(log_t) what happens 0 1.0000 0.6486 -0.4577 negative gradient -> increase T 1 1.5805 0.5193 -0.1323 confidence softens from 95.3% toward 87.0% 2 2.0591 0.5008 -0.0161 approaching the bowl minimum 3 2.1266 0.5004 -0.0055 halved step prevents overshooting 4 2.1500 0.5004 -0.0020 closing in on 3 / ln(4) ... 14 2.1640 0.5004 -0.0000 stops: |grad_log_t| < 1e-7 (matches 3 / ln 4 = 2.1640)Once
Tis learned on the held-out validation set (never on the training set, where the model has memorised labels and already looks artificially accurate!), calibrating new test or production logits is simplysoftmax(logits, T):def calibrate(logits: np.ndarray, T: float) -> np.ndarray: return softmax(logits, T)On a new input with logits
[3.0, 0.0],calibrateoutputs[0.800, 0.200]instead of[0.953, 0.047]— honest probabilities with the exact same predicted class0.Complete solution
from typing import Sequence import math import numpy as np def _scaled(logits: np.ndarray, T: float) -> np.ndarray: # Using `not (T > 0)` rejects zero, negative numbers, and NaN in one check. if not (T > 0): raise ValueError("temperature must be positive") # raw_logits: 2D float matrix of shape (N, K), one row of K class scores per example. raw_logits = np.asarray(logits, dtype=float) if raw_logits.ndim != 2 or raw_logits.shape[0] == 0 or raw_logits.shape[1] == 0: raise ValueError("logits must be a non-empty 2D array of shape (N, K)") return raw_logits / T def _log_softmax(logits: np.ndarray, T: float) -> np.ndarray: scaled_logits = _scaled(logits, T) # Subtract each row's maximum before exp() so the largest exponent is exp(0) = 1 (never overflows). row_max = scaled_logits.max(axis=1, keepdims=True) shifted_logits = scaled_logits - row_max log_sum_exp = np.log(np.exp(shifted_logits).sum(axis=1, keepdims=True)) return shifted_logits - log_sum_exp def softmax(logits: np.ndarray, T: float = 1.0) -> np.ndarray: # Exponentiating log-softmax avoids both overflow on large logits and 0/0 = NaN. return np.exp(_log_softmax(logits, T)) def _check_labels(logits: np.ndarray, labels: Sequence[int]) -> np.ndarray: raw_logits = np.asarray(logits, dtype=float) if raw_logits.ndim != 2 or raw_logits.shape[0] == 0 or raw_logits.shape[1] == 0: raise ValueError("logits must be a non-empty 2D array of shape (N, K)") num_rows, num_classes = raw_logits.shape if len(labels) != num_rows: raise ValueError("need exactly one label per row of logits") # Validate each label explicitly so booleans, floats (e.g. 1.9), and negative indices (-1) fail loudly. checked_labels = np.empty(num_rows, dtype=int) for idx, label in enumerate(labels): if isinstance(label, bool) or not isinstance(label, (int, np.integer)): raise ValueError("labels must be integers") label_int = int(label) if label_int < 0 or label_int >= num_classes: raise ValueError("labels must be in [0, K)") checked_labels[idx] = label_int return checked_labels def nll(logits: np.ndarray, labels: Sequence[int], T: float) -> float: # y: 1D integer array of shape (N,) holding the true class index in [0, K) for each row. y = _check_labels(logits, labels) # log_probs: 2D array of shape (N, K) where entry (n, k) is log p_k(x_n; T). log_probs = _log_softmax(logits, T) row_indices = np.arange(len(y)) true_log_probs = log_probs[row_indices, y] return float(-np.mean(true_log_probs)) def nll_grad(logits: np.ndarray, labels: Sequence[int], T: float) -> float: y = _check_labels(logits, labels) z = np.asarray(logits, dtype=float) # probs: 2D array of shape (N, K) holding calibrated class probabilities softmax(z / T). probs = softmax(z, T) row_indices = np.arange(len(y)) # For each row n, dl_n/dT = (z_{n, y_n} - sum_j p_{n, j} * z_{n, j}) / T^2. true_class_logits = z[row_indices, y] expected_logits = np.sum(probs * z, axis=1) return float(np.mean(true_class_logits - expected_logits) / (T * T)) def fit_temperature(logits: np.ndarray, labels: Sequence[int], t_min: float = 0.01, t_max: float = 100.0, max_iter: int = 200, tol: float = 1e-7) -> float: if not (0 < t_min < t_max and math.isfinite(t_max)): raise ValueError("need 0 < t_min < t_max with finite bounds") z = np.asarray(logits, dtype=float) y = _check_labels(z, labels) # Optimise log_t = log(T) so every unconstrained step corresponds to a positive T = exp(log_t). log_t_min = math.log(t_min) log_t_max = math.log(t_max) log_t = min(max(0.0, log_t_min), log_t_max) # start at T = 1.0 when inside [t_min, t_max] current_T = min(max(math.exp(log_t), t_min), t_max) current_loss = nll(z, y, current_T) step_size = 1.0 for _ in range(max_iter): current_T = min(max(math.exp(log_t), t_min), t_max) # Chain rule: dL/d(log_t) = dL/dT * dT/d(log_t) = T * dL/dT. grad_log_t = current_T * nll_grad(z, y, current_T) if abs(grad_log_t) < tol: break # Backtracking line search: shrink step_size until the NLL decreases enough (Armijo condition). while True: unclipped_log_t = log_t - step_size * grad_log_t candidate_log_t = min(max(unclipped_log_t, log_t_min), log_t_max) candidate_T = min(max(math.exp(candidate_log_t), t_min), t_max) candidate_loss = nll(z, y, candidate_T) predicted_change = grad_log_t * (candidate_log_t - log_t) if candidate_loss <= current_loss + 0.5 * predicted_change: break step_size /= 2.0 # If candidate_log_t did not move, we are pinned against t_min or t_max with gradient pointing outward. if candidate_log_t == log_t: break log_t = candidate_log_t current_loss = candidate_loss # Double step_size so the optimiser crosses flat high-temperature regions in a few steps. step_size *= 2.0 # Clamp once more so float rounding in exp(log(t_max)) never exceeds t_max by 1 ULP. return min(max(math.exp(log_t), t_min), t_max) def calibrate(logits: np.ndarray, T: float) -> np.ndarray: return softmax(logits, T)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a weather forecaster who knows which days look rainier than others, yet every time they announce "98% chance of rain", it actually rains only 75% of the time. Their ranking of days is good, so you do not want to retrain them from scratch — you just want a single dial that tones down their exaggerated confidence until "75% chance" really means rain 3 days out of 4. Probability calibration is that exact property (predicted probabilities match real-world hit rates), and temperature scaling is that single dial: before turning raw model scores (logits, the unconstrained real numbers produced by a classifier's final layer) into probabilities with softmax (the formula exp(z_i) / sum_j exp(z_j) that makes positive numbers sum to 1), we divide every logit by one positive number T.
Naive implementations fail in three ways: computing log(exp(z / T) / sum exp(z / T)) directly overflows to NaN on large logits like 1000, tuning T by accuracy accomplishes nothing because dividing by T > 0 never changes which class has the largest score, and running fixed-step gradient descent directly on T can step into negative temperatures (reversing class predictions) or crawl on flat regions. Instead, we minimise negative log-likelihood (NLL) — the average of -log(predicted probability of the true class) on a held-out validation set — using the log-sum-exp trick (subtracting each row's maximum before exp so the largest exponent is exp(0) = 1) and optimising log(T) with a backtracking line search (halving the step size until the loss genuinely drops).
Walk through Example 2's 5-row validation set where every row has 2-class logits [3.0, 0.0] and the true labels are [0, 0, 0, 0, 1] (so class 0 is right 4 out of 5 times = 80%):
- At
T = 1.0,softmax([3.0, 0.0]) = [0.953, 0.047]. On the fifth row where class 1 is true, the model gave class 1 only0.047probability, creating a steep NLL penalty (-log(0.047) = 3.05) and a negative gradient (dL/d(log T) = -0.458) telling us to raiseT. - Gradient descent on
log(T)raisesTfrom1.000->1.581->2.059->2.164, wheredL/dT = 0because the average true-class logit(3 + 3 + 3 + 3 + 0) / 5 = 2.4matches the model's expected logit0.80 * 3 + 0.20 * 0 = 2.4. - At
T = 2.164,calibrate([[3.0, 0.0]], T)outputs[0.800, 0.200]: class 0 is still the winner, and the 80% confidence now matches the 80% validation accuracy.
Complexity
- Time: One call to
softmax,nll, ornll_gradtakesO(N * K)time because we visit each of theNvalidation rows and itsKclass logits a constant number of times to find row maxima, exponentiate, and sum across classes.fit_temperatureruns at mostmax_iterouter iterations (and a handful of halving checks per iteration), doingO(N * K)work per loss or gradient evaluation — because the 1-D objective is smooth and unimodal (single-bowl shaped), it typically converges in under 15 iterations regardless ofN. - Space:
O(N * K)auxiliary memory to hold the(N, K)arrays of scaled logits and softmax probabilities during vectorised NumPy operations, with no extra memory accumulated across iterations.
Edge cases
- 100% accuracy on the validation set: When the true class strictly has the highest logit on every validation row,
z_y > E_p[z]everywhere, so NLL keeps shrinking toward0asT -> 0. The optimiser cleanly stops att_min(or once the gradient shrinks belowtol), which in practice signals that the validation split is too small or too easy. - Worse-than-uniform predictions: When the true class's logit is on average smaller than the unweighted mean of its row's logits, NLL decreases toward
log(K)asT -> infinity, and the optimiser stops cleanly att_max. - Large logits (such as
1000.0): Subtracting the row maximum inside_log_softmaxpreventsnp.expfrom overflowing toinfand prevents0 / 0 = NaN. - Rows with identical logits (e.g.,
[3.0, 3.0]): Every temperature gives[0.5, 0.5],z_y - E_p[z] = 0, and those rows contribute zero gradient without dividing by zero. - Floating-point rounding at the bounds: Because
math.exp(math.log(100.0))evaluates to100.00000000000004in IEEE-754 arithmetic, clamping the returned value withmin(max(math.exp(log_t), t_min), t_max)guaranteest_min <= T <= t_maxholds exactly. - Invalid inputs:
T <= 0,T = NaN, empty or non-2Dlogits, booleans or fractional floats as labels, negative labels like-1(which NumPy would otherwise wrap to the last class), andt_min >= t_maxall raiseValueError.
Common mistakes
- Fitting
Ton the training set instead of a held-out validation set. A neural network has already memorised or overfit its training labels, so its high confidence looks deserved on training data; fittingTthere yieldsTnear or below1, leaving production predictions severely overconfident. - Updating
Tdirectly with a fixed learning rate. Without thelog(T)reparameterisation, a single large negative gradient step can pushT <= 0(inverting every class ranking), and without line search a fixed step size either diverges on large logits or crawls whenTis large. - Dividing probabilities by
Tinstead of logits.softmax(z) / Tno longer sums to1, andsoftmax(softmax(z) / T)is a completely different transformation; if only probabilitiespare saved, the equivalent temperature-scaled formula isp_i^(1/T) / sum_j p_j^(1/T)(computed safely assoftmax(log(p), T)). - Selecting
Tusing top-1 accuracy or ROC AUC (binary). Monotone scaling of a single score preserves rankings and argmax, so accuracy never moves withT; always fitTwith a proper probability loss like NLL or Brier score (the mean squared error between predicted probability vectors and one-hot true labels). - Expecting one scalar
Tto fix class-specific bias. Temperature scaling adjusts overall sharpness uniformly across all inputs and classes; it cannot fix a model that systematically overpredicts class A while underpredicting class B.
Alternative approaches
- Newton's method on inverse temperature
b = 1 / T: Because NLL is strictly convex inbwith first derivativemean(E_p[z] - z_y)and second derivativemean(Var_p(z)), damped 1-D Newton updates (b <- b - grad / hess) converge quadratically in 5–8 steps without needing a step-size schedule. - Bisection (binary search) on the gradient sign: Since
dL/dTis monotonically non-decreasing in sign across the single optimum (negative belowT*, positive aboveT*), bisectinglog(T)on[log(t_min), log(t_max)]findsT*to1e-9precision in about 40 evaluations ofnll_gradwith zero line-search logic. - Off-the-shelf 1-D bounded minimisers: In production pipelines where SciPy or PyTorch is allowed,
scipy.optimize.minimize_scalar(..., bounds=(t_min, t_max), method="bounded")ortorch.optim.LBFGSonlog_tfinds the exact same minimum.
Follow-up questions
- Which quantitative metrics and diagnostic plots would you use on a separate test split to confirm that calibration improved? Evaluate on a third, untouched test split (separate from both model training and fitting
T) by comparing NLL, Brier score, and Expected Calibration Error (ECE) before and after scaling. ECE groups predictions intoMconfidence bins (say 10 bins of width0.1) and computes the weighted average of|bin accuracy - average bin confidence|: for instance, 100 predictions averaging0.90confidence with0.75accuracy plus 50 predictions averaging0.60confidence with0.62accuracy giveECE = (100/150) * 0.15 + (50/150) * 0.02 = 0.107. Pair ECE with a reliability diagram, which plots observed accuracy against predicted confidence per bin so perfect calibration lies on they = xdiagonal. - How does single-parameter temperature scaling compare against Platt scaling, vector scaling, and isotonic regression? Platt scaling (for binary classification) fits a two-parameter logistic curve
sigmoid(a * m + b)on the logit gapm = z_1 - z_0, so temperature scaling is Platt scaling witha = 1/Tand biasb = 0. Vector scaling learns one multiplier and one bias per class (2Kparameters), which can correct class-level imbalance shifts, but it can change the predicted argmax class and overfit small validation sets. Isotonic regression fits a non-parametric step-wise non-decreasing curve from raw scores to empirical frequencies; it can fix non-sigmoidal distortions given thousands of validation points, but it creates probability ties and overfits badly when validation data is scarce. - How can live distribution shift break a previously fitted temperature, and how would you detect and remedy it in production? Because
Tonly rescales confidence to match the validation set's error profile, calibration often degrades under distribution shift (when live inputs or class base rates differ from validation) even before top-1 accuracy visibly drops. Monitor binned ECE and average predicted probability against delayed ground-truth labels on rolling windows, and refitTperiodically on recent labelled data. If a binary task suffers a prior shift (for example, click rate doubles during a holiday while user features per class stay similar), add an intercept offsetb(Platt scaling) so the average predicted probability can shift alongside sharpness.
Follow-up questions
- Which quantitative metrics and diagnostic plots would you use on a separate test split to confirm that calibration improved?
- How does single-parameter temperature scaling compare against Platt scaling, vector scaling, and isotonic regression?
- How can live distribution shift break a previously fitted temperature, and how would you detect and remedy it in production?
Similar questions
- End-to-End Modeling Strategy for Skewed Binary Labels
- Single-Split Piecewise Constant Step Fit
- Presenting Your Highest-Impact ML Project
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift