Reading history

Confusion Matrix, Precision, Recall and F1 Score Explained

4 min read 2 views

Learn classification metrics: the confusion matrix, accuracy, precision, recall and F1, the accuracy trap on imbalanced data, and how to choose a metric.

“95% accurate” sounds impressive until you learn that the model never spots the cases you actually care about. Classification metrics break a model’s results down by type of mistake, so you can see whether it misses real cases, raises false alarms, or both. This lesson explains the confusion matrix, precision, recall and the F1 score with a small worked example you can check by hand.

In this lesson you will learn

  • True and false positives and negatives
  • Reading a confusion matrix
  • Precision, recall and the F1 score
  • Why accuracy misleads on imbalanced data
  • Reading scikit-learn’s classification_report

The Confusion Matrix

Imagine a screening test for 20 patients, 5 of whom have a disease. Every prediction falls into one of four boxes:

Predicted diseasePredicted healthy
Actually has diseaseTrue positive (TP)False negative (FN): a missed case
Actually healthyFalse positive (FP): a false alarmTrue negative (TN)
from sklearn.metrics import (accuracy_score, confusion_matrix, precision_score,
                             recall_score, f1_score, classification_report)

# 1 = has the disease, 0 = healthy (20 patients)
actual    = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
predicted = [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

tn, fp, fn, tp = confusion_matrix(actual, predicted).ravel()
print(f"TP={tp}  FN={fn}  FP={fp}  TN={tn}")
print("Accuracy: ", accuracy_score(actual, predicted))
print("Precision:", precision_score(actual, predicted))
print("Recall:   ", recall_score(actual, predicted))
print("F1 score: ", round(f1_score(actual, predicted), 3))
print()
print(classification_report(actual, predicted, target_names=["healthy", "disease"]))

Output

TP=3  FN=2  FP=1  TN=14
Accuracy:  0.85
Precision: 0.75
Recall:    0.6
F1 score:  0.667

              precision    recall  f1-score   support

     healthy       0.88      0.93      0.90        15
     disease       0.75      0.60      0.67         5

    accuracy                           0.85        20
   macro avg       0.81      0.77      0.78        20
weighted avg       0.84      0.85      0.84        20

What Each Metric Means

MetricFormulaQuestion it answersHere
Accuracy(TP + TN) / allHow often is it right overall?17/20 = 0.85
PrecisionTP / (TP + FP)When it says “disease”, how often is it right?3/4 = 0.75
Recall (sensitivity)TP / (TP + FN)Of the real cases, how many did it find?3/5 = 0.60
F1 score2 × P × R / (P + R)A single balance of precision and recall0.667
  • scikit-learn’s confusion_matrix puts actual classes in rows and predictions in columns, ordered by label (0 then 1), so ravel() returns TN, FP, FN, TP in that order.
  • The model looks fine at 85% accuracy but finds only 3 of the 5 sick patients. For a screening test, that low recall is the number that matters.
  • classification_report shows precision, recall and F1 for each class, plus averages. Support is the number of real examples of each class.

The Accuracy Trap

from sklearn.metrics import accuracy_score, recall_score

# A lazy "model" that always predicts healthy
actual = [1] * 5 + [0] * 95
always_healthy = [0] * 100
print("Accuracy:", accuracy_score(actual, always_healthy))
print("Recall:  ", recall_score(actual, always_healthy))

Output

Accuracy: 0.95
Recall:   0.0

When only 5% of cases are positive, a “model” that always answers “healthy” reaches 95% accuracy while finding nobody. Whenever one class is rare, as with fraud, disease or defects, look at recall, precision and F1 for the rare class instead of accuracy.

Which Metric Should You Optimise?

SituationFocus onWhy
Disease screening, fraud detectionRecallMissing a real case is very costly
Spam filter, recommending contentPrecisionFalse alarms annoy users or hide important email
Both errors matterF1 scoreBalances the two
Balanced classes, equal costsAccuracySimple and fair in that case

Precision and recall pull against each other. Lowering a logistic regression threshold catches more real cases (higher recall) but adds false alarms (lower precision).

Common Mistakes

  1. Reporting only accuracy on imbalanced data.
  2. Mixing up the confusion matrix layout between tools. In scikit-learn, rows are actual and columns are predicted.
  3. Calculating metrics on training data. Always use the test set.
  4. Forgetting which class is “positive”. By default it is label 1, so set pos_label if your class of interest is 0.

Practice Exercises

Exercise 1. A fraud model flags 50 transactions; 40 are really fraud. There were 80 frauds in total. Work out precision and recall.

Show answer

Precision = 40 / 50 = 0.80. Recall = 40 / 80 = 0.50. The model is usually right when it flags something, but it misses half of all fraud.

Exercise 2. Calculate F1 for precision 0.8 and recall 0.5.

Show answer

2 × 0.8 × 0.5 / (0.8 + 0.5) = 0.8 / 1.3 ≈ 0.615. F1 sits closer to the weaker of the two scores.

Frequently Asked Questions

What is the difference between macro and weighted averages?

A macro average treats every class equally. A weighted average weights each class by its support, so large classes count more. On imbalanced data the macro average shows how well the small classes are handled.

What are ROC curves and AUC?

They show how recall and false-alarm rate change across every possible threshold. AUC summarises the curve in one number from 0.5 (random guessing) to 1.0 (perfect ranking). Use roc_auc_score with predicted probabilities.

Summary

  • The confusion matrix counts TP, FP, FN and TN.
  • Precision measures false alarms; recall measures missed cases; F1 balances them.
  • Accuracy can be meaningless when one class is rare.
  • Choose the metric that matches the real cost of each mistake.

Next: K-Nearest Neighbours.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *