Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 11: Metrics

Open in Colab

When a measure becomes a target, it ceases to be a good measure.

Goodhart’s law, as phrased by Marilyn Strathern

11.1 One Number Is Never the Whole Story

Chapters 9 and 10 compared models by “the score”. Which score was a choice, and it matters as much as the model. A model that flags a few cancers it is very sure about, and one that flags almost every cancer at the price of many false alarms, can have the same accuracy and be useful in completely different places.

A metric should reflect what the mistakes cost in the problem at hand. This chapter gives the standard metrics, shows what each one sees and hides, and ends with a guide for choosing.

We use three datasets:

  • Breast cancer (569 tumours, 37% malignant): a balanced, medical classification problem.

  • Fraud-like transactions: 20 000 synthetic rows with 1.1% positives, generated with make_classification, to study imbalance.

  • Diabetes (442 patients): a regression problem, for the regression metrics.

171 test tumours, 64 malignant

11.2 The Confusion Matrix

For a binary classifier, every prediction falls in one of four cells. We call the class we look for positive (malignant, fraud, spam):

predicted positivepredicted negative
actually positivetrue positive (TP)false negative (FN): a miss
actually negativefalse positive (FP): a false alarmtrue negative (TN)
TP = 60, FN = 4, FP = 4, TN = 103

Of 64 malignant tumours, the model finds 60 and misses 4; of 107 benign ones, it raises 4 false alarms. Every metric of this section is a ratio of these four numbers.

11.3 Accuracy, Precision, Recall and F1

MetricFormulaQuestion it answersCancer test
AccuracyTP+TNall\dfrac{TP + TN}{\text{all}}how often is the model right?163/171=0.953163/171 = 0.953
PrecisionTPTP+FP\dfrac{TP}{TP + FP}when it says positive, how often is it right?60/64=0.93860/64 = 0.938
Recall (sensitivity, true positive rate)TPTP+FN\dfrac{TP}{TP + FN}of the real positives, how many does it find?60/64=0.93860/64 = 0.938
Specificity (true negative rate)TNTN+FP\dfrac{TN}{TN + FP}of the real negatives, how many does it clear?103/107=0.963103/107 = 0.963
F12⋅P⋅RP+R\dfrac{2 \cdot P \cdot R}{P + R}a balance of precision and recall0.938
accuracy 0.953  precision 0.938  recall 0.938  F1 0.938

Precision and recall pull against each other, and the right balance depends on the costs:

  • Recall first when a miss is costly: screening for cancer, detecting intrusions. A false alarm costs a second test; a miss can cost a life.

  • Precision first when a false alarm is costly: a spam filter that hides a real email, a fraud system that blocks a customer’s card, a recommendation that annoys.

F1 is the harmonic mean of the two: it is high only when both are, so a model cannot hide a terrible recall behind a perfect precision. When one matters more, the FβF_\beta score weights recall β\beta times as much as precision: Fβ=(1+β2) PR/(β2P+R)F_\beta = (1 + \beta^2)\,P R / (\beta^2 P + R); F2F_2 is common in screening.

11.4 Thresholds, ROC and Precision–Recall Curves

A probabilistic classifier outputs a score pp; the prediction “positive” is p≥tp \ge t for a threshold tt, 0.5 by default. Lowering tt flags more cases: recall rises, precision falls. Each threshold gives one confusion matrix, so a single model has a whole family of operating points.

The ROC curve

The ROC curve (receiver operating characteristic) plots the true positive rate (recall) against the false positive rate FP/(FP+TN)FP / (FP + TN) for every threshold. A random classifier lies on the diagonal; a perfect one hugs the top-left corner. The area under the ROC curve (ROC AUC) summarises it: the probability that a random positive gets a higher score than a random negative. 0.5 is chance, 1.0 is perfect.

The precision–recall curve

The precision–recall curve plots precision against recall for every threshold, and its area is summarised by average precision (AP). A random classifier has a precision equal to the share of positives, so the baseline of this curve moves with the class balance.

cancer: ROC AUC 0.992, average precision 0.989 (baseline 0.37)

On the balanced cancer data both are excellent. The difference between them appears with imbalance.

11.5 Imbalanced Classes

The accuracy paradox

20 000 transactions, 1.1% of them fraudulent:

1.1% positives; 66 frauds among 6000 test transactions
"never fraud": accuracy 0.989, recall 0
logistic regression: TP 16, FN 50, FP 3, TN 5931
  accuracy 0.9912  precision 0.842  recall 0.242  F1 0.376  balanced accuracy 0.621

A model that never predicts fraud reaches 98.9% accuracy. The logistic regression reaches 99.1%, and catches only 16 of 66 frauds (recall 0.24). Accuracy is dominated by the 5 934 easy negatives and says almost nothing about the frauds. Balanced accuracy, the mean of the recalls of both classes, gives 0.62: closer to the truth.

ROC AUC against average precision

ROC AUC 0.901   average precision 0.495   (a random model: 0.5 and 0.011)
Source
<Figure size 1000x360 with 2 Axes>

The ROC AUC of 0.90 looks excellent; the average precision of 0.50 tells the real story. The false positive rate divides by the 5 934 negatives, so even a few hundred false alarms barely move the ROC curve; precision divides by what the model flags, so it shows directly how many alarms are false. With rare positives, prefer the precision–recall curve.

Remedies

Three remedies, all aimed at the same thing: making the rare class count more.

  1. Move the threshold. The model is unchanged; only the decision rule is.

threshold 0.5 : TP 16 FN 50 FP   3   precision 0.842  recall 0.242  F1 0.376
threshold 0.2 : TP 28 FN 38 FP  16   precision 0.636  recall 0.424  F1 0.509
threshold 0.1 : TP 35 FN 31 FP  56   precision 0.385  recall 0.530  F1 0.446
threshold 0.05: TP 41 FN 25 FP 171   precision 0.193  recall 0.621  F1 0.295
  1. Weight the classes. class_weight='balanced' multiplies each example’s loss by the inverse of its class frequency, so the 1% count as much as the 99%.

  2. Resample. Duplicate minority examples (oversampling; SMOTE creates synthetic ones by interpolation), or drop majority examples (undersampling). Resample the training data only, never the test data.

class weights: TP 55 FN 11 FP 1031   precision 0.051  recall 0.833  ROC AUC 0.904
oversampling:  precision 0.052  recall 0.848

Weighting and oversampling both lift the recall from 0.24 to about 0.83, at a precision of 0.05: about 1 000 false alarms for 55 frauds found. The ROC AUC hardly changes (0.904): the models rank transactions almost as before; what changed is where the default threshold falls. In practice the three remedies are close cousins, and the threshold is chosen last, from the costs: if a missed fraud costs 50 times a false alarm, pick the threshold that minimises 50⋅FN+FP50 \cdot FN + FP on validation data.

11.6 Judging Probabilities

When the probabilities themselves are used (a risk score shown to a doctor, an expected loss in euros), a metric must judge them, not only the decisions:

  • Log loss (cross-entropy): −1n∑[ylog⁡p+(1−y)log⁡(1−p)]-\frac{1}{n}\sum [y \log p + (1 - y)\log(1 - p)]. Confident wrong answers are punished heavily.

  • Brier score: 1n∑(p−y)2\frac{1}{n}\sum (p - y)^2, the mean squared error of the probabilities.

  • Calibration: among the cases given p≈0.2p \approx 0.2, about 20% should be positive. A reliability diagram plots the observed frequency against the predicted probability.

plain model:    mean predicted probability 0.0109 (true rate 0.0110)  Brier 0.0074  log loss 0.0363
class weights:  mean predicted probability 0.2627                     Brier 0.1220  log loss 0.3834

The plain model’s average probability matches the true fraud rate; the weighted model’s is 24 times too high. Class weights and resampling distort probabilities: fine when only the decisions matter, wrong when the probabilities are reported. If both are needed, train without reweighting and move the threshold, or recalibrate (CalibratedClassifierCV).

11.7 More Than Two Classes

Precision, recall and F1 are computed per class (each class in turn is “positive”), then averaged:

  • Macro: the plain mean over classes. Every class counts equally, so a rare class with poor results pulls it down.

  • Weighted: the mean weighted by each class’s size.

  • Micro: pool all the counts first. For single-label problems it equals accuracy.

We keep only 20 images of the digit 9 among the handwritten digits, so that 9 becomes a rare class:

accuracy 0.965  micro F1 0.965  weighted F1 0.965  macro F1 0.955
F1 per class: [0.99 0.94 0.99 0.96 0.97 0.97 0.97 0.98 0.91 0.86]

Accuracy, micro and weighted F1 all say 0.965; only the macro F1 (0.955) is pulled down by the rare 9s, whose own F1 is 0.86. Report per-class numbers whenever the classes matter unequally, and use the macro average when every class deserves the same weight.

11.8 Regression Metrics

For a numerical target, the error of each prediction is ei=y^i−yie_i = \hat y_i - y_i:

MetricFormulaUnitsNotes
MAE$\frac{1}{n}\sume_i$
MSE1n∑ei2\frac{1}{n}\sum e_i^2squaredwhat least squares minimises; dominated by large errors
RMSEMSE\sqrt{\text{MSE}}the target’scomparable to MAE; always ≥\ge MAE
R²1−∑ei2∑(yi−yˉ)21 - \dfrac{\sum e_i^2}{\sum (y_i - \bar y)^2}nonethe share of variance explained; 0 = predicting the mean, can be negative
MAPE$\frac{1}{n}\sume_i / y_i$
MAE 44.6  RMSE 55.7  R² 0.393  MAPE 39.5%
baseline (predict the training mean): MAE 59.5

The model’s typical error is 45 points of disease progression (MAE), against 60 for always predicting the mean; it explains 39% of the variance.

Outliers: MAE against RMSE

Ten errors of about ±10, then the same with one error of 100:

ten errors of about 10  : MAE   9.9   RMSE  10.0
one of them becomes 100 : MAE  18.9   RMSE  33.0

One large error doubles the MAE but triples the RMSE: squaring makes large errors dominate. Choose RMSE when a large error is much worse than two half-size ones (a bridge load, a dosage); choose MAE when every unit of error costs the same, or when the data contain outliers you do not want to chase.

11.9 Other Tasks

  • Clustering (Chapter 13): the silhouette (without labels) and the adjusted Rand index (against known labels).

  • Ranking and retrieval (Chapters 6 and 21): precision@k, recall@k, mean reciprocal rank (MRR), nDCG.

  • Generated text and images (Part III): task-specific scores (BLEU, ROUGE, FID) and, increasingly, human or model-based judgement.

11.10 Choosing a Metric

SituationPrimary metricAlso report
Balanced classes, equal costsaccuracythe confusion matrix
A miss is costly (screening)recall, or F2F_2precision at that recall
A false alarm is costly (spam, blocking)precisionrecall at that precision
Rare positivesaverage precision (PR AUC)precision and recall at the chosen threshold
Ranking quality, any thresholdROC AUC (balanced data)the ROC curve
Probabilities are usedlog loss, Briera reliability diagram
Several classes of unequal sizemacro F1per-class F1
Regression, errors cost linearlyMAEa baseline’s MAE
Regression, large errors very costlyRMSEMAE, residual plot
Comparing to “predict the mean”R²RMSE in the target’s units

Whatever the metric, decide it before looking at the results, compute it on validation data for every choice, and on the test set once.

11.11 Summary

  • Everything about a binary classifier’s decisions is in its confusion matrix; accuracy, precision, recall, specificity and F1 are ratios of its cells.

  • The threshold trades precision for recall; ROC and precision–recall curves show every threshold at once.

  • With rare positives, accuracy and ROC AUC flatter the model; use precision–recall, and choose the threshold from the costs.

  • Class weights and resampling raise recall but distort probabilities.

  • Log loss, Brier score and calibration judge probabilities themselves.

  • Macro averages give every class equal weight; micro and weighted averages follow the big classes.

  • MAE measures the typical error; RMSE punishes large ones; R² compares with predicting the mean.

Exercises

  1. A test finds 90 of 100 sick patients and raises 30 false alarms among 900 healthy ones. Compute accuracy, precision, recall, specificity and F1.

  2. Why is the harmonic mean, not the arithmetic mean, used in F1? Give a precision and recall where the two means differ a lot.

  3. A fraud model has ROC AUC 0.95 and average precision 0.20, with 0.5% frauds. Is it good? What would you show the bank?

  4. A missed fraud costs 200 euros, a false alarm 2 euros. How would you choose the threshold?

  5. Explain why class_weight='balanced' raises recall but makes the predicted probabilities unusable as risks.

  6. A dataset has three classes with 900, 90 and 10 examples. A model gets F1 0.99, 0.80 and 0.10 on them. Compute the macro F1 and say what the micro F1 would hide.

  7. Two regression models have MAE 10 and 12, and RMSE 30 and 15. What does that tell you about their errors? Which would you deploy for estimating delivery times? For a medicine dose?

Further Reading

  • T. Fawcett, “An introduction to ROC analysis”, Pattern Recognition Letters, 2006.

  • T. Saito, M. Rehmsmeier, “The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets”, PLoS ONE, 2015.

  • H. He, E. A. Garcia, “Learning from imbalanced data”, IEEE TKDE, 2009.

  • A. Niculescu-Mizil, R. Caruana, “Predicting good probabilities with supervised learning”, ICML, 2005.

  • The scikit-learn user guide, “Metrics and scoring: quantifying the quality of predictions”.