Machine Learning with scikit-learn

Confusion Matrix in Python with scikit-learn

See exactly which mistakes a classifier makes: read TP, FP, FN and TN, then precision, recall and the classification report.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • confusion_matrix and its layout
  • Unpacking tn, fp, fn, tp
  • Precision, recall and classification_report
rows = actual, columns = predicted
TN 5
FP 2
FN 1
TP 4

Counting right and wrong answers

The problem

A spam filter that is 75% accurate can be useless or fine, depending on its mistakes. Letting spam through and deleting real mail are very different errors, and accuracy hides which one happens.

Think of it like this

A confusion matrix is like a referee's scorecard with four boxes: goals correctly allowed, goals correctly refused, goals wrongly refused and fouls wrongly allowed. You can see not only how often the referee was right, but how they were wrong.

From a scorecard to code
TP = 4✅ Spam caught
TN = 5📬 Real mail delivered
FP = 2🚫 Real mail sent to spam
FN = 1📨 Spam that got through
Rows are the truth, columns are the predictions.
In one sentence

A confusion matrix is a table that counts the samples of each actual class (rows) by the class the model predicted (columns).

Key points

  1. For two classes, confusion_matrix(...).ravel() gives tn, fp, fn, tp in that order.
  2. Precision = TP / (TP + FP) = 0.67: a third of the spam alerts were wrong.
  3. Recall = TP / (TP + FN) = 0.80: 80% of the spam was caught.
  4. classification_report shows precision, recall and F1 for every class.

When should you use it?

  • Evaluating any classifier beyond accuracy.
  • Imbalanced problems such as fraud or disease detection.
  • Choosing between models that make different kinds of mistakes.

When not to use it

  • Regression models that predict numbers: use MAE or R^2.
  • Many classes: the table gets big; start with the classification report.

Example code

Open in editor →
main.py
from sklearn.metrics import classification_report, confusion_matrix

# 1 = spam, 0 = not spam
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1]

cm = confusion_matrix(y_true, y_pred)
print("Confusion matrix (rows = actual, columns = predicted):")
print(cm)

tn, fp, fn, tp = cm.ravel().tolist()
print(f"TN={tn} FP={fp} FN={fn} TP={tp}")
print(f"Precision = TP / (TP + FP) = {tp / (tp + fp):.2f}")
print(f"Recall    = TP / (TP + FN) = {tp / (tp + fn):.2f}")

print(classification_report(y_true, y_pred, target_names=["not spam", "spam"]))
Get a Run button for this example

Result of running the code

Confusion matrix (rows = actual, columns = predicted):
[[5 2]
 [1 4]]
TN=5 FP=2 FN=1 TP=4
Precision = TP / (TP + FP) = 0.67
Recall    = TP / (TP + FN) = 0.80
              precision    recall  f1-score   support

    not spam       0.83      0.71      0.77         7
        spam       0.67      0.80      0.73         5

    accuracy                           0.75        12
   macro avg       0.75      0.76      0.75        12
weighted avg       0.76      0.75      0.75        12

Code explanation

confusion_matrix puts actual classes in rows and predicted classes in columns, with class 0 first. So the top row says 5 real non-spam messages were kept (TN) and 2 were flagged as spam (FP), and the bottom row says 1 spam got through (FN) and 4 were caught (TP). cm.ravel() unpacks the four numbers in the order tn, fp, fn, tp. Precision 0.67 means a third of the spam alerts were wrong; recall 0.80 means 80% of the spam was caught. classification_report prints the same figures for both classes plus the overall accuracy of 0.75.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Trusting accuracy on imbalanced data

A model that always predicts the majority class can score 95% and catch nothing.

Problem
print(accuracy_score(y_true, y_pred))  # only
Fix
print(classification_report(y_true, y_pred))

Swapping the arguments

The true labels come first; swapping them transposes the matrix.

Problem
confusion_matrix(y_pred, y_true)
Fix
confusion_matrix(y_true, y_pred)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson