Confusion Matrix in Machine Learning
A confusion matrix is a table for understanding the mistakes made by a classification model. Instead of only asking "How many predictions were correct?", it asks a more useful question: "Which classes were confused with which other classes?"
Confusion Matrix in Simple Words
Actual answer
Model prediction
Compare them
Count each type of result
For a binary problem, every prediction ends up in one of four boxes: TP, TN, FP, or FN.
Confusion matrices are useful in problems such as spam filtering, fraud screening, defect detection, credit-risk classification, security alerts, and medical research because different kinds of mistakes can have very different consequences.
Why the Name "Confusion Matrix"?
Off-diagonal cells show cases where one class was predicted as another. For example, a spam email predicted as legitimate is one kind of confusion, while a legitimate email predicted as spam is a different kind of confusion.
What Is a Confusion Matrix?
A confusion matrix compares actual labels with predicted labels. In a binary classification problem, the four cells are True Positive, False Positive, False Negative, and True Negative.
Binary Classification Confusion Matrix
Suppose Positive is the class we especially want to detect, such as "Fraud" or "Spam". A common teaching layout is:
| Predicted Positive | Predicted Negative | |
|---|---|---|
| Actual Positive | True Positive (TP) | False Negative (FN) |
| Actual Negative | False Positive (FP) | True Negative (TN) |
Important: check the axis and label order.
Different books and tools may display axes in different orientations. In scikit-learn, confusion_matrix(y_true, y_pred) uses rows for true classes and columns for predicted classes.
For binary labels ordered as [0, 1], the matrix is commonly read as [[TN, FP], [FN, TP]].
One Consistent Example for the Whole Lesson
Imagine 100 cases. There are 40 actual positives and 60 actual negatives. The model produces:
TP = 35
35 positives found correctly
FN = 5
5 positives missed
FP = 10
10 false alarms
TN = 50
50 negatives rejected correctly
Understanding Each Component
1. True Positive (TP)
The model predicts Positive and the actual class is also Positive.
Example: TP = 35 of the 40 actual positive cases.
2. True Negative (TN)
The model predicts Negative and the actual class is also Negative.
Example: TN = 50 of the 60 actual negative cases.
3. False Positive (FP)
The model predicts Positive, but the actual class is Negative. This is a false alarm.
Example: FP = 10.
False positives are often associated with a Type-I error in binary hypothesis-testing language, although the terminology depends on how the problem and hypotheses are defined.
4. False Negative (FN)
The model predicts Negative, but the actual class is Positive. The positive case was missed.
Example: FN = 5.
Whether an FP or FN is more costly depends on the application. In some screening tasks missing a positive can be especially costly; in other tasks false alarms may be the bigger problem.
Metrics Derived from the Same Matrix
We will use the same values throughout: TP = 35, TN = 50, FP = 10, FN = 5.
1. Accuracy — How many predictions were correct overall?
Accuracy = (TP + TN) / (TP + TN + FP + FN)
= (35 + 50) / 100
= 85 / 100
= 0.85 = 85%
Why accuracy can hide an important failure
If 990 of 1000 transactions are legitimate, a model that predicts "legitimate" for every transaction gets 99% accuracy while detecting none of the 10 fraud cases. Accuracy can still be useful, but it should be interpreted together with class balance, error costs, and other metrics.
2. Precision — When the model says Positive, how often is it right?
Precision = TP / (TP + FP)
= 35 / (35 + 10)
= 35 / 45
≈ 0.778 = 77.8%
3. Recall (Sensitivity) — How many real positives did we find?
Recall = TP / (TP + FN)
= 35 / (35 + 5)
= 35 / 40
= 0.875 = 87.5%
Precision vs Recall: Thresholds Often Create a Trade-Off
For a classifier that produces a score or probability, changing the decision threshold changes which cases are predicted positive.
This is a common pattern, not a rule that precision and recall must move in opposite directions after every model improvement.
4. Specificity — How many real negatives did we identify?
Specificity = TN / (TN + FP)
= 50 / (50 + 10)
= 50 / 60
≈ 0.833 = 83.3%
5. F1 Score — One number combining Precision and Recall
F1 = 2 × (Precision × Recall) / (Precision + Recall)
= 2 × (0.778 × 0.875) / (0.778 + 0.875)
≈ 0.824 = 82.4%
F1 is the harmonic mean of precision and recall. It can be useful when both false positives and false negatives matter, but it does not include true negatives directly and is not automatically the best metric for every imbalanced problem.
| Metric | Question it answers | Example result |
|---|---|---|
| Accuracy | How many predictions were correct overall? | 85.0% |
| Precision | How trustworthy are positive predictions? | 77.8% |
| Recall | How many actual positives were found? | 87.5% |
| Specificity | How many actual negatives were found? | 83.3% |
| F1 | How strong is the precision/recall balance? | 82.4% |
Multiclass Confusion Matrix
Confusion matrices are not limited to two classes. If a classifier predicts Cat, Dog, or Horse, the matrix can have three rows and three columns.
| Actual ↓ / Predicted → | Cat | Dog | Horse |
|---|---|---|---|
| Cat | 8 | 1 | 1 |
| Dog | 2 | 7 | 1 |
| Horse | 0 | 1 | 9 |
The diagonal cells are correct predictions. Off-diagonal cells tell us which classes are being confused. For multiclass precision/recall/F1, each class can be evaluated against the others using a one-vs-rest view and then summarized using averages.
Macro average
Compute a metric for each class and take an unweighted average. Each class contributes equally.
Weighted average
Average class-wise metrics while weighting each class by its support (number of true examples).
Counts vs Normalized Confusion Matrices
Raw counts answer questions such as "How many cases were missed?" A normalized matrix can answer questions such as "What fraction of each true class was predicted as each class?"
Raw: [[50, 10], [5, 35]]
Row-normalized: useful for comparing error proportions when class sizes differ.
Python Implementation
Scikit-learn can calculate the matrix, unpack TN/FP/FN/TP for a binary problem, create a display, and generate precision/recall/F1 summaries.
Confusion Matrix + Classification Report
Pythonimport numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import (
confusion_matrix,
classification_report,
ConfusionMatrixDisplay,
)
# 1 = Dog (positive class), 0 = Not Dog (negative class)
y_true = np.array([1, 1, 1, 0, 1, 0, 1, 1, 0, 0])
y_pred = np.array([1, 0, 1, 0, 1, 1, 1, 1, 0, 0])
# Rows = true labels, columns = predicted labels
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
tn, fp, fn, tp = cm.ravel()
print("Confusion matrix:")
print(cm)
print(f"TN={tn}, FP={fp}, FN={fn}, TP={tp}")
print("\nClassification report:")
print(
classification_report(
y_true,
y_pred,
labels=[0, 1],
target_names=["Not Dog", "Dog"],
digits=2,
)
)
# Current scikit-learn display API
ConfusionMatrixDisplay.from_predictions(
y_true,
y_pred,
labels=[0, 1],
display_labels=["Not Dog", "Dog"],
cmap="Blues",
values_format="d",
)
plt.title("Confusion Matrix")
plt.show()Verified output:
Confusion matrix:
[[3 1]
[1 5]]
TN=3, FP=1, FN=1, TP=5
Classification report:
precision recall f1-score support
Not Dog 0.75 0.75 0.75 4
Dog 0.83 0.83 0.83 6
accuracy 0.80 10
macro avg 0.79 0.79 0.79 10
weighted avg 0.80 0.80 0.80 10How to read the heatmap
Large diagonal values mean many correct predictions. Large off-diagonal values identify particular class confusions that deserve investigation. A dark diagonal is encouraging, but always inspect the counts, class sizes, and error costs rather than judging only by color intensity.
Common Mistakes
Mixing up FP and FN
Write actual labels on one axis and predicted labels on the other before interpreting the cells.
Assuming Positive means "good"
Positive simply means the class designated as positive for the analysis. Fraud or disease can be the positive class.
Trusting accuracy alone
Check class balance and the consequences of FP and FN.
Calling every FN more dangerous than every FP
The relative cost is domain-specific.
Ignoring decision thresholds
For score-based classifiers, changing the threshold changes the confusion matrix.
Reading multiclass averages without class-wise scores
Macro and weighted averages can hide very different performance for individual classes.
Quick Recap
A real positive is predicted negative. Which cell?
False Negative (FN).
Which metric asks, "Of all actual positives, how many were found?"
Recall (Sensitivity).
Why can two classifiers with the same accuracy behave very differently?
They can make different numbers or types of false-positive and false-negative errors.
Final Summary
A confusion matrix turns a single classification score into an error breakdown. It shows not only how often the model was correct, but how it was wrong. From its cells we can derive accuracy, precision, recall, specificity, F1, and other useful measures.
The best metric depends on the problem. Always define the positive class, verify the matrix orientation, understand the cost of false positives and false negatives, and keep class imbalance in mind.
Most Important Insight to Remember
Do not ask only "What is the accuracy?" Ask "Which mistakes is the model making, and which mistakes matter most for this application?"
Continue learning