ML Confusion Matrix
"The model is 90 % accurate" sounds great — until you learn that 90 % of the emails were not spam to begin with, so a model that never flags anything would also be 90 % accurate. To understand a classifier you need to see which kinds of mistakes it makes. The tool for that is the confusion matrix.
The four outcomes
For a yes/no (binary) problem, every prediction lands in one of four boxes. Imagine a smoke detector that should beep (positive) when there is a fire:
| Predicted: no beep | Predicted: beep | |
|---|---|---|
| Actual: no fire | True Negative (TN) — quiet, correctly | False Positive (FP) — beeps at toast |
| Actual: fire | False Negative (FN) — misses a fire! | True Positive (TP) — beeps at a fire |
The diagonal (TN, TP) holds correct predictions; everything off the diagonal is a mistake. A false negative is far more dangerous than a false positive here — which is exactly the kind of insight a single accuracy number hides.
Computing a confusion matrix
sklearn.metrics.confusion_matrix(actual, predicted) counts the four boxes. Rows are the actual classes, columns the predicted classes:
from sklearn.metrics import confusion_matrix
actual = [0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1] # 1 = fire
predicted = [0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1] # 1 = beep
cm = confusion_matrix(actual, predicted)
print(cm)
tn, fp, fn, tp = cm.ravel()
print(f"TN={tn} FP={fp} FN={fn} TP={tp}")[[5 2]
[1 4]]
TN=5 FP=2 FN=1 TP=4
ravel() flattens the 2×2 matrix in the order TN, FP, FN, TP — a handy idiom.
A real classifier
Let's evaluate a model on scikit-learn's built-in breast cancer data set (569 tumours described by 30 measurements; the target is 0 = malignant, 1 = benign). It ships with the library, so no download is needed. We train a small decision tree and look at its test-set confusion matrix as a picture:
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.25, random_state=1, stratify=data.target)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
predicted = model.predict(X_test)
cm = confusion_matrix(y_test, predicted)
ConfusionMatrixDisplay(cm, display_labels=data.target_names).plot(cmap="Blues")
plt.show()
print(cm)[[49 4]
[ 4 86]]
stratify=data.target keeps the same share of malignant and benign cases in the training and test sets — a good habit for classification.
Metrics derived from the matrix
All the usual classification scores are simple ratios of the four counts:
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / all | How often is the model right overall? |
| Precision | TP / (TP + FP) | When it says "positive", how often is it right? |
| Recall (sensitivity) | TP / (TP + FN) | Of all real positives, how many did it find? |
| Specificity | TN / (TN + FP) | Of all real negatives, how many did it leave alone? |
| F1 score | 2 · P · R / (P + R) | A balance of precision and recall |
from sklearn.metrics import (confusion_matrix, accuracy_score, precision_score,
recall_score, f1_score)
actual = [0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1]
predicted = [0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1]
tn, fp, fn, tp = confusion_matrix(actual, predicted).ravel()
print("by hand:")
print(" accuracy ", round((tp + tn) / (tp + tn + fp + fn), 3))
print(" precision ", round(tp / (tp + fp), 3))
print(" recall ", round(tp / (tp + fn), 3))
print(" specificity", round(tn / (tn + fp), 3))
print("scikit-learn:")
print(" accuracy ", round(accuracy_score(actual, predicted), 3))
print(" precision ", round(precision_score(actual, predicted), 3))
print(" recall ", round(recall_score(actual, predicted), 3))
print(" f1 ", round(f1_score(actual, predicted), 3))by hand:
accuracy 0.75
precision 0.667
recall 0.8
specificity 0.714
scikit-learn:
accuracy 0.75
precision 0.667
recall 0.8
f1 0.727
scikit-learn has no specificity_score, but specificity is simply the recall of the negative class: recall_score(actual, predicted, pos_label=0).
The classification report
classification_report prints precision, recall and F1 for every class in one table:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.25, random_state=1, stratify=data.target)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test), target_names=data.target_names)) precision recall f1-score support
malignant 0.92 0.92 0.92 53
benign 0.96 0.96 0.96 90
accuracy 0.94 143
macro avg 0.94 0.94 0.94 143
weighted avg 0.94 0.94 0.94 143
The support column is the number of real examples of each class in the test set.
More than two classes
The idea extends naturally: with three classes the matrix is 3×3, and each off-diagonal cell says "this class was mistaken for that one".
from sklearn.metrics import confusion_matrix
labels = ["cat", "dog", "rabbit"]
actual = ["cat", "dog", "dog", "rabbit", "cat", "dog", "rabbit", "cat", "dog"]
predicted = ["cat", "dog", "cat", "rabbit", "cat", "dog", "dog", "dog", "dog"]
print(confusion_matrix(actual, predicted, labels=labels))[[2 1 0]
[1 3 0]
[0 1 1]]
Reading row by row: one cat was taken for a dog, one dog for a cat, and one rabbit for a dog.
Go further: Accuracy, Precision, Recall, F1 and the Confusion Matrix computes every metric from these cells, checks them against scikit-learn and shows the accuracy paradox.
Test yourself
In scikit-learn's confusion matrix for a binary problem, what does cm[1, 0] hold?
- True negatives
- False positives
- False negatives
- True positives
A cancer-screening model must miss as few real cases as possible. Which metric should be high?
- Precision
- Recall
- Specificity
- Accuracy only
Precision is defined as…
- TP / (TP + FN)
- TN / (TN + FP)
- TP / (TP + FP)
- (TP + TN) / all