# Chapter 7: Measuring Classifiers

> Confusion matrices, precision, recall, and the ROC curve. Opening question: A classifier is right 90% of the time. Is it any good?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/measuring-classifiers/

For regression, one number such as RMSE told us most of what we needed. Classification is trickier. There are two different ways to be wrong, they rarely cost the same, and the most obvious score can hide a useless model. This chapter builds the small set of measurements that people actually use.

## Ninety percent and useless

A clinic screens 200 patients for an illness. Twenty of them have it. Someone proposes this classifier:

> Whatever the patient's data says, answer "healthy".

It is right about all 180 healthy patients and wrong about the 20 ill ones. That is 180 out of 200, an accuracy of 90%. It has also failed every single person the screening exists to find.

Accuracy counts all mistakes as equal and all examples as equal. When one class is rare, as here, the data is imbalanced, and a model can score well by ignoring the rare class entirely. Fraud, faults, and disease are all like this: the cases that matter are the uncommon ones.

**Check your understanding:** One email in a hundred is a scam. A filter that lets every email through has what accuracy?

- 1% — It is wrong only about the scams, which are 1% of emails. It is right about the other 99%.
- 50% — There are two classes, but they are not equally common. Nearly every email is legitimate.
- 99% **(correct)** — It is right about the 99 legitimate emails and wrong about the 1 scam. A near-perfect score for a filter that does nothing.

## Four kinds of outcome

A real model gives each patient a risk score, and we flag those above a threshold, as in [the last chapter](https://thebookofml.com/logistic-regression/). Every patient then lands in one of four groups, depending on what the model said and what was true.

The table of those four counts is the confusion matrix. Two of its cells are mistakes. A healthy patient who is flagged is a false positive, a false alarm. An ill patient who is cleared is a false negative, a miss.

> **Interactive figure: One threshold, four outcomes.** Each dot is a patient. Ill patients are in the top row, healthy ones in the bottom row, and everyone to the right of the orange line is flagged.
> Try it: start at 0.50 and read the four counts. Then lower the threshold until no ill patient is missed, and see what that costs in false alarms.
> (Use it at https://thebookofml.com/measuring-classifiers/)

At a threshold of 0.50 the model catches 17 of the 20 ill patients and misses 3. It also raises 15 false alarms. Its accuracy is 91%, one point better than the classifier that did nothing, yet it is doing something completely different and far more useful. Accuracy could not tell them apart. The four counts can.

## Precision and recall

Two questions get the useful information out of the matrix. Each one looks at a different slice.

**Of the patients we flagged, how many are really ill?** That is precision. At 0.50 we flagged 32 people and 17 were ill:

$$
\text{precision} = \frac{\text{caught}}{\text{caught} + \text{false alarms}} = \frac{17}{17 + 15} = 53\%
$$

**Of the patients who are really ill, how many did we flag?** That is recall:

$$
\text{recall} = \frac{\text{caught}}{\text{caught} + \text{missed}} = \frac{17}{17 + 3} = 85\%
$$

The do-nothing classifier has a recall of zero, which exposes it immediately.

> **Interactive figure: A trade, not a free choice.** Precision and recall for every threshold from 0.05 to 0.95.
> Try it: slide the threshold to the right and watch precision climb while recall falls. Find a threshold where both are above 60%.
> (Use it at https://thebookofml.com/measuring-classifiers/)

The two pull in opposite directions. Flag almost everyone and recall is perfect but precision is dreadful. Flag only the most certain cases, say above 0.70, and precision rises to 85% while recall drops to 55%. No threshold maximises both.

When a single number is wanted, the F1 score combines them. It is high only when precision and recall are both high, so neither can be sacrificed for the other.

**Note:** F1 is 2 × precision × recall ÷ (precision + recall). A model with 100% precision and 0% recall has an F1 of 0, not 50%.

## Every threshold at once

Precision and recall describe a model *at one threshold*. To judge the model itself, whatever threshold is used later, plot all the thresholds together.

For each threshold, mark two things: across, the share of healthy patients wrongly flagged; up, the share of ill patients caught. Joining the points gives the ROC curve.

> **Interactive figure: The whole model in one curve.** Each point on the orange curve is one threshold. The dark dot is the threshold you choose.
> Try it: move the threshold from 0.95 down to 0.05 and watch the dot travel from the bottom left to the top right.
> (Use it at https://thebookofml.com/measuring-classifiers/)

A perfect model reaches the top left corner: every ill patient caught, no healthy one flagged. A model that guesses lies along the diagonal. The closer a curve bows toward the corner, the better the model separates the two groups.

The area under the curve, the AUC, sums this up in one number. It has a concrete meaning: pick one ill patient and one healthy patient at random, and the AUC is the chance that the model gives the ill one the higher score. Here it is 0.958. A perfect model scores 1, and guessing scores 0.5.

## Choosing the threshold

The ROC curve shows which trade-offs are available. It does not say which to take. That depends on what each mistake costs, and the costs come from the situation, not from the data.

**Example: Pricing the mistakes**

Suppose a false alarm means an extra blood test, cost 1 unit. A missed illness means late treatment, cost 50 units. Compare two thresholds:

| Threshold | Missed | False alarms | Accuracy | Total cost |
|---|---|---|---|---|
| 0.50 | 3 | 15 | 91.0% | 3 × 50 + 15 = 165 |
| 0.35 | 0 | 41 | 79.5% | 0 × 50 + 41 = 41 |

The lower threshold has much *worse* accuracy and a quarter of the cost.

> **Interactive figure: Put a price on each mistake.** The same patients, with each miss costing 50 and each false alarm costing 1.
> Try it: find the threshold with the lowest total cost. Notice that it is not the one with the highest accuracy.
> (Use it at https://thebookofml.com/measuring-classifiers/)

The default threshold of 0.50 treats both mistakes as equally bad. That is almost never true. A spam filter should rarely bin a real email, so it wants high precision. A screening test should rarely miss an illness, so it wants high recall. Decide which mistake is worse, by how much, and choose the threshold to match.

**Check your understanding:** A bank's fraud model blocks cards. Blocking a genuine customer is annoying; missing a fraud is expensive but refundable. Customers are leaving because of wrongly blocked cards. What should change?

- Lower the threshold, to catch more fraud — That raises recall and blocks even more genuine customers, the opposite of what is needed.
- Raise the threshold, accepting lower recall **(correct)** — A higher threshold blocks only the surest cases. Precision rises, fewer genuine customers are blocked, and a little more fraud gets through.
- Report accuracy instead of precision — Changing the report changes nothing about which cards are blocked.

**Common mistake: Quoting precision without recall**

Either number can be made perfect on its own. Flag only the single case you are surest about, and precision is 100%. Flag everybody, and recall is 100%. Neither model is any use. A precision figure means something only next to the recall achieved at the same threshold, and the other way round. When someone reports just one of them, ask for the other.

## In code

```python
from sklearn.metrics import (classification_report, confusion_matrix,
                             precision_score, recall_score, roc_auc_score)

# y_true: 1 for ill, 0 for healthy.   scores: the model's risk score for each patient.
y_pred = (scores >= 0.5).astype(int)            # apply a threshold yourself

print(confusion_matrix(y_true, y_pred))         # [[165  15]     rows: truth (healthy, ill)
                                                #  [  3  17]]    columns: prediction
print(precision_score(y_true, y_pred))          # 0.53
print(recall_score(y_true, y_pred))             # 0.85
print(roc_auc_score(y_true, scores))            # 0.958: uses the scores, not a threshold

print(classification_report(y_true, y_pred))    # precision, recall and F1 for both classes
```

Note that scikit-learn puts the negative class first, so the matrix reads cleared-and-healthy in the top left. Always check which way round a confusion matrix is before reading it.

## Key takeaways

- **Accuracy misleads** when one class is rare. A model can score well by ignoring the cases that matter.
- The **confusion matrix** separates the two kinds of mistake: false alarms and misses.
- **Precision** asks how trustworthy a flag is. **Recall** asks how many real cases were found. Raising one lowers the other.
- The **ROC curve** shows every threshold at once, and **AUC** scores the model without choosing one.
- The right threshold depends on **what each mistake costs**. 0.50 is rarely it.

## What you should now be able to do

- Explain why accuracy misleads when one class is rare.
- Fill in a confusion matrix and work out precision, recall and F1 from it.
- Read an ROC curve and say what AUC measures.
- Choose a threshold from the costs of the two kinds of mistake.

## Exercises

### Exercise (by hand)

At a threshold of 0.50 the screening model catches 17 of the 20 ill patients and raises 15 false alarms among the 180 healthy ones. Fill in the four cells of the confusion matrix, then work out accuracy, precision, recall and F1.

**Hint:**

True negatives are the healthy patients who were not flagged: 180 minus the false alarms.

**Solution:**

True positives 17, false negatives 3, false positives 15, true negatives $180 - 15 = 165$.

- Accuracy: $(17 + 165) / 200 = 91\%$
- Precision: $17 / (17 + 15) = 17 / 32 \approx 53\%$
- Recall: $17 / 20 = 85\%$
- F1: $2 \times 0.53 \times 0.85 / (0.53 + 0.85) \approx 0.65$

About half of the flags are false alarms, and three ill patients in twenty are missed. The accuracy figure hides both facts.

### Exercise (by hand)

For the same 200 patients, work out accuracy, precision and recall for a model that flags everyone, and for a model that flags no one.

**Hint:**

For each model, fill in the four cells first. One of the measures ends up as 0 divided by 0.

**Solution:**

**Flags everyone.** All 20 ill patients are caught, so recall is 100%. Of the 200 flags, 20 are right, so precision is 10%. Accuracy is also 10%.

**Flags no one.** No ill patient is caught, so recall is 0%. Accuracy is $180 / 200 = 90\%$. Precision is 0 divided by 0, which has no value: the model never made a flag to be judged.

The two extremes show why one number is never enough. Each of them is perfect on one measure and useless in practice.

### Exercise (by hand)

A false alarm costs 1 (a follow-up test) and a missed illness costs 20. Threshold A gives 15 false alarms and 3 misses. Threshold B gives 40 false alarms and 1 miss. Which is cheaper? Which has the higher accuracy?

**Hint:**

Multiply each kind of mistake by its cost and add. For accuracy, count the mistakes of both kinds together.

**Solution:**

Cost of A: $15 \times 1 + 3 \times 20 = 75$. Cost of B: $40 \times 1 + 1 \times 20 = 60$. **B is cheaper.**

Accuracy of A: 18 mistakes in 200, so 91%. Accuracy of B: 41 mistakes in 200, so 79.5%. **A is more accurate.**

Accuracy counts every mistake the same. When a miss is twenty times worse than a false alarm, the better model is the one that makes more mistakes of the cheap kind.

### Exercise (think)

What does an AUC of 0.5 tell you about a model? What about an AUC of 0.3, and what would you do with such a model?

**Hint:**

AUC is the chance that a random positive case gets a higher score than a random negative one.

**Solution:**

AUC is the chance that the model gives a randomly chosen positive case a higher score than a randomly chosen negative one. At 0.5 the scores carry no information: the model ranks no better than a coin.

An AUC of 0.3 means the model usually ranks positives **below** negatives. It has found a real pattern and has it backwards. Flip its scores (use one minus the score) and the AUC becomes 0.7. In practice an AUC well below 0.5 nearly always means a bug, such as labels swapped somewhere.

### Exercise (with the figure)

In the figure "A trade, not a free choice", read precision and recall at a threshold of 0.50 and at 0.70. Then find the lowest threshold at which no ill patient is missed, and read the precision there.

**Hint:**

At 0.50 the model catches 17 of 20 with 15 false alarms.

**Solution:**

At 0.50, recall is 85% and precision about 53%. At 0.70, precision rises to 85% and recall falls to 55%: the flags are more trustworthy and nearly half the ill patients are missed.

To miss nobody the threshold has to drop well below 0.50, and precision falls a long way, because most of the people flagged are now healthy. For a screening test that can be the right choice: a false alarm costs a follow-up test, and a miss costs far more.

## Going further

### When to prefer a precision-recall curve

With a very rare positive class, the ROC curve can look excellent while precision is poor, because the false alarm rate is a share of a huge number of negatives. Plotting precision against recall for every threshold gives a more honest picture in that case.

### Is 70% really 70%?

A risk score of 0.7 is only useful as a probability if about 70% of patients given that score turn out to be ill. A model for which this holds is called calibrated. A model can rank patients well, with a high AUC, and still be badly calibrated.

### More than two classes

With several classes the confusion matrix grows to one row and one column per class. Precision and recall are then computed for each class in turn and averaged.

## References

- Google, *Machine Learning Crash Course*: [Classification](https://developers.google.com/machine-learning/crash-course/classification).
- MLU-Explain, [ROC and AUC](https://mlu-explain.github.io/roc-auc/) and [Precision and Recall](https://mlu-explain.github.io/precision-recall/).
- T. Fawcett, "An introduction to ROC analysis", *Pattern Recognition Letters* 27 (2006).

## Next

With a way to measure classifiers in hand, the rest of this part builds three more of them, each on a different idea. The first has no weights and does no training at all.
