Measuring Classifiers

Dive into Deep Learning · §3.4

Measuring Classifiers: Precision, Recall, Costs & Calibration
class imbalance · recall & precision · Bayes prevalence effect · cost-sensitive thresholds · reliability diagrams · ECE · temperature scaling

When Higher Accuracy Means a Worse Classifier

The Limits of Raw Accuracy

Our Fashion-MNIST classifier reached \sim 83\% accuracy on 10 balanced classes where every mistake costs the same. Three conditions break that symmetry:

  • Severe class imbalance: Under 1\% disease prevalence, always predicting healthy scores 99\% accuracy while detecting zero positive cases.
  • Asymmetric error costs: Missing an illness (\mathrm{FN}) is vastly costlier than ordering a confirmatory test (\mathrm{FP}).
  • Probability-driven decisions: Threshold rules act directly on \hat{p} = P(y \mid \mathbf{x}), requiring predicted confidences to match empirical accuracy (calibration).

The Binary Confusion Matrix Under Class Imbalance

1% Disease Prevalence Benchmark

Screening 100{,}000 people at 1\% prevalence (1{,}000 sick, 99{,}000 healthy) with a test that detects 90\% of sick patients (\mathrm{TP}=900, \mathrm{FN}=100) and falsely flags 5\% of healthy people (\mathrm{FP}=4{,}950, \mathrm{TN}=94{,}050):

  • The accuracy paradox: Summing the diagonal gives (900 + 94{,}050) / 100{,}000 = 94.95\% accuracy, so raw accuracy ranks the useless “always-healthy” rule (99.0\%) ahead of a test that catches 90\% of sick patients.
  • Why accuracy fails: True negatives (\mathrm{TN} = 94{,}050) swamp the denominator while the 1{,}000 sick patients contribute at most 1\%.

Isolating Positive Detection: Recall and Precision

Column vs. Row Ratios

To evaluate positive detection without being swamped by \mathrm{TN}, we pair two complementary ratios:

\mathrm{recall} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FN}}, \qquad \mathrm{precision} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FP}}

  • Recall (900/1{,}000 = 0.90): Fraction of truly sick patients caught (vs. 0.00 for “always healthy”).
  • Precision (900/5{,}850 \approx 0.154): Fraction of positive flags that are genuinely sick—sending only 5.85\% of the population to confirmatory testing.

How Precision Scales with Population Prevalence

Bayes’ Theorem in Classifier Evaluation

Holding intrinsic recall (0.90) and false-alarm rate (\mathrm{FPR} = 0.05) fixed while sweeping disease prevalence \pi = P(\text{sick}):

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

Precision Depends on Prevalence via Bayes’ Rule

Bayes’ Theorem in Classifier Evaluation

  • Intrinsic vs. prevalence-dependent: Recall and \mathrm{FPR} belong to the classifier alone, whereas precision P(\text{sick} \mid \text{flagged}) = \frac{\text{recall}\cdot\pi}{\text{recall}\cdot\pi + \mathrm{FPR}\cdot(1-\pi)} scales with population prevalence \pi via Bayes’ rule.

Asymmetric Error Costs and Expected Risk

Cost-Sensitive Evaluation

When false negatives and false positives carry unequal penalties \kappa_{\mathrm{FN}} and \kappa_{\mathrm{FP}}, we evaluate classifiers by expected cost per person:

\text{Expected Cost} = \frac{\kappa_{\mathrm{FN}}\cdot\mathrm{FN} + \kappa_{\mathrm{FP}}\cdot\mathrm{FP}}{n}

  • Numerical comparison (\kappa_{\mathrm{FN}} = 100,\; \kappa_{\mathrm{FP}} = 1):
    • “Always healthy” (\mathrm{FN} = 1{,}000,\; \mathrm{FP} = 0): costs 1.00 per person.
    • Screening test (\mathrm{FN} = 100,\; \mathrm{FP} = 4{,}950): costs 0.1495 per person, 6.7\times lower cost despite 4 points lower accuracy.

Deriving the Bayes-Optimal Decision Threshold

From Probabilities to Optimal Actions

Given a calibrated probability p = P(\text{sick} \mid \mathbf{x}), predicting healthy costs p\,\kappa_{\mathrm{FN}} in expectation while predicting sick costs (1 - p)\,\kappa_{\mathrm{FP}}:

p\,\kappa_{\mathrm{FN}} > (1 - p)\,\kappa_{\mathrm{FP}} \quad \Longleftrightarrow \quad p > \tau^* = \frac{\kappa_{\mathrm{FP}}}{\kappa_{\mathrm{FP}} + \kappa_{\mathrm{FN}}}

  • Equal costs (\kappa_{\mathrm{FN}} = \kappa_{\mathrm{FP}}): Recovers standard \tau^* = 1/2 (\operatorname{argmax}).
  • 100:1 cost ratio: Drops threshold to \tau^* = 1/101 \approx 0.01, so even a 2\% predicted risk warrants flagging.

Threshold Trade-Offs: Precision, Recall, F1 & ROC

Sweeping the Decision Threshold

Varying the decision threshold \tau \in [0, 1] trades recall directly against precision and false alarms:

  • Lowering \tau (\tau \downarrow): Monotonically increases recall (\mathrm{TP} \uparrow) while decreasing precision (\mathrm{FP} \uparrow).
  • F1 score: Harmonic mean \mathrm{F1} = \frac{2\,\mathrm{precision}\cdot\mathrm{recall}}{\mathrm{precision} + \mathrm{recall}}, which is small whenever either precision or recall is small.
  • Threshold-free curves: ROC (\mathrm{TPR} vs. \mathrm{FPR}, prevalence-invariant \mathrm{AUC}) and Precision–Recall (far more informative under 1\% imbalance).

What Does It Mean for a Classifier to Be Calibrated?

Trustworthy Probability Estimates

For a q-class classifier, define each prediction’s confidence and correctness:

\hat{p}^{(i)} = \max_{j} \hat{y}^{(i)}_j, \qquad c^{(i)} = \mathbf{1}\!\Big(\operatorname*{argmax}_j \hat{y}^{(i)}_j = y^{(i)}\Big)

  • Top-class calibration: Among examples where the model reports confidence \hat{p} \approx \alpha, the empirical accuracy satisfies P(c = 1 \mid \hat{p} = \alpha) = \alpha.
  • Orthogonal to accuracy: Predicting uniform (0.1, \ldots, 0.1) on 10 balanced classes is perfectly calibrated (10\% accuracy at 0.10 confidence) yet uninformative.

Reliability Bins and Expected Calibration Error (ECE)

Quantifying Miscalibration

Partition [0, 1] into B = 10 confidence bins I_b = [\frac{b-1}{B}, \frac{b}{B}) and compare each bin’s mean confidence \bar{p}_b against empirical accuracy a_b:

\mathrm{ECE} = \sum_{b=1}^B \frac{n_b}{n}\,\big|a_b - \bar{p}_b\big|

  • Empty low bins: By the pigeonhole principle, \max_j \hat{y}_j \ge 1/10, so bin [0, 0.1) always has n_1 = 0.

Computing Reliability Bins and ECE

Quantifying Miscalibration

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}')
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)

Auditing Calibration of Softmax Regression

Per-Bin Reliability Table on Fashion-MNIST

Computing reliability(conf, correct) across the 10{,}000 Fashion-MNIST validation predictions:

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}')

Reading the Per-Bin Reliability Table

Per-Bin Reliability Table on Fashion-MNIST

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
  • Interpreting the bin counts: Across the bins [0.4, 0.5) through [0.9, 1.0] (about 97\% of predictions), empirical accuracy matches mean confidence within about 6 percentage points, yielding an overall \mathrm{ECE} < 0.03.

Visualizing the Reliability Diagram

Overconfidence vs. Underconfidence

  • Reliability diagram: Plots a_b against \bar{p}_b for all bins with n_b \ge 100.
  • Diagonal reference (a_b = \bar{p}_b): A perfectly calibrated classifier lies on the dotted diagonal.
  • Above vs. below the diagonal: Points above the diagonal indicate an underconfident model (a_b > \bar{p}_b); points below indicate an overconfident model (a_b < \bar{p}_b).
  • Shallow vs. deep networks: Our linear model sits slightly above the diagonal (confidence \approx 81\% vs. accuracy \approx 83\%); deep networks typically sag well below it (T > 1 needed).

Post-Hoc Recalibration via Temperature Scaling

One-Parameter Convex Calibration Fix

Temperature scaling (Guo et al., 2017) freezes trained weights and fits a single scalar T > 0 on a held-out validation split to minimize validation NLL of \mathrm{softmax}(\mathbf{o} / T).

  • Why held-out data & zero accuracy loss: Fitting T on validation data reflects generalization margins, and because T > 0 preserves logit ranking, every class prediction and overall accuracy stay 100% unchanged.

Fitting the Temperature on Held-Out Data

One-Parameter Convex Calibration Fix

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

Concept Check: Screening Precision, Reject Option & ECE

Concept Check

Work out these three diagnostic and decision-making problems:

  1. Cleaner screening test: In our 1\%-prevalence disease example (1{,}000 sick, 99{,}000 healthy), suppose an upgraded test keeps 90\% recall (\mathrm{TP} = 900) while cutting false alarms on the healthy from 5\% down to 1\%. What are its new accuracy and precision, and does its accuracy beat “always healthy” (99.0\%)?
  2. Abstention / specialist referral (Exercise 1): Suppose a correct diagnosis costs 0, a misdiagnosis costs \lambda_s = 100, and referring an uncertain case to a human specialist costs \lambda_r = 5. Above what top-class confidence \hat{p} should the automated classifier make a diagnosis instead of abstaining?
  3. Temperature shift: If we divide all logits of our slightly underconfident Fashion-MNIST model by T = 2, what happens to its validation accuracy and to its ECE?

Answers: (1) \mathrm{FP} = 0.01 \times 99{,}000 = 990 and \mathrm{TN} = 98{,}010, giving accuracy (900 + 98{,}010)/100{,}000 = 98.91\% (still below 99.0\%) while precision jumps from 15.4\% to 900 / (900 + 990) \approx 47.6\%. (2) Expected error cost of guessing is (1 - \hat{p})\lambda_s; guessing beats abstaining when (1 - \hat{p})\lambda_s < \lambda_r \iff \hat{p} > 1 - \lambda_r/\lambda_s = 1 - 5/100 = 0.95. (3) Accuracy is unchanged (order of logits is preserved), while T = 2 pushes confidences even lower toward 0.10, worsening underconfidence and increasing ECE.

Summary: Metrics, Decisions, and Calibration

Section Summary

Diagnostic / Tool Mathematical Definition What It Solves
Recall (Sensitivity / TPR) \mathrm{TP} / (\mathrm{TP} + \mathrm{FN}) = P(\hat{y}=1 \mid y=1) Fraction of true positives caught; invariant to class prevalence
Precision (PPV) \mathrm{TP} / (\mathrm{TP} + \mathrm{FP}) = P(y=1 \mid \hat{y}=1) Fraction of positive flags that are true; scales with prevalence via Bayes’ rule
Bayes cost threshold Predict positive iff p > \frac{\kappa_{\mathrm{FP}}}{\kappa_{\mathrm{FP}} + \kappa_{\mathrm{FN}}} Minimizes expected asymmetric cost (\kappa_{\mathrm{FN}}=100, \kappa_{\mathrm{FP}}=1 \implies \tau^* = 1/101)
Reliability diagram & ECE \mathrm{ECE} = \sum_{b=1}^B \frac{n_b}{n}\big|a_b - \bar{p}_b\big| Audits whether predicted confidence \bar{p}_b matches empirical bin accuracy a_b
Temperature scaling \hat{\mathbf{y}}(T) = \mathrm{softmax}(\mathbf{o}/T),\; T^* = \operatorname{argmin}_T \mathrm{NLL}_{\mathrm{val}}(T) 1D convex post-hoc recalibration on held-out data; never alters accuracy