ML Atlas

Machine learning from zero · Lesson 2.2 · 9 of 33 lessons ready · 10 min

Evaluating a classifier: beyond accuracy

In short

Accuracy hides which mistakes a model makes. The confusion matrix, precision and recall reveal the trade-off a threshold creates on tumour data.

Warm-up Two questions from earlier lessons. A minute, and it never blocks the lesson.
From lesson 2.1: Classification: drawing a boundary What does logistic regression output before any threshold is applied?

Show the answer

Correct answer: A number from 0 to 1 — the probability of one of the classes

The sigmoid turns the weighted sum into a probability, and the threshold turns that probability into a decision.

From lesson 1.6: Gradient descent: learning by small steps The loss climbs higher with every step. What is the most likely cause?

Show the answer

Correct answer: The learning rate is too large, so the steps overshoot the minimum

With too large a step the parameters jump past the valley to a higher point each time, and the error grows.

A smoke alarm that never makes a sound is never wrong about a false fire. A smoke alarm that screams every time you make toast never misses a real one. Which is the better alarm? Neither — and a single accuracy number would not even tell you which one you have. This lesson is about counting mistakes in a way that shows their kind, not just their number.

Predict, then check You want to catch at least 95% of the malignant tumours (recall of at least 95%). What is the highest threshold on the slider that does it?
How sure are you?

Interactive lab

This interactive lab runs in a browser with JavaScript enabled. The text around it describes what the lab shows.

Show the answer

Correct answer: 0.1

At threshold 0.1 recall is 96.9% (62 of 64 malignant tumours found), at 0.2 only 92.2% and at 0.5 82.8%. You pay in false alarms: 20 healthy biopsies flagged as malignant at 0.1 against 3 at 0.5.

Try this

  • Move the threshold slider to the left. Watch the false negatives in the confusion matrix shrink and the false positives grow, and see recall and precision move in opposite directions.
  • Move the threshold slider to the right and watch the reverse happen. Keep an eye on accuracy: does it tell you which kind of mistake you are making?
  • Find the highest threshold at which no malignant tumour is missed. Read how many benign tumours are falsely flagged at that point.
  • Pick the threshold you would choose for a screening test, and say in one sentence why.

Now that you've tried it, let's see what was actually going on.

The idea in plain words

Back to the 569 breast tumours from lesson 1. A model gives each tumour a score: the higher the score, the more likely it is malignant. A threshold turns the score into a decision. Every decision then lands in one of four boxes:

predicted malignantpredicted benign
really malignanttrue positive (TP)false negative (FN)
really benignfalse positive (FP)true negative (TN)

This table is the confusion matrix. The diagonal holds the correct decisions. The two other cells hold two very different kinds of error: a false positive is a false alarm (a healthy patient sent for more tests), a false negative is a miss (a cancer sent home).

The smoke alarm makes the point. The silent alarm has no false positives and plenty of false negatives. The toast alarm has the reverse. A good alarm balances the two according to what each mistake costs.

Why it works

Two numbers summarise the matrix far better than accuracy does:

precision = TP / (TP + FP) recall = TP / (TP + FN)

Recall answers: of all the malignant tumours, what share did we catch? Precision answers: of all the tumours we called malignant, what share really were? Recall is about not missing; precision is about not crying wolf.

The threshold controls the trade-off between them. Lower the threshold and more tumours are flagged as malignant: you catch more cancers (recall rises) but also flag more benign tumours (precision usually falls). Raise it and the opposite happens. No threshold can maximise both, unless the model separates the classes perfectly. Choosing a threshold is therefore not a technical detail but a decision about values: how many false alarms are you willing to accept to avoid one missed cancer?

Accuracy blends all four cells into one number and hides this choice. It also hides class imbalance. Since 357 of the 569 tumours are benign, a model that calls everything benign gets nearly two thirds right while catching zero cancers — recall of zero. This is the accuracy paradox: a model can look decent by accuracy and be useless for the purpose it was built for.

Common mistake

The most common mistake is reporting accuracy alone, especially on imbalanced data where one class is much rarer than the other. The second is keeping the default threshold of 0.5 without asking what the errors cost. A screening test, where a miss can be fatal and a false alarm means an extra examination, should usually have a lower threshold than a test that triggers surgery. A third trap is mixing up precision and recall; remembering the questions they answer — "of those I flagged" versus "of those that exist" — helps more than memorising formulas.

So far we have scored models on one fixed test set. But a model can do brilliantly on the data it learned from and poorly on everything else. In the next lesson we make that happen on purpose: overfitting.

Catch the AI’s mistake

This is how a chatbot answered. One sentence is factually wrong. Which one?

Question: At threshold 0.1 my tumour classifier finds 62 of the 64 malignant tumours, but it also flags 20 benign ones. How should I read that?

Chatbot’s answer

Show the wrong sentence

The wrong sentence: And since precision is the share of all malignant tumours that the model catches, it is just as high here.

That is the definition of recall. Precision answers the other question — of the tumours flagged, how many are really malignant — and at threshold 0.1 the 20 false alarms pull it down, while at 0.5 there are only 3.

Quiz

Three questions to check yourself. Pick an answer, or open the answer under a question. Keyboard: arrow keys choose, Enter or Space confirms.

1. A screening model misses many cancers but almost never raises a false alarm. Which number is low?
Show the answer

Correct answer: Recall, i.e. the share of cancers detected

Recall is the share of real positives that were caught, so many misses mean low recall.

2. You lower the decision threshold. What usually happens?
Show the answer

Correct answer: Recall rises and precision usually falls, because there are more alarms

A lower threshold flags more cases as positive, catching more true positives but also adding false positives.

3. Why can accuracy be misleading on the tumour data?
Show the answer

Correct answer: Because with a benign majority a model can score well while missing every cancer

With imbalanced classes the majority answer alone produces a respectable accuracy and zero recall.

Key takeaways

  • The confusion matrix splits decisions into true and false positives and negatives.
  • Recall is the share of real positives caught; precision is the share of flagged cases that are real.
  • The threshold trades recall against precision, and the right balance depends on the cost of each error.
  • Accuracy hides the kind of mistakes and can look good on imbalanced data while missing every positive.

Going further: formula, code, practice

The math

A threshold t turns a score into a decision: predict malignant when score ≥ t. Counting the four boxes gives the metrics:

  • accuracy = (TP + TN) / n, the share of all decisions that are right;
  • precision = TP / (TP + FP), the share of alarms that are real;
  • recall = TP / (TP + FN), the share of real cases that were caught;
  • F1 = 2 · precision · recall / (precision + recall), the harmonic mean of the two, which stays low if either one is low.

Lowering t can only add alarms, so TP and FP never fall and FN never rises. That is why recall never falls as t goes down, while precision usually does. A model that always answers "benign" has TP = 0, so recall is 0, and its accuracy is just the share of the majority class: 357 / 569.

In code (Python)

The 569 tumours from the lesson, with the lab's 10 "mean" features, a scaled logistic regression and a stratified 30% test split (171 biopsies, random_state=1). The lab's own counts (TP / FN / FP) are 53 / 11 / 3 at threshold 0.5 and 62 / 2 / 20 at 0.1. This split is not the lab's, so the counts differ a little:

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, b = load_breast_cancer(return_X_y=True, as_frame=True)
X = X.filter(like="mean ")  # the 10 "mean" features, as in the lab
y = 1 - b  # in sklearn 0 = malignant; flip so that 1 = malignant
print(f"tumours {len(y)}, benign {(y == 0).sum()}, always-benign accuracy {(y == 0).mean():.3f}")
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, stratify=y, random_state=1)
score = make_pipeline(StandardScaler(), LogisticRegression()).fit(Xtr, ytr).predict_proba(Xte)[:, 1]
for t in (0.5, 0.1):
    flag = score >= t
    tp, fp, fn = (flag & (yte == 1)).sum(), (flag & (yte == 0)).sum(), (~flag & (yte == 1)).sum()
    print(f"t={t}: TP {tp} FN {fn} FP {fp} precision {tp / (tp + fp):.3f} recall {tp / (tp + fn):.3f}")

Output

tumours 569, benign 357, always-benign accuracy 0.627
t=0.5: TP 53 FN 11 FP 2 precision 0.964 recall 0.828
t=0.1: TP 61 FN 3 FP 13 precision 0.824 recall 0.953

At 0.5 recall is 0.828 here, as in the lab, but at 0.1 it is 0.953 against the lab's 96.9%, and the false alarms are 13 instead of 20. Recall moves from split to split, which is the point of lesson 2. Lowering the threshold from 0.5 to 0.1 still raises recall and lowers precision, as the lesson says. The always-benign baseline looks decent by accuracy and finds no cancer at all.

For practitioners
  • Report precision and recall (or the whole confusion matrix) next to accuracy, and always say which class is "positive".
  • Choose the threshold on validation data, from the cost of each error, not from habit. The default 0.5 is only a convention.
  • Always compute the baseline of predicting the majority class. If your accuracy is close to it, the model has learned little.
  • Recall and precision at one threshold are one point of a curve. To compare two models fairly, compare them at the same recall or look at the whole precision-recall curve.
  • A score is only a ranking unless it is calibrated. Do not read 0.3 as "30% chance" without checking calibration.

Go deeper in the Atlas

Encyclopedia entries on the ideas in this lesson: