Skip to main content
LearnMLAcademy
Intermediate10 min read

Confusion Matrix

Interpret confusion matrices, precision, recall, and harmonic F1-scores, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

1

Actual answer

2

Model prediction

3

Compare them

4

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 PositivePredicted Negative
Actual PositiveTrue Positive (TP)False Negative (FN)
Actual NegativeFalse 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.

Higher thresholdUsually fewer positive predictions: this may reduce false positives, but it can also miss more real positives.
Lower thresholdUsually more positive predictions: this may find more real positives, but can also create more false alarms.

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.

MetricQuestion it answersExample result
AccuracyHow many predictions were correct overall?85.0%
PrecisionHow trustworthy are positive predictions?77.8%
RecallHow many actual positives were found?87.5%
SpecificityHow many actual negatives were found?83.3%
F1How 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 →CatDogHorse
Cat811
Dog271
Horse019

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

Python
import 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        10

How 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?"

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Confusion Matrix"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
TP=45, FP=15, FN=5, TN=935. Calculate precision and recall and explain both for a medical context.
Question 2 of 4
A model predicts not-fraud for every transaction on a dataset with 0.3% fraud rate. What does its confusion matrix look like?
Question 3 of 4
Users are complaining that legitimate emails go to spam (false positives). What change do you make and what is the consequence?
Question 4 of 4
What is the Matthews Correlation Coefficient (MCC) and why might it be more informative than F1 for highly imbalanced datasets?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1TP=45, FP=15, FN=5, TN=935. Calculate precision and recall and explain both for a medical context.▼

Correct Answer: Precision=75%: of 60 flagged patients, 75% truly have the disease. Recall=90%: of 50 true cases, 90% were detected. For medical screening, recall (catching 90% of true cases) is the priority — the 10% missed cases are the most dangerous outcome

Precision=45/(45+15)=75%. Recall=45/(45+5)=90%. In disease screening: FN (missing a sick patient) is catastrophic; FP (unnecessary follow-up) is manageable. High recall is the right priority.

2A model predicts not-fraud for every transaction on a dataset with 0.3% fraud rate. What does its confusion matrix look like?▼

Correct Answer: TP=0, FP=0, FN=3000, TN=997000 (assuming 1M transactions). Accuracy=99.7% — looks excellent while the model is completely useless. Recall=0/3000=0%

This confusion matrix exposes what accuracy hides: Recall=0% and F1≈0. A model achieving 99.7% accuracy is completely worthless for its stated purpose — catching fraud.

3Users are complaining that legitimate emails go to spam (false positives). What change do you make and what is the consequence?▼

Correct Answer: Raise the classification threshold above 0.5 — predict spam only when the model is more confident. This reduces FP (fewer legitimate emails flagged) but increases FN (more actual spam gets through). The confusion matrix shifts: FP↓, FN↑, TP↓, TN↑. Precision increases; recall decreases

Threshold adjustment is the most direct lever for controlling the FP-FN tradeoff without retraining. Raising the threshold requires higher model confidence to classify as positive — fewer false positives, but some real spam also escapes.

4What is the Matthews Correlation Coefficient (MCC) and why might it be more informative than F1 for highly imbalanced datasets?▼

Correct Answer: MCC = (TP×TN - FP×FN) / √((TP+FP)(TP+FN)(TN+FP)(TN+FN)) incorporates all four confusion matrix cells. F1 ignores TN entirely. For severely imbalanced datasets, a model can achieve high F1 by predicting nearly all positives while making many false predictions — MCC penalises this because it includes TN. MCC ranges from -1 to +1, with 0 indicating random performance

F1=2TP/(2TP+FP+FN) — ignores TN and can be gamed on imbalanced data. MCC balances all four confusion matrix cells and produces high values only when all four are proportionally large — considered the most informative single metric for binary classification.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next