Skip to content

Intermediate: machine learning · Evaluating models · topic 28 of 62 · 35 min

Confusion matrix, accuracy, precision, recall and F1

Explanation

A confusion matrix counts four outcomes of a yes/no model: true positives, false positives, false negatives and true negatives. Accuracy is the share right overall, which misleads when one class is rare. Precision asks "of the alarms, how many were real?"; recall asks "of the real cases, how many did we catch?"; F1 balances the two.

Why accuracy is not enough

Imagine 1,000 payments, of which 10 are fraud. A lazy model that says "not fraud" every time is 99% accurate and catches zero fraud. Accuracy hides this because the rare class barely affects it. To see what a classifier really does, we count each kind of right and wrong answer.

The confusion matrix

Predicted positivePredicted negative
Actually positiveTrue positive (TP): caughtFalse negative (FN): missed
Actually negativeFalse positive (FP): false alarmTrue negative (TN): correctly ignored

"Positive" means the class we are looking for: fraud, disease, spam. It is not "good". A false positive is a false alarm; a false negative is a miss.

The metrics

  • Accuracy = (TP + TN) ÷ all. The share of all predictions that are right.
  • Precision = TP ÷ (TP + FP). Of everything we flagged, how much was real? High precision means few false alarms.
  • Recall (also called sensitivity or true positive rate) = TP ÷ (TP + FN). Of all real positives, how many did we catch? High recall means few misses.
  • F1 = 2 × precision × recall ÷ (precision + recall). The harmonic mean: it is high only when BOTH are high.
python
tp, fp, fn, tn = 8, 12, 2, 978
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(round(precision, 2), round(recall, 2), round(f1, 2))
Shows 0.4 0.8 0.53. The model catches 8 of 10 frauds (good recall), but only 40% of its alarms are real (low precision).

Which one matters?

It depends on the cost of each mistake. In cancer screening, missing a case (FN) is far worse than an extra check (FP), so recall comes first. In a spam filter, hiding an important email (FP) is worse than letting one spam through, so precision comes first. In fraud detection, both matter, and teams often fix a minimum recall and then maximise precision. Talk to the people who live with the mistakes before choosing.

Think of it like this: Think of a security guard at a mall. A guard with high recall stops almost every shoplifter but also stops many honest shoppers. A guard with high precision only stops people who really stole, but lets some thieves walk out. The mall manager decides which balance is acceptable.
python
from sklearn.metrics import confusion_matrix, classification_report

print(confusion_matrix(y_test, y_pred))        # [[TN FP]
                                               #  [FN TP]]
print(classification_report(y_test, y_pred))   # precision, recall, F1 per class
Shown only. Note scikit-learn's layout: row 0 is the negative class, so TN is top-left.

Common mistakes

  • Reporting accuracy alone on imbalanced data. Fix: always show the confusion matrix and recall/precision for the rare class.
  • Dividing by zero when the model never predicts positive (precision is undefined). Fix: decide a rule; libraries usually report 0.
  • Mixing up scikit-learn's matrix layout with a textbook layout. Fix: print the labels.
  • Calling the averaged F1 of all classes "the F1" without saying which average (macro or weighted).

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Confusion matrix, accuracy, precision, recall and F1 · 1/6

Accuracy can lie

Accuracy can lie. A model that never finds fraud can still be ninety-nine percent accurate.

Prefer a video by a teacher? Find free videos on “confusion matrix precision recall f1 score explained” on YouTube ↗

In real life: Screening chest X-rays

A hospital tests an AI tool that flags chest X-rays for possible tuberculosis. The doctors insist on very high recall: a missed TB case can spread the disease. They accept lower precision, because a flagged X-ray only means a doctor looks more carefully. The evaluation report therefore leads with recall on confirmed TB cases, then shows how many extra reviews the tool creates per day.

Practice (0/3 done)

Task 1 · Code · Python

Write confusion(y_true, y_pred) for labels 0 and 1 (1 is the positive class). Return the tuple (tp, fp, fn, tn).

Task 2 · Code · Python

Write prf(tp, fp, fn) that returns (precision, recall, f1), each rounded to 4 decimal places. If a denominator is 0, that metric is 0.0 (and F1 is 0.0 when precision + recall is 0).

Task 3 · Code · Python

Show why accuracy misleads. Write lazy_vs_model(y_true, y_pred): return a tuple (lazy_accuracy, model_recall), where lazy_accuracy is the accuracy of always predicting 0, and model_recall is the recall of y_pred for class 1. Round both to 4 decimal places; recall is 0.0 if there are no positives.

Quick quiz

Question 1

1.A spam filter marks a real message from your bank as spam. What kind of error is this (spam = positive)?

Question 2

2.Recall answers which question?

Question 3

3.For early cancer screening, which metric usually matters most?

Question 4

4.Precision is 1.0 and recall is 0.1. What is F1, roughly?

Question 5

5.Why is accuracy misleading for rare events?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

A spam filter marks a real message from your bank as spam. What kind of error is this (spam = positive)?

Answer: False positive

It predicted positive (spam) but the truth was negative.

Recall answers which question?

Answer: Of all real positives, how many did we catch?

Recall = TP ÷ (TP + FN).

For early cancer screening, which metric usually matters most?

Answer: Recall

Missing a real case is the costliest mistake, so maximise recall.

Precision is 1.0 and recall is 0.1. What is F1, roughly?

Answer: 0.18

2 × 1 × 0.1 ÷ 1.1 ≈ 0.18. F1 stays low unless both are high.

Why is accuracy misleading for rare events?

Answer: Predicting the common class every time already scores very high

Accuracy is dominated by the large class.

A RAG bot gives wrong answers. recall@5 is 0.4. What should you fix first?Related

Answer: Retrieval: the right source is often not even retrieved

Without the right source, the answer cannot be grounded.

From Evaluating LLM apps

When you oversample the rare class with SMOTE, which data should you resample?Related

Answer: Only the training data

The test set must reflect the real world; resampling before splitting also leaks.

From Thresholds, ROC-AUC and imbalanced classes

A test for a rare condition is 99% sensitive. Why can most positive results still be false?Related

Answer: Because the healthy group is so large that even a small false positive rate gives many false alarms

This is the base rate fallacy: a small rate times a huge group can beat a large rate times a tiny group.

From Conditional probability and Bayes' theorem

Which prediction gives the LARGEST log loss when the true label is 1?Related

Answer: p = 0.02

A confident wrong answer (p near 0 for a true 1) is punished most.

From Logistic regression and classification

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Evaluating models” before its exam: Thresholds, ROC-AUC and imbalanced classes, Regression metrics: MAE, MSE, RMSE and R², Overfitting, underfitting and regularisation, Cross-validation and tuning hyperparameters.
  2. Module 6 exam: Evaluating models · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
  3. Then the next module, k-NN, decision trees and ensembles. 62 topics left in the course before the final exam.

← Previous: Train, validation and test sets