3.4 Measuring Classifiers

Our Fashion-MNIST softmax regression model classifies roughly 83%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%1\% of patients have a disease or 0.1%0.1\% of transactions are fraudulent), a useless classifier that always predicts the majority class scores 99%99\% or 99.9%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 y^\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,000100{,}000 people for a disease with 1%1\% prevalence (1,0001{,}000 sick and 99,00099{,}000 healthy). A trivial rule that ignores every test result and always predicts healthy achieves 99%99\% accuracy while detecting not a single sick patient. Now compare it against a real screening test that detects 90%90\% of sick patients while falsely flagging 5%5\% of healthy ones:

sick (positive)healthy (negative)
predicted sick900900 (TP)4,9504{,}950 (FP)
predicted healthy100100 (FN)94,05094{,}050 (TN)

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

recall=TPTP+FN,precision=TPTP+FP.(3.4.1)\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 recall=900/1,000=0.90\textrm{recall} = 900 / 1{,}000 = 0.90 (versus 00 for "always healthy"). Reading across the first row gives precision=900/5,850≈0.15\textrm{precision} = 900 / 5{,}850 \approx 0.15: only 15%15\% of flagged people are actually sick, because 5%5\% false alarms from the huge healthy majority (4,9504{,}950) outnumber the 900900 true positives (the Bayes' theorem effect from Section 1.6.5.2). In two-stage clinical screening, 90%90\% recall with 15%15\% precision is ideal: the cheap first test catches almost every sick patient and sends only the 5,8505{,}850 flagged patients to a definitive follow-up test.

Let us hold our test's intrinsic recall (0.900.90) and false-alarm rate (0.050.05) fixed while sweeping the disease prevalence across {0.1%,1%,10%,50%}\{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 κFN=100\kappa_{\textrm{FN}} = 100 whereas a false alarm costs κFP=1\kappa_{\textrm{FP}} = 1 (and correct calls cost 00). Weighted by these penalties, the "always-healthy" rule incurs an expected cost of 100×1,000/100,000=1.00100 \times 1{,}000 / 100{,}000 = 1.00 per person, whereas our screening test costs (100×100+1×4,950)/100,000≈0.15(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(sick∣x)p = P(\textrm{sick} \mid \mathbf{x}) for an individual, predicting healthy has expected cost p κFNp\,\kappa_{\textrm{FN}} and predicting sick has expected cost (1−p) κFP(1 - p)\,\kappa_{\textrm{FP}}. Predicting sick minimizes expected cost whenever

p κFN>(1−p) κFP,that is,p>κFPκFP+κFN.(3.4.2)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 (κFN=κFP\kappa_{\textrm{FN}} = \kappa_{\textrm{FP}}) recover the familiar 1/21/2 threshold (argmax classification). With κFN=100\kappa_{\textrm{FN}} = 100 and κFP=1\kappa_{\textrm{FP}} = 1, however, the optimal threshold drops to 1/101≈0.011/101 \approx 0.01: even a 2%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 precision⋅recall/(precision+recall)= 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 (3.4.2) act directly on the numerical value of pp, which means they rely on the classifier being calibrated: among all examples where the classifier predicts confidence p^≈0.80\hat{p} \approx 0.80, roughly 80%80\% should actually be correct.

In a qq-class problem, we check top-class calibration by recording each validation prediction's confidence p^(i)=max⁡jy^j(i)\hat{p}^{(i)} = \max_j \hat{y}^{(i)}_j and correctness indicator c(i)=1(argmax⁡jy^j(i)=y(i))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),…,[0.9,1.0][0, 0.1), [0.1, 0.2), \ldots, [0.9, 1.0], and comparing each bin's mean confidence pˉb\bar{p}_b against its empirical accuracy aba_b. Plotting aba_b against pˉb\bar{p}_b gives a reliability diagram (where a perfectly calibrated model lies along the diagonal ab=pˉba_b = \bar{p}_b), and their sample-weighted average gap defines the expected calibration error (ECE):

ECE=∑bnbn∣ab−pˉb∣.(3.4.3)\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

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

Filtering to well-populated bins with at least 100100 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=xy = 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 (nb≥100n_b \geq 100), empirical accuracy tracks mean confidence within eight percentage points, sitting slightly above the diagonal (average confidence ∼81%\sim 81\% vs. accuracy ∼83%\sim 83\%, for an ECE below 0.030.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>0T > 0 (Section 3.1), and fit TT to minimize cross-entropy on a held-out validation split. Because dividing by T>0T > 0 preserves logit ordering, temperature scaling never alters a single class prediction or changes accuracy; it only rescales confidence (T>1T > 1 damps overconfidence; T<1T \lt 1 sharpens underconfidence). Let us fit TT 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

Consistent with our slightly underconfident reliability curve, the fitted temperature sits just below 11 (T≈0.9T \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 (TP/(TP+FN)\textrm{TP}/(\textrm{TP}+\textrm{FN}), an intrinsic property of the classifier) and precision (TP/(TP+FP)\textrm{TP}/(\textrm{TP}+\textrm{FP}), which scales with population prevalence via Bayes' theorem). When false negatives and false positives carry unequal costs κFN\kappa_{\textrm{FN}} and κFP\kappa_{\textrm{FP}}, expected cost is minimized by predicting positive whenever p>κFP/(κFP+κFN)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>0T > 0 on held-out data rescales confidence without changing accuracy.

3.4.4 Exercises#

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

    1. Write the expected cost of predicting ii in terms of the costs and p(j∣x)p(j \mid x), and state the rule that selects the optimal ii. Check that it reduces to (3.4.2) for two classes.
    2. Let a correct guess cost 00 and a wrong guess cost λs\lambda_s, and allow the classifier to abstain instead of guessing, at a fixed cost λr<λs\lambda_r \lt \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 λr/λs=0.05\lambda_r/\lambda_s = 0.05. Compute the threshold and state what the classifier should do with a prediction at 0.90.9 confidence. Then describe a case in which reporting the full distribution p(y∣x)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 jj a weight wj>0w_j > 0 and train ff on the class-weighted average loss

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

where ll is the cross-entropy loss and y(i)y^{(i)} is the class of example ii, so that every example of class jj counts wjw_j times.

  1. Let the training examples be drawn with class prior p(y)p(y) and class-conditional densities p(x∣y)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 wy p(y)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 x\mathbf{x} with class probabilities p(j∣x)p(j \mid \mathbf{x}), and suppose the model can output any distribution y^\hat{\mathbf{y}}. Show that the expected weighted loss
−∑jwj p(j∣x)log⁡y^j(3.4.5)-\sum_j w_j\, p(j \mid \mathbf{x}) \log \hat{y}_j \tag{3.4.5}

is minimized by y^j∝wj p(j∣x)\hat{y}_j \propto w_j\, p(j \mid \mathbf{x}).

  1. For the two classes healthy and sick, find the threshold on p(sick∣x)p(\textrm{sick} \mid \mathbf{x}) above which the arg⁡max⁡\arg\max of this y^\hat{\mathbf{y}} is sick, and choose the weights so that the threshold equals that of (3.4.2). Explain why choosing wsick>whealthyw_\textrm{sick} > w_\textrm{healthy} raises recall, and what it does to the number of false positives.

  2. 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.10.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 11. 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 (3.4.2).
  3. [code] ROC curves. A binary classifier that outputs a score s∈(0,1)s \in (0, 1) for the positive class can be thresholded at any τ∈[0,1]\tau \in [0, 1], not just 12\frac{1}{2}: predict positive whenever s>τs > \tau. The receiver operating characteristic (ROC) curve plots the true-positive rate (recall) against the false-positive rate FP/(FP+TN)\textrm{FP}/(\textrm{FP}+\textrm{TN}) as τ\tau sweeps from 11 down to 00. Simulate 10001000 positive and 10001000 negative examples with scores s=σ(z)s = \sigma(z), where σ(z)=1/(1+exp⁡(−z))\sigma(z) = 1/(1 + \exp(-z)) is the sigmoid, z∼N(μ,1)z \sim \mathcal{N}(\mu, 1) for positives, and z∼N(0,1)z \sim \mathcal{N}(0, 1) for negatives.

    1. Compute and plot the ROC curve for μ∈{0,1,2}\mu \in \{0, 1, 2\}, and state which points of the plot the endpoints τ=1\tau = 1 and τ=0\tau = 0 give.
    2. Show that a classifier whose scores are independent of the labels traces the diagonal in expectation.
    3. For μ=2\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.
  4. [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 aa and bb, with aa as the positive class and the score s=σ(oa−ob)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 C\mathbf{C} of Section 3.3 for the same pairs, and explain why the two diagnostics need not agree.
  5. [code] Temperature scaling. The text fits TT 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 TT on the training images instead and compare it with the TT 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?

Discussions