3.4 Measuring Classifiers
Our Fashion-MNIST softmax regression model classifies roughly 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:
- Class imbalance: When the positive class of interest is rare (say, of patients have a disease or of transactions are fraudulent), a useless classifier that always predicts the majority class scores or accuracy while catching zero positives.
- Asymmetric error costs: Missing a life-threatening illness (a false negative) is vastly costlier than ordering a follow-up test (a false positive).
- Probability-driven decisions: Downstream decision rules act directly on the numerical predicted probabilities , 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 people for a disease with prevalence ( sick and healthy). A trivial rule that ignores every test result and always predicts healthy achieves accuracy while detecting not a single sick patient. Now compare it against a real screening test that detects of sick patients while falsely flagging of healthy ones:
| sick (positive) | healthy (negative) | |
|---|---|---|
| predicted sick | (TP) | (FP) |
| predicted healthy | (FN) | (TN) |
In this binary confusion matrix, the four cells are true positives (), false positives (), false negatives (), and true negatives (). Summing the diagonal gives accuracy, so raw accuracy ranks the useless "always-healthy" rule () ahead of a lifesaving test ().
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:
Reading down the first column gives (versus for "always healthy"). Reading across the first row gives : only of flagged people are actually sick, because false alarms from the huge healthy majority () outnumber the true positives (the Bayes' theorem effect from Section 1.6.5.2). In two-stage clinical screening, recall with precision is ideal: the cheap first test catches almost every sick patient and sends only the flagged patients to a definitive follow-up test.
Let us hold our test's intrinsic recall () and false-alarm rate () fixed while sweeping the disease prevalence across :
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 whereas a false alarm costs (and correct calls cost ). Weighted by these penalties, the "always-healthy" rule incurs an expected cost of per person, whereas our screening test costs per person, nearly seven times lower.
More generally, if a classifier estimates probability for an individual, predicting healthy has expected cost and predicting sick has expected cost . Predicting sick minimizes expected cost whenever
Equal costs () recover the familiar threshold (argmax classification). With and , however, the optimal threshold drops to : even a 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 , 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 , which means they rely on the classifier being calibrated: among all examples where the classifier predicts confidence , roughly should actually be correct.
In a -class problem, we check top-class calibration by recording each validation prediction's confidence and correctness indicator , partitioning the examples into confidence bins , and comparing each bin's mean confidence against its empirical accuracy . Plotting against gives a reliability diagram (where a perfectly calibrated model lies along the diagonal ), and their sample-weighted average gap defines the expected calibration error (ECE):
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 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 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 (), empirical accuracy tracks mean confidence within eight percentage points, sitting slightly above the diagonal (average confidence vs. accuracy , for an ECE below ). 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 (Section 3.1), and fit to minimize cross-entropy on a held-out validation split. Because dividing by preserves logit ordering, temperature scaling never alters a single class prediction or changes accuracy; it only rescales confidence ( damps overconfidence; sharpens underconfidence). Let us fit 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 (), 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 (, an intrinsic property of the classifier) and precision (, which scales with population prevalence via Bayes' theorem). When false negatives and false positives carry unequal costs and , expected cost is minimized by predicting positive whenever , 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 on held-out data rescales confidence without changing accuracy.
3.4.4 Exercises#
-
Optimal decisions and rejection. In a multiclass problem, let be the cost of predicting class when the true class is , and let be the probability of class given the input .
- Write the expected cost of predicting in terms of the costs and , and state the rule that selects the optimal . Check that it reduces to (3.4.2) for two classes.
- Let a correct guess cost and a wrong guess cost , and allow the classifier to abstain instead of guessing, at a fixed cost . Derive the threshold on the top-class probability above which guessing beats abstaining.
- In medical diagnosis, deferring to a specialist is cheap relative to a misdiagnosis, say . Compute the threshold and state what the classifier should do with a prediction at confidence. Then describe a case in which reporting the full distribution serves the physician better than either guessing or abstaining.
Adapted from Kevin Murphy, Probabilistic Machine Learning: An Introduction, Exercise 5.1.
-
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 a weight and train on the class-weighted average loss
where is the cross-entropy loss and is the class of example , so that every example of class counts times.
- Let the training examples be drawn with class prior and class-conditional densities . 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 . Name the change to the training data, rather than to the loss, that has the same effect.
- Fix an input with class probabilities , and suppose the model can output any distribution . Show that the expected weighted loss
is minimized by .
-
For the two classes healthy and sick, find the threshold on above which the of this is sick, and choose the weights so that the threshold equals that of (3.4.2). Explain why choosing raises recall, and what it does to the number of false positives.
-
Calibration and usefulness. A ten-class problem has the same number of examples in every class.
- A classifier ignores its input and outputs the probability for every class, breaking ties at random. Show that it is calibrated, and compute its accuracy.
- Another classifier is right on 95% of the examples and always reports confidence . Draw its reliability diagram and compute its expected calibration error.
- Explain why calibration and accuracy measure different things, and why neither can replace the other when a decision uses the threshold (3.4.2).
-
[code] ROC curves. A binary classifier that outputs a score for the positive class can be thresholded at any , not just : predict positive whenever . The receiver operating characteristic (ROC) curve plots the true-positive rate (recall) against the false-positive rate as sweeps from down to . Simulate positive and negative examples with scores , where is the sigmoid, for positives, and for negatives.
- Compute and plot the ROC curve for , and state which points of the plot the endpoints and give.
- Show that a classifier whose scores are independent of the labels traces the diagonal in expectation.
- For , plot the precision-recall curve, precision against recall as 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.
-
[code] AUC as ranking probability. ● This problem uses the ROC curves and simulated scores of problem 4.
- 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.
- Compute this probability in closed form for the simulated scores and compare it with the trapezoidal area under each of the curves.
- Apply the ROC curve and the AUC to the trained softmax regression on the validation images of two classes and , with as the positive class and the score , 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 of Section 3.3 for the same pairs, and explain why the two diagnostics need not agree.
-
[code] Temperature scaling. The text fits on the first half of the validation images.
- Draw the reliability diagrams of the second half before and after scaling, and show that the accuracy does not change.
- Fit on the training images instead and compare it with the of the text. Explain why the fit should use data that the model was not trained on.
- Compute the expected calibration error of the unscaled model with 5, 10, and 20 bins. How much does the number depend on the binning?