3.4  Measuring Classifiers

Our Fashion-MNIST softmax regression model classifies roughly \(83\%\) of validation images correctly. Does higher accuracy always mean a better classifier? Only when every class is equally important and every type of error carries the exact same cost. In real deployments, three everyday conditions break that symmetry:

  1. Class imbalance: When the positive class of interest is rare (say, \(1\%\) of patients have a disease or \(0.1\%\) of transactions are fraudulent), a useless classifier that always predicts the majority class scores \(99\%\) or \(99.9\%\) accuracy while catching zero positives.
  2. Asymmetric error costs: Missing a life-threatening illness (a false negative) is vastly costlier than ordering a follow-up test (a false positive).
  3. Probability-driven decisions: Downstream decision rules act directly on the numerical predicted probabilities \(\hat{\mathbf{y}}\), which are trustworthy only if the classifier is calibrated.

In this section, we develop the metrics and diagnostics for all three: precision and recall, cost-sensitive decision thresholds, reliability diagrams and expected calibration error (ECE), and post-hoc temperature scaling.

3.4.1 The Limits of Accuracy

3.4.1.1 Class Imbalance

Suppose we screen \(100{,}000\) people for a disease with \(1\%\) prevalence (\(1{,}000\) sick and \(99{,}000\) healthy). A trivial rule that ignores every test result and always predicts healthy achieves \(99\%\) accuracy while detecting not a single sick patient. Now compare it against a real screening test that detects \(90\%\) of sick patients while falsely flagging \(5\%\) of healthy ones:

sick (positive) healthy (negative)
predicted sick \(900\) (TP) \(4{,}950\) (FP)
predicted healthy \(100\) (FN) \(94{,}050\) (TN)

In this \(2 \times 2\) binary confusion matrix, the four cells are true positives (\(\textrm{TP} = 900\)), false positives (\(\textrm{FP} = 4{,}950\)), false negatives (\(\textrm{FN} = 100\)), and true negatives (\(\textrm{TN} = 94{,}050\)). Summing the diagonal gives \(94{,}950 / 100{,}000 = 95\%\) accuracy, so raw accuracy ranks the useless “always-healthy” rule (\(99\%\)) ahead of a lifesaving test (\(95\%\)).

To evaluate performance on the positive class specifically, we pair two ratios: recall (or sensitivity / true-positive rate), the fraction of true positives caught, and precision (or positive predictive value), the fraction of positive flags that are truly positive:

\[\textrm{recall} = \frac{\textrm{TP}}{\textrm{TP} + \textrm{FN}}, \qquad \textrm{precision} = \frac{\textrm{TP}}{\textrm{TP} + \textrm{FP}}. \tag{3.4.1}\]

Reading down the first column gives \(\textrm{recall} = 900 / 1{,}000 = 0.90\) (versus \(0\) for “always healthy”). Reading across the first row gives \(\textrm{precision} = 900 / 5{,}850 \approx 0.15\): only \(15\%\) of flagged people are actually sick, because \(5\%\) false alarms from the huge healthy majority (\(4{,}950\)) outnumber the \(900\) true positives (the Bayes’ theorem effect from Section 1.6.5.2). In two-stage clinical screening, \(90\%\) recall with \(15\%\) precision is ideal: the cheap first test catches almost every sick patient and sends only the \(5{,}850\) flagged patients to a definitive follow-up test.

Let us hold our test’s intrinsic recall (\(0.90\)) and false-alarm rate (\(0.05\)) fixed while sweeping the disease prevalence across \(\{0.1\%, 1\%, 10\%, 50\%\}\):

recall, false_alarms = 0.9, 0.05  # Properties of the test
for prevalence in [0.001, 0.01, 0.1, 0.5]:
    tp, fp = recall * prevalence, false_alarms * (1 - prevalence)
    accuracy = tp + (1 - false_alarms) * (1 - prevalence)
    print(f'{prevalence:5.1%} sick: accuracy {accuracy:.3f}, '
          f'recall {recall:.2f}, precision {tp / (tp + fp):.3f}')
 0.1% sick: accuracy 0.950, recall 0.90, precision 0.018
 1.0% sick: accuracy 0.950, recall 0.90, precision 0.154
10.0% sick: accuracy 0.945, recall 0.90, precision 0.667
50.0% sick: accuracy 0.925, recall 0.90, precision 0.947

Notice what changes and what stays fixed: recall and false-alarm rate are properties of the classifier alone, whereas precision depends heavily on the population prevalence.

3.4.1.2 Asymmetric Costs

Suppose missing a sick patient costs \(\kappa_{\textrm{FN}} = 100\) whereas a false alarm costs \(\kappa_{\textrm{FP}} = 1\) (and correct calls cost \(0\)). Weighted by these penalties, the “always-healthy” rule incurs an expected cost of \(100 \times 1{,}000 / 100{,}000 = 1.00\) per person, whereas our screening test costs \((100 \times 100 + 1 \times 4{,}950) / 100{,}000 \approx 0.15\) per person, nearly seven times lower.

More generally, if a classifier estimates probability \(p = P(\textrm{sick} \mid \mathbf{x})\) for an individual, predicting healthy has expected cost \(p\,\kappa_{\textrm{FN}}\) and predicting sick has expected cost \((1 - p)\,\kappa_{\textrm{FP}}\). Predicting sick minimizes expected cost whenever

\[p \, \kappa_\textrm{FN} > (1 - p)\, \kappa_\textrm{FP}, \quad \textrm{that is,} \quad p > \frac{\kappa_\textrm{FP}}{\kappa_\textrm{FP} + \kappa_\textrm{FN}}. \tag{3.4.2}\]

Equal costs (\(\kappa_{\textrm{FN}} = \kappa_{\textrm{FP}}\)) recover the familiar \(1/2\) threshold (argmax classification). With \(\kappa_{\textrm{FN}} = 100\) and \(\kappa_{\textrm{FP}} = 1\), however, the optimal threshold drops to \(1/101 \approx 0.01\): even a \(2\%\) predicted risk warrants flagging the patient. Lowering the threshold raises recall at the expense of precision (when costs are unspecified, practitioners often summarize the trade-off via the harmonic mean of precision and recall, the F1 score \(= 2\,\textrm{precision}\cdot\textrm{recall}/(\textrm{precision} + \textrm{recall})\), or sweep all thresholds via ROC and precision–recall curves; see Exercises 4 and 5).

3.4.2 Calibration

3.4.2.1 Reliability Diagrams

Cost-sensitive decision rules like Equation 3.4.2 act directly on the numerical value of \(p\), which means they rely on the classifier being calibrated: among all examples where the classifier predicts confidence \(\hat{p} \approx 0.80\), roughly \(80\%\) should actually be correct.

In a \(q\)-class problem, we check top-class calibration by recording each validation prediction’s confidence \(\hat{p}^{(i)} = \max_j \hat{y}^{(i)}_j\) and correctness indicator \(c^{(i)} = \mathbf{1}(\operatorname{argmax}_j \hat{y}^{(i)}_j = y^{(i)})\), partitioning the examples into confidence bins \([0, 0.1), [0.1, 0.2), \ldots, [0.9, 1.0]\), and comparing each bin’s mean confidence \(\bar{p}_b\) against its empirical accuracy \(a_b\). Plotting \(a_b\) against \(\bar{p}_b\) gives a reliability diagram (where a perfectly calibrated model lies along the diagonal \(a_b = \bar{p}_b\)), and their sample-weighted average gap defines the expected calibration error (ECE):

\[\textrm{ECE} = \sum_b \frac{n_b}{n} \left| a_b - \bar{p}_b \right|. \tag{3.4.3}\]

Let us train our concise SoftmaxRegression model on Fashion-MNIST, collect its validation logits O and labels y, and compute its per-bin reliability statistics, ECE, and reliability diagram:

data = d2l.FashionMNIST(batch_size=256)
model = d2l.SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.board.display = False
trainer.fit(model, data)
O, y = [], []
for X, Y in data.val_dataloader():
    O.append(d2l.numpy(model(X)))
    y.append(d2l.numpy(Y))
O, y = np.concatenate(O), np.concatenate(y)
print(f'validation accuracy {(O.argmax(axis=1) == y).mean():.3f}')
validation accuracy 0.823
validation accuracy 0.826
validation accuracy 0.831
validation accuracy 0.823

To compute each prediction’s confidence, we apply the numerically shifted softmax (Section 3.3) to the logits in NumPy and take the maximum probability per row.

def softmax(O):
    """Row-wise softmax of a NumPy array of logits."""
    E = np.exp(O - O.max(axis=1, keepdims=True))
    return E / E.sum(axis=1, keepdims=True)

conf = softmax(O).max(axis=1)  # Confidence of each prediction
correct = (O.argmax(axis=1) == y).astype(float)

Next, reliability(conf, correct, num_bins=10) groups the validation predictions into ten equal-width confidence bins via np.bincount, returning the per-bin sample counts n, mean confidences mean_conf, empirical accuracies acc, and sample-weighted ece:

def reliability(conf, correct, num_bins=10):
    """Count, mean confidence, and accuracy per confidence bin; the ECE."""
    bins = np.minimum((conf * num_bins).astype(int), num_bins - 1)
    n = np.bincount(bins, minlength=num_bins)
    mean_conf = np.bincount(bins, conf, num_bins) / np.maximum(n, 1)
    acc = np.bincount(bins, correct, num_bins) / np.maximum(n, 1)
    return n, mean_conf, acc, np.sum(n * np.abs(acc - mean_conf)) / len(conf)

n, mean_conf, acc, ece = reliability(conf, correct)
for b in np.flatnonzero(n):
    print(f'confidence {b / 10:.1f} to {(b + 1) / 10:.1f}: {n[b]:4d} '
          f'predictions, mean {mean_conf[b]:.3f}, accuracy {acc[b]:.3f}')
print(f'ECE: {ece:.3f}')
confidence 0.1 to 0.2:    2 predictions, mean 0.178, accuracy 0.000
confidence 0.2 to 0.3:   39 predictions, mean 0.266, accuracy 0.231
confidence 0.3 to 0.4:  268 predictions, mean 0.359, accuracy 0.343
confidence 0.4 to 0.5:  655 predictions, mean 0.457, accuracy 0.516
confidence 0.5 to 0.6:  956 predictions, mean 0.548, accuracy 0.548
confidence 0.6 to 0.7:  953 predictions, mean 0.650, accuracy 0.656
confidence 0.7 to 0.8: 1025 predictions, mean 0.752, accuracy 0.792
confidence 0.8 to 0.9: 1372 predictions, mean 0.854, accuracy 0.883
confidence 0.9 to 1.0: 4730 predictions, mean 0.972, accuracy 0.976
ECE: 0.015
confidence 0.1 to 0.2:    2 predictions, mean 0.186, accuracy 0.000
confidence 0.2 to 0.3:   52 predictions, mean 0.271, accuracy 0.269
confidence 0.3 to 0.4:  276 predictions, mean 0.361, accuracy 0.359
confidence 0.4 to 0.5:  637 predictions, mean 0.456, accuracy 0.521
confidence 0.5 to 0.6:  897 predictions, mean 0.551, accuracy 0.548
confidence 0.6 to 0.7:  948 predictions, mean 0.650, accuracy 0.679
confidence 0.7 to 0.8: 1008 predictions, mean 0.750, accuracy 0.779
confidence 0.8 to 0.9: 1401 predictions, mean 0.853, accuracy 0.882
confidence 0.9 to 1.0: 4779 predictions, mean 0.972, accuracy 0.975
ECE: 0.016
confidence 0.1 to 0.2:    2 predictions, mean 0.186, accuracy 0.000
confidence 0.2 to 0.3:   51 predictions, mean 0.266, accuracy 0.275
confidence 0.3 to 0.4:  274 predictions, mean 0.357, accuracy 0.376
confidence 0.4 to 0.5:  708 predictions, mean 0.456, accuracy 0.492
confidence 0.5 to 0.6:  886 predictions, mean 0.550, accuracy 0.567
confidence 0.6 to 0.7:  888 predictions, mean 0.651, accuracy 0.687
confidence 0.7 to 0.8:  982 predictions, mean 0.751, accuracy 0.794
confidence 0.8 to 0.9: 1392 predictions, mean 0.854, accuracy 0.894
confidence 0.9 to 1.0: 4817 predictions, mean 0.973, accuracy 0.978
ECE: 0.020
confidence 0.1 to 0.2:    1 predictions, mean 0.165, accuracy 0.000
confidence 0.2 to 0.3:   43 predictions, mean 0.264, accuracy 0.302
confidence 0.3 to 0.4:  271 predictions, mean 0.360, accuracy 0.439
confidence 0.4 to 0.5:  710 predictions, mean 0.456, accuracy 0.508
confidence 0.5 to 0.6:  953 predictions, mean 0.550, accuracy 0.553
confidence 0.6 to 0.7:  914 predictions, mean 0.651, accuracy 0.662
confidence 0.7 to 0.8:  958 predictions, mean 0.751, accuracy 0.771
confidence 0.8 to 0.9: 1387 predictions, mean 0.853, accuracy 0.877
confidence 0.9 to 1.0: 4763 predictions, mean 0.972, accuracy 0.976
ECE: 0.015

Filtering to well-populated bins with at least \(100\) predictions (used = n >= 100) so noisy small-sample ratios do not distort the curve, we plot acc[used] against mean_conf[used] alongside the ideal \(y = x\) diagonal:

used = n >= 100  # Fewer predictions give too noisy an accuracy
d2l.plot([mean_conf[used], [0, 1]], [acc[used], [0, 1]], 'mean confidence',
         'accuracy', legend=['softmax regression', 'calibrated'],
         fmts=('o-', 'k:'), figsize=(3.5, 3.5))

Across all well-populated bins (\(n_b \geq 100\)), empirical accuracy tracks mean confidence within eight percentage points, sitting slightly above the diagonal (average confidence \(\sim 81\%\) vs. accuracy \(\sim 83\%\), for an ECE below \(0.03\)). Unlike deep overparameterized networks, which frequently become severely overconfident, shallow softmax regression on Fashion-MNIST is already well calibrated (slightly underconfident).

3.4.2.2 Temperature Scaling

When a reliability diagram reveals miscalibration, temperature scaling (Guo et al. 2017) offers a one-parameter post-hoc fix: hold the trained weights fixed, divide the logits by a scalar temperature \(T > 0\) (Section 3.1), and fit \(T\) to minimize cross-entropy on a held-out validation split. Because dividing by \(T > 0\) preserves logit ordering, temperature scaling never alters a single class prediction or changes accuracy; it only rescales confidence (\(T > 1\) damps overconfidence; \(T < 1\) sharpens underconfidence). Let us fit \(T\) on the first half of our Fashion-MNIST validation set and check the ECE on the second half:

def nll(O, y, T):
    """Mean cross-entropy of softmax(O / T), computed from the logits."""
    Z = O / T
    m = Z.max(axis=1)
    lse = m + np.log(np.exp(Z - m[:, None]).sum(axis=1))
    return np.mean(lse - Z[np.arange(len(y)), y])

half = len(y) // 2
Ts = np.linspace(0.5, 2, 151)
T = Ts[np.argmin([nll(O[:half], y[:half], t) for t in Ts])]
ece = lambda Z: reliability(softmax(Z).max(axis=1), correct[half:])[3]
print(f'T = {T:.2f}; ECE on the second half: {ece(O[half:]):.3f} before, '
      f'{ece(O[half:] / T):.3f} after scaling')
T = 0.93; ECE on the second half: 0.015 before, 0.012 after scaling
T = 0.93; ECE on the second half: 0.015 before, 0.013 after scaling
T = 0.90; ECE on the second half: 0.016 before, 0.009 after scaling
T = 0.93; ECE on the second half: 0.014 before, 0.012 after scaling

Consistent with our slightly underconfident reliability curve, the fitted temperature sits just below \(1\) (\(T \approx 0.9\)), leaving the already tiny ECE essentially unchanged.

3.4.3 Summary

Raw accuracy is an adequate figure of merit only when classes are balanced and all errors cost the same. When positive examples are rare, true negatives dominate overall accuracy, so we separate positive detection into recall (\(\textrm{TP}/(\textrm{TP}+\textrm{FN})\), an intrinsic property of the classifier) and precision (\(\textrm{TP}/(\textrm{TP}+\textrm{FP})\), which scales with population prevalence via Bayes’ theorem). When false negatives and false positives carry unequal costs \(\kappa_{\textrm{FN}}\) and \(\kappa_{\textrm{FP}}\), expected cost is minimized by predicting positive whenever \(p > \kappa_{\textrm{FP}}/(\kappa_{\textrm{FP}} + \kappa_{\textrm{FN}})\), a rule that relies on the predicted probabilities being calibrated. Reliability diagrams and expected calibration error audit that agreement, and fitting a single post-hoc temperature \(T > 0\) on held-out data rescales confidence without changing accuracy.

3.4.4 Exercises

  1. Optimal decisions and rejection. In a multiclass problem, let \(\kappa_{ij}\) be the cost of predicting class \(i\) when the true class is \(j\), and let \(p(j \mid x)\) be the probability of class \(j\) given the input \(x\).

    1. Write the expected cost of predicting \(i\) in terms of the costs and \(p(j \mid x)\), and state the rule that selects the optimal \(i\). Check that it reduces to Equation 3.4.2 for two classes.
    2. Let a correct guess cost \(0\) and a wrong guess cost \(\lambda_s\), and allow the classifier to abstain instead of guessing, at a fixed cost \(\lambda_r < \lambda_s\). Derive the threshold on the top-class probability above which guessing beats abstaining.
    3. In medical diagnosis, deferring to a specialist is cheap relative to a misdiagnosis, say \(\lambda_r/\lambda_s = 0.05\). Compute the threshold and state what the classifier should do with a prediction at \(0.9\) confidence. Then describe a case in which reporting the full distribution \(p(y \mid x)\) serves the physician better than either guessing or abstaining.

    Adapted from Kevin Murphy, Probabilistic Machine Learning: An Introduction, Exercise 5.1.

  2. Class-weighted loss. In the screening example of Section 3.4.1, missing a sick patient costs much more than a false alarm. Give each class \(j\) a weight \(w_j > 0\) and train \(f\) on the class-weighted average loss

    \[\frac{1}{n} \sum_{i=1}^n w_{y^{(i)}}\, l\big(f(\mathbf{x}^{(i)}), y^{(i)}\big), \tag{3.4.4}\]

    where \(l\) is the cross-entropy loss and \(y^{(i)}\) is the class of example \(i\), so that every example of class \(j\) counts \(w_j\) times.

    1. Let the training examples be drawn with class prior \(p(y)\) and class-conditional densities \(p(\mathbf{x} \mid y)\). Show that the expected class-weighted loss is proportional to the expected unweighted loss under the distribution with the same class-conditionals and class prior proportional to \(w_y\, p(y)\). Name the change to the training data, rather than to the loss, that has the same effect.
    2. Fix an input \(\mathbf{x}\) with class probabilities \(p(j \mid \mathbf{x})\), and suppose the model can output any distribution \(\hat{\mathbf{y}}\). Show that the expected weighted loss \[-\sum_j w_j\, p(j \mid \mathbf{x}) \log \hat{y}_j \tag{3.4.5}\] is minimized by \(\hat{y}_j \propto w_j\, p(j \mid \mathbf{x})\).
    3. For the two classes healthy and sick, find the threshold on \(p(\textrm{sick} \mid \mathbf{x})\) above which the \(\arg\max\) of this \(\hat{\mathbf{y}}\) is sick, and choose the weights so that the threshold equals that of Equation 3.4.2. Explain why choosing \(w_\textrm{sick} > w_\textrm{healthy}\) raises recall, and what it does to the number of false positives.
  3. Calibration and usefulness. A ten-class problem has the same number of examples in every class.

    1. A classifier ignores its input and outputs the probability \(0.1\) for every class, breaking ties at random. Show that it is calibrated, and compute its accuracy.
    2. Another classifier is right on 95% of the examples and always reports confidence \(1\). Draw its reliability diagram and compute its expected calibration error.
    3. Explain why calibration and accuracy measure different things, and why neither can replace the other when a decision uses the threshold Equation 3.4.2.
  4. [code] ROC curves. A binary classifier that outputs a score \(s \in (0, 1)\) for the positive class can be thresholded at any \(\tau \in [0, 1]\), not just \(\frac{1}{2}\): predict positive whenever \(s > \tau\). The receiver operating characteristic (ROC) curve plots the true-positive rate (recall) against the false-positive rate \(\textrm{FP}/(\textrm{FP}+\textrm{TN})\) as \(\tau\) sweeps from \(1\) down to \(0\). Simulate \(1000\) positive and \(1000\) negative examples with scores \(s = \sigma(z)\), where \(\sigma(z) = 1/(1 + \exp(-z))\) is the sigmoid, \(z \sim \mathcal{N}(\mu, 1)\) for positives, and \(z \sim \mathcal{N}(0, 1)\) for negatives.

    1. Compute and plot the ROC curve for \(\mu \in \{0, 1, 2\}\), and state which points of the plot the endpoints \(\tau = 1\) and \(\tau = 0\) give.
    2. Show that a classifier whose scores are independent of the labels traces the diagonal in expectation.
    3. For \(\mu = 2\), plot the precision-recall curve, precision against recall as \(\tau\) sweeps, once with equal numbers of positives and negatives and once with positives making up 1% of the examples (keep 1000 negatives and draw 10 positives, or reweight). Explain why the ROC curve does not change with the prevalence while the precision-recall curve drops, and which of the two describes the screening test of this section better.
  5. [code] AUC as ranking probability. ● This problem uses the ROC curves and simulated scores of problem 4.

    1. Show that, when no two scores tie, the area under the ROC curve equals the probability that a randomly chosen positive example receives a higher score than a randomly chosen negative one, which makes it a threshold-free summary of ranking quality.
    2. Compute this probability in closed form for the simulated scores and compare it with the trapezoidal area under each of the curves.
    3. Apply the ROC curve and the AUC to the trained softmax regression on the validation images of two classes \(a\) and \(b\), with \(a\) as the positive class and the score \(s = \sigma(o_a - o_b)\), the sigmoid of the difference of the two logits: sneaker versus sandal, and shirt versus T-shirt. Compare the ordering of the two AUCs with the entries of the confusion matrix \(\mathbf{C}\) of Section 3.3 for the same pairs, and explain why the two diagnostics need not agree.
  6. [code] Temperature scaling. The text fits \(T\) on the first half of the validation images.

    1. Draw the reliability diagrams of the second half before and after scaling, and show that the accuracy does not change.
    2. Fit \(T\) on the training images instead and compare it with the \(T\) of the text. Explain why the fit should use data that the model was not trained on.
    3. Compute the expected calibration error of the unscaled model with 5, 10, and 20 bins. How much does the number depend on the binning?