What learning is · lesson 8 of 13
Parts in this lesson
Aconfusion_matrix(y_test, pred)the four kinds of answer
Btp / (tp + fp), tp / (tp + fn)precision and recall, by hand
Cprecision_score, recall_score, f1_scorethe same, from sklearn.metrics
Droc_curve, roc_auc_scoreevery threshold at once

Measuring classifiers

Last updated

Accuracy treats every mistake as equally bad, and every class as equally common. Often neither is true: missing a cancer is worse than a false alarm, and a disease that 1 person in 100 has makes 99% accuracy easy and worthless. This lesson breaks a classifier’s answers into the four boxes of a confusion matrix, and builds the measures that matter from them: precision, recall, F1 and the ROC curve.

By the end of this lesson you can

  • Read a confusion matrix and name its four cells
  • Compute precision, recall and F1, by hand and with sklearn.metrics
  • Explain how moving a threshold trades precision against recall, and read a ROC curve and its AUC
  • Spot when accuracy hides a useless model

The confusion matrix

This lesson's data comes with scikit-learn: measurements of 569 breast tumours from cell images, each found to be malignant (cancer) or benign. The class we're looking for, malignant, is called positive; the other, negative. (Positive means "the thing we're testing for is there", not "good news".)

Every prediction lands in one of four boxes:

  • True positive (TP): malignant, and called malignant.
  • False negative (FN): malignant, but called benign. A missed cancer.
  • False positive (FP): benign, but called malignant. A false alarm.
  • True negative (TN): benign, and called benign.

Counted up, they make the confusion matrix. scikit-learn puts the truth in the rows and the prediction in the columns, negative class first:

tumours.ipynb

The same four numbers, laid out with their names:

The tumours’ confusion matrixtruth down the side, prediction across the top
predictedtruthbenignbenignmalignantmalignant104TNtrue negative3FPfalse positive6FNfalse negative58TPtrue positive

162 of 171 on the diagonal (outlined) are right; every box off it is a kind of mistake.

Of 171 test tumours: 104 benign called benign (TN), 3 benign called malignant (FP), 6 malignant called benign (FN), 58 malignant caught (TP). Accuracy is (104+58)/171=94.7%. But six missed cancers is the number a doctor would ask about first, and accuracy hides it.

Precision and recall

Two measures split the mistakes apart:

precision=TPTP+FP,recall=TPTP+FN

In words: precision is, of everything the model called positive, the share that really was. Recall is, of everything really positive, the share the model caught. Precision asks "when it raises the alarm, can I trust it?"; recall asks "does it miss any?"

On the grid, precision reads down the "predicted malignant" column, and recall reads along the "truly malignant" row:

Precision: one column58 of the 61 called malignant
predictedtruthbenignbenignmalignantmalignant104TNtrue negative3FPfalse positive6FNfalse negative58TPtrue positive

Precision uses the predicted-positive column: of the 61 called malignant, 58 really were.

Recall: one row58 of the 64 truly malignant
predictedtruthbenignbenignmalignantmalignant104TNtrue negative3FPfalse positive6FNfalse negative58TPtrue positive

Recall uses the truly positive row: of the 64 really malignant, 58 were caught.

tumours.ipynb

Precision is 58/61=0.951: 95% of its malignant calls were right. Recall is 58/64=0.906: it caught 91% of the cancers and missed 9%. For a screening test, recall is the one to push up: a false alarm means another test, but a miss means an untreated cancer. For a spam filter it's the other way round: a real message lost in spam (a false positive) is worse than some spam getting through, so precision matters more.

F1

When you want one number that needs both to be good, the usual choice is the F1 score:

F1=2⋅precision⋅recallprecision+recall

In words: twice the product over the sum, which is the harmonic mean of the two. It's 1 only if both are 1, and it's dragged down hard by whichever is worse. A model with precision 1.0 and recall 0.01 has an ordinary average of about 0.5, but an F1 of about 0.02. Here it's 0.928, between the two.

F1 treats precision and recall as equally important. If they aren't (as in screening), don't hide behind F1; report both, and say which one you're prioritising and why.

Thresholds, the ROC curve and AUC

Most classifiers don't just say yes or no. They give a score, often a probability, and you choose a threshold: everything at or above it is called positive. k-NN's score is the share of neighbours voting malignant, and predict uses a threshold of 0.5.

The threshold is a dial between the two kinds of mistake. Lower it and you catch more positives (recall up) but raise more false alarms (precision down). Drag it and watch everything move together:

Threshold sliderthreshold 0.5
00.51score: grey healthy, pink sickpositive →false positive raterecall
Called healthyCalled sick
Really healthy135 true negatives5 false positives
Really sick6 false negatives54 true positives

Precision 0.915, recall 0.9, F1 0.908, accuracy 0.945.

The ROC curve (receiver operating characteristic, a name from radar) shows every threshold at once. Each threshold gives a point: across, the false positive rate FP/(FP+TN), the share of negatives wrongly flagged; up, the true positive rate, which is recall. A perfect classifier reaches the top-left corner; a coin toss runs along the dashed diagonal.

tumours.ipynb

The AUC, the area under the ROC curve, sums the whole curve up in one number: 1.0 is perfect, 0.5 is guessing. It has a neat meaning: the chance that a randomly chosen positive gets a higher score than a randomly chosen negative. Here it's 0.979. AUC doesn't depend on any one threshold, so it compares models fairly before you've decided where to set the dial; then you pick the threshold that suits the problem's costs.

Wrong way: when accuracy lies

A disease affects 10 people in 1,000. Here's a "model" that says everyone is healthy:

lazy.ipynb

Accuracy 0.99, recall 0.0. It never finds a single sick person, and it's 99% accurate, because 99% of people are healthy. This is lesson 1.9's base-rate trap in a new form, and it's common: fraud, rare diseases, machine faults, anything where the interesting class is rare (class imbalance).

So whenever classes are uneven:

  • compare against this "always the common class" baseline before believing any accuracy;
  • look at the confusion matrix, and at precision and recall for the rare class;
  • use AUC or F1 to compare models, not accuracy.

Check what you learned

A fraud model flags 50 payments; 40 of them really are fraud. There were 80 frauds in all. What are its precision and recall?
Predict, then check with the threshold slider: you lower the threshold. What happens to recall and precision?
On data where 2% of machines are faulty, a model gets 98% accuracy. What should you check first?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning