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:

  1. softmax(logits: np.ndarray, T: float = 1.0) -> np.ndarray: Return the (N, K) matrix of row-wise rescaled probabilities q_k(z_n; T) without overflowing on large score magnitudes (such as 1000.0).
  2. nll(logits: np.ndarray, labels: Sequence[int], T: float) -> float: Return the mean negative log-likelihood L(T) across all N rows as a Python float.
  3. nll_grad(logits: np.ndarray, labels: Sequence[int], T: float) -> float: Derive and compute the exact analytical derivative dL / dT at temperature T.
  4. 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: Minimise L(T) over [t_min, t_max] via gradient-based optimisation and return the fitted scalar T in [t_min, t_max].
  5. calibrate(logits: np.ndarray, T: float) -> np.ndarray: Map new 2D score rows logits to calibrated probability vectors using a fitted temperature T.

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

  • logits must convert to a non-empty 2D numeric array of shape (N, K) with N >= 1 and K >= 1; otherwise raise ValueError.
  • T must be strictly positive (T > 0, rejecting 0, negative numbers, and NaN); otherwise raise ValueError.
  • labels must have length N, and every element must be an integer (not bool or float) satisfying 0 <= y_n < K; otherwise raise ValueError.
  • fit_temperature requires finite bounds satisfying 0 < t_min < t_max (otherwise raise ValueError) and must return a float within [t_min, t_max].
  • Use only the Python standard library and NumPy.

Step-by-step walkthrough

  1. Understand the goal: fixing confidence without changing predictions

    Suppose a trained classifier inspects an input x and 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 to 1, 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 T as a contrast knob on the logits before softmax:

    • T > 1 shrinks the gaps between logits, softening the distribution toward uniform 1 / K (less confident).
    • T < 1 stretches the gaps between logits, pushing the top probability closer to 1 (more confident).
    • T = 1 leaves the model's original probabilities untouched.

    Because dividing every score in a row by the same positive number T preserves their order (z_a > z_b implies z_a / T > z_b / T), the winning class argmax_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, logits is a 2D array of shape (N, K) (N examples, K classes), labels holds N integer class indices in [0, K), and fit_temperature returns one float T.

  2. 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 1000 and T = 1, exp(1000) overflows 64-bit floating point (inf), so inf / inf produces NaN. Similarly, if a tiny probability underflows to 0.0, taking log(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 calling exp(). Subtracting m multiplies both the numerator and the denominator of softmax by exp(-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 - m is <= 0, and at least one entry in each row equals 0, whose exponential is exp(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))
    
  3. Formulate the validation negative log-likelihood (NLL)

    How do we measure whether T produces honest probabilities? Accuracy is useless here because T never 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 z and true class index y, 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 of log p_k(x_n; T), so we just pick out column y[n] from each row n and negate the average. Notice that we validate labels explicitly first: in NumPy, an invalid label of -1 would silently index the last class instead of raising an error, and a float like 1.9 cast with dtype=int would silently truncate to 1.

    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))
    
  4. Derive the gradient with respect to T

    To minimise L(T) with gradient descent, we differentiate l(T) = -z_y / T + log(sum_j exp(z_j / T)) with respect to T one term at a time, using d/dT (1 / T) = -1 / T^2 and 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^2
    

    Adding the two pieces together and averaging over all N validation 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^2
    

    Here E_p[z] = sum_j p_j * z_j is the probability-weighted average logit that the model expects under its current temperature T:

    • When the model gets a row right (z_y is the largest logit), z_y > E_p[z], so that row's gradient is positive — it pulls T down (sharper confidence).
    • When the model is confidently wrong (z_y is smaller than E_p[z]), that row's gradient is negative — it pushes T up (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, so dl/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))
    
  5. 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 temperature b = 1 / T. Then l(b) = -b * z_y + log(sum_j exp(b * z_j)), and differentiating twice with respect to b gives:

    dl/db     = E_p[z] - z_y
    d^2l/db^2 = E_p[z^2] - (E_p[z])^2 = Var_p(z) >= 0
    

    Because a variance is never negative, L is convex in 1 / T. Since T = 1 / b is strictly decreasing for T > 0, L(T) is unimodal (single-bowl shaped): setting dL/dT = 0 matches 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 raw T = 1 predicts 95.3% confidence for class 0). At optimal T*, p_0 = 1 / (1 + exp(-3 / T*)) equals 0.80, so 3 / T* = ln(4) and T* = 3 / 1.3863 = 2.1640.

    Why does fit_temperature take 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 > 0 for all T > 0, so NLL keeps shrinking toward 0 as T -> 0. We stop cleanly at t_min.
    • True class on average below the unweighted mean logit of its row: NLL keeps shrinking toward log(K) as T -> infinity. We stop cleanly at t_max.
  6. Optimise log(T) with backtracking gradient descent

    Running plain gradient descent directly on T with a fixed learning rate has two pitfalls: a big negative gradient step can jump to T <= 0 (which flips class rankings upside down or crashes), and the curvature changes wildly between small T and large T.

    We solve both cleanly:

    1. Optimise log_t = ln(T) instead of T: every real number log_t maps to a strictly positive T = exp(log_t) > 0, and keeping T inside [t_min, t_max] is just clipping log_t to [ln(t_min), ln(t_max)]. By the chain rule:
    dL / d(log_t) = (dL / dT) * (dT / d(log_t)) = T * (dL / dT)
    
    1. 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 by grad_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 double step_size for the next round (so flat regions are crossed quickly); otherwise we halve step_size and retry. Finally, we clamp exp(log_t) to [t_min, t_max] so floating-point rounding in exp(log(t_max)) never overshoots t_max by 1e-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)
    
  7. Trace gradient descent and calibrate new predictions

    Let's trace fit_temperature starting at T = 1.0 (log_t = 0.0) on Example 2 ([[3.0, 0.0]] * 5 with 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 T is 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 simply softmax(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], calibrate outputs [0.800, 0.200] instead of [0.953, 0.047] — honest probabilities with the exact same predicted class 0.

  8. 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 only 0.047 probability, creating a steep NLL penalty (-log(0.047) = 3.05) and a negative gradient (dL/d(log T) = -0.458) telling us to raise T.
  • Gradient descent on log(T) raises T from 1.000 -> 1.581 -> 2.059 -> 2.164, where dL/dT = 0 because the average true-class logit (3 + 3 + 3 + 3 + 0) / 5 = 2.4 matches the model's expected logit 0.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, or nll_grad takes O(N * K) time because we visit each of the N validation rows and its K class logits a constant number of times to find row maxima, exponentiate, and sum across classes. fit_temperature runs at most max_iter outer iterations (and a handful of halving checks per iteration), doing O(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 of N.
  • 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 toward 0 as T -> 0. The optimiser cleanly stops at t_min (or once the gradient shrinks below tol), 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) as T -> infinity, and the optimiser stops cleanly at t_max.
  • Large logits (such as 1000.0): Subtracting the row maximum inside _log_softmax prevents np.exp from overflowing to inf and prevents 0 / 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 to 100.00000000000004 in IEEE-754 arithmetic, clamping the returned value with min(max(math.exp(log_t), t_min), t_max) guarantees t_min <= T <= t_max holds exactly.
  • Invalid inputs: T <= 0, T = NaN, empty or non-2D logits, booleans or fractional floats as labels, negative labels like -1 (which NumPy would otherwise wrap to the last class), and t_min >= t_max all raise ValueError.

Common mistakes

  • Fitting T on 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; fitting T there yields T near or below 1, leaving production predictions severely overconfident.
  • Updating T directly with a fixed learning rate. Without the log(T) reparameterisation, a single large negative gradient step can push T <= 0 (inverting every class ranking), and without line search a fixed step size either diverges on large logits or crawls when T is large.
  • Dividing probabilities by T instead of logits. softmax(z) / T no longer sums to 1, and softmax(softmax(z) / T) is a completely different transformation; if only probabilities p are saved, the equivalent temperature-scaled formula is p_i^(1/T) / sum_j p_j^(1/T) (computed safely as softmax(log(p), T)).
  • Selecting T using top-1 accuracy or ROC AUC (binary). Monotone scaling of a single score preserves rankings and argmax, so accuracy never moves with T; always fit T with 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 T to 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 in b with first derivative mean(E_p[z] - z_y) and second derivative mean(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/dT is monotonically non-decreasing in sign across the single optimum (negative below T*, positive above T*), bisecting log(T) on [log(t_min), log(t_max)] finds T* to 1e-9 precision in about 40 evaluations of nll_grad with 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") or torch.optim.LBFGS on log_t finds 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 into M confidence bins (say 10 bins of width 0.1) and computes the weighted average of |bin accuracy - average bin confidence|: for instance, 100 predictions averaging 0.90 confidence with 0.75 accuracy plus 50 predictions averaging 0.60 confidence with 0.62 accuracy give ECE = (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 the y = x diagonal.
  • 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 gap m = z_1 - z_0, so temperature scaling is Platt scaling with a = 1/T and bias b = 0. Vector scaling learns one multiplier and one bias per class (2K parameters), 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 T only 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 refit T periodically 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 offset b (Platt scaling) so the average predicted probability can shift alongside sharpness.

Follow-up questions

Similar questions

More NewsBreak interview questions

All 4 NewsBreak questions →