Intermediate: machine learning · Evaluating models · topic 28 of 62 · 35 min
Confusion matrix, accuracy, precision, recall and F1
Explanation
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 positive | Predicted negative | |
|---|---|---|
| Actually positive | True positive (TP): caught | False negative (FN): missed |
| Actually negative | False positive (FP): false alarm | True 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.
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))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.
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 classCommon 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. 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)
Write confusion(y_true, y_pred) for labels 0 and 1 (1 is the positive class). Return the tuple (tp, fp, fn, tn).
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).
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Thresholds, ROC-AUC and imbalanced classesEvaluating models · same module
- Regression metrics: MAE, MSE, RMSE and R²Evaluating models · same module
- Evaluating LLM appsBuilding with generative AI, and MLOps
- The ML workflow end to endThe ML workflow, regression and classification
- Intrusion detection and prevention (IDS/IPS)Cyber Security: from zero to SOC analyst · Identity and network defence
- Monitoring with CloudWatch, CloudTrail and ConfigCloud Computing (AWS, Azure, Google Cloud) · Serverless, monitoring and cost control
Questions people ask about this
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.
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.
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.
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
- 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.
- Module 6 exam: Evaluating models · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, k-NN, decision trees and ensembles. 62 topics left in the course before the final exam.