The Wayback Machine - https://web.archive.org/web/20241126230252/https://www.geeksforgeeks.org/confusion-matrix-machine-learning/
Open In App

Understanding the Confusion Matrix in Machine Learning

Last Updated : 08 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Machine learning models are increasingly used in various applications to classify data into different categories. However, evaluating the performance of these models is crucial to ensure their accuracy and reliability. One essential tool in this evaluation process is the confusion matrix. In this article, we will delve into the details of the confusion matrix, its significance in machine learning, and how it can be used to improve the performance of classification models.

What is a Confusion Matrix?

A confusion matrix is a matrix that summarizes the performance of a machine learning model on a set of test data. It is a means of displaying the number of accurate and inaccurate instances based on the model’s predictions. It is often used to measure the performance of classification models, which aim to predict a categorical label for each input instance.

The matrix displays the number of instances produced by the model on the test data.

  • True Positive (TP): The model correctly predicted a positive outcome (the actual outcome was positive).
  • True Negative (TN): The model correctly predicted a negative outcome (the actual outcome was negative).
  • False Positive (FP): The model incorrectly predicted a positive outcome (the actual outcome was negative). Also known as a Type I error.
  • False Negative (FN): The model incorrectly predicted a negative outcome (the actual outcome was positive). Also known as a Type II error.

Why do we need a Confusion Matrix?

When assessing a classification model’s performance, a confusion matrix is essential. It offers a thorough analysis of true positive, true negative, false positive, and false negative predictions, facilitating a more profound comprehension of a model’s recall, accuracy, precision, and overall effectiveness in class distinction. When there is an uneven class distribution in a dataset, this matrix is especially helpful in evaluating a model’s performance beyond basic accuracy metrics.

Metrics based on Confusion Matrix Data

1. Accuracy

Accuracy is used to measure the performance of the model. It is the ratio of Total correct instances to the total instances. 

[Tex]Accuracy = \frac {TP+TN}{TP+TN+FP+FN} [/Tex]

For the above case:

Accuracy = (5+3)/(5+3+1+1) = 8/10 = 0.8

2. Precision

Precision is a measure of how accurate a model’s positive predictions are. It is defined as the ratio of true positive predictions to the total number of positive predictions made by the model.

[Tex]\text{Precision} = \frac{TP}{TP+FP} [/Tex]

For the above case:

Precision = 5/(5+1) =5/6 = 0.8333

3. Recall

Recall measures the effectiveness of a classification model in identifying all relevant instances from a dataset. It is the ratio of the number of true positive (TP) instances to the sum of true positive and false negative (FN) instances.

[Tex]\text{Recall} = \frac{TP}{TP+FN} [/Tex]

 For the above case:

Recall = 5/(5+1) =5/6 = 0.8333

Note: We use precision when we want to minimize false positives, crucial in scenarios like spam email detection where misclassifying a non-spam message as spam is costly. And we use recall when minimizing false negatives is essential, as in medical diagnoses, where identifying all actual positive cases is critical, even if it results in some false positives.

4. F1-Score

F1-score is used to evaluate the overall performance of a classification model. It is the harmonic mean of precision and recall,

[Tex]\text{F1-Score} = \frac {2 \cdot Precision \cdot Recall}{Precision + Recall} [/Tex]

For the above case:

F1-Score: = (2* 0.8333* 0.8333)/( 0.8333+ 0.8333)  = 0.8333

We balance precision and recall with the F1-score when a trade-off between minimizing false positives and false negatives is necessary, such as in information retrieval systems.

5. Specificity

Specificity is another important metric in the evaluation of classification models, particularly in binary classification. It measures the ability of a model to correctly identify negative instances. Specificity is also known as the True Negative Rate. Formula is given by:

[Tex]\text{Specificity} = \frac{TN}{TN+FP} [/Tex]

For example,

Specificity=3/(1+3)​=3/4=0.75

6. Type 1 and Type 2 error

1. Type 1 error

Type 1 error occurs when the model predicts a positive instance, but it is actually negative. Precision is affected by false positives, as it is the ratio of true positives to the sum of true positives and false positives.

[Tex]\text{Type 1 Error} = \frac{FP}{TN+FP} [/Tex]

For example, in a courtroom scenario, a Type 1 Error, often referred to as a false positive, occurs when the court mistakenly convicts an individual as guilty when, in truth, they are innocent of the alleged crime. This grave error can have profound consequences, leading to the wrongful punishment of an innocent person who did not commit the offense in question. Preventing Type 1 Errors in legal proceedings is paramount to ensuring that justice is accurately served and innocent individuals are protected from unwarranted harm and punishment.

2. Type 2 error

Type 2 error occurs when the model fails to predict a positive instance. Recall is directly affected by false negatives, as it is the ratio of true positives to the sum of true positives and false negatives.

In the context of medical testing, a Type 2 Error, often known as a false negative, occurs when a diagnostic test fails to detect the presence of a disease in a patient who genuinely has it. The consequences of such an error are significant, as it may result in a delayed diagnosis and subsequent treatment.

[Tex]\text{Type 2 Error} = \frac{FN}{TP+FN} [/Tex]

Precision emphasizes minimizing false positives, while recall focuses on minimizing false negatives.

Confusion Matrix For binary classification

A 2X2 Confusion matrix is shown below for the image recognition having a Dog image or Not Dog image.

Predicted DogPredicted Not Dog
Actual DogTrue Positive (TP)False Negative (FN)
Actual Not DogFalse Positive (FP)True Negative (TN)
  • True Positive (TP): It is the total counts having both predicted and actual values are Dog.
  • True Negative (TN): It is the total counts having both predicted and actual values are Not Dog.
  • False Positive (FP): It is the total counts having prediction is Dog while actually Not Dog.
  • False Negative (FN): It is the total counts having prediction is Not Dog while actually, it is Dog.

Example: Confusion Matrix for Dog Image Recognition with Numbers

Index

1

2

3

4

5

6

7

8

9

10

Actual

Dog

Dog

Dog

Not Dog

Dog

Not Dog

Dog

Dog

Not Dog

Not Dog

Predicted

Dog

Not Dog

Dog

Not Dog

Dog

Dog

Dog

Dog

Not Dog

Not Dog

Result

TP

FN

TP

TN

TP

FP

TP

TP

TN

TN

  • Actual Dog Counts = 6 
  • Actual Not Dog Counts = 4
  • True Positive Counts = 5
  • False Positive Counts = 1
  • True Negative Counts = 3
  • False Negative Counts = 1

 

Predicted

Dog

Not Dog


Actual

Dog

True Positive
(TP =5)

False Negative
(FN =1)

Not Dog

False Positive
(FP=1)

True Negative
(TN=3)

Implementation of Confusion Matrix for Binary classification using Python

Step 1: Import the necessary libraries

Python
import numpy as np
from sklearn.metrics import confusion_matrix,classification_report
import seaborn as sns
import matplotlib.pyplot as plt 

Step 2: Create the NumPy array for actual and predicted labels

Python
actual    = np.array(
  ['Dog','Dog','Dog','Not Dog','Dog','Not Dog','Dog','Dog','Not Dog','Not Dog'])
predicted = np.array(
  ['Dog','Not Dog','Dog','Not Dog','Dog','Dog','Dog','Dog','Not Dog','Not Dog'])

Step 3: Compute the confusion matrix

Python
cm = confusion_matrix(actual,predicted)

Step 4: Plot the confusion matrix with the help of the seaborn heatmap

Python
sns.heatmap(cm, 
            annot=True,
            fmt='g', 
            xticklabels=['Dog','Not Dog'],
            yticklabels=['Dog','Not Dog'])
plt.ylabel('Actual', fontsize=13)
plt.title('Confusion Matrix', fontsize=17, pad=20)
plt.gca().xaxis.set_label_position('top') 
plt.xlabel('Prediction', fontsize=13)
plt.gca().xaxis.tick_top()

plt.gca().figure.subplots_adjust(bottom=0.2)
plt.gca().figure.text(0.5, 0.05, 'Prediction', ha='center', fontsize=13)
plt.show()

Output:

confusion-Matrix

Visualizing the Confusion Matrix

Step 5: Classifications Report based on Confusion Metrics

Python
print(classification_report(actual, predicted))

Output:

precision recall f1-score support Dog 0.83 0.83 0.83 6 Not Dog 0.75 0.75 0.75 4 accuracy 0.80 10 macro avg 0.79 0.79 0.79 10 weighted avg 0.80 0.80 0.80 10

Confusion Matrix For Multi-class Classification

In multi-class classification, you have more than two possible classes for your model to predict. The confusion matrix expands to accommodate these additional classes.

  • Rows: Represent the actual classes (ground truth) in your dataset.
  • Columns: Represent the predicted classes by your model.

Each cell within the matrix shows the count of instances where the model predicted a particular class (column) when the actual class was another (row).

Now, let’s consider there are three classes. A 3X3 Confusion matrix is shown below for the image having three classes.

Example: Confusion Matrix for Image Classification (Cat, Dog, Horse)

Predicted CatPredicted DogPredicted Horse
Actual CatTrue Positive (TP)False Negative (FN)False Negative (FN)
Actual DogFalse Negative (FN)True Positive (TP)False Negative (FN)
Actual HorseFalse Negative (FN)False Negative (FN)True Positive (TP)
  • True Positive (TP): The image was of a particular animal (cat, dog, or horse), and the model correctly predicted that animal. For example, a picture of a cat correctly identified as a cat.
  • True Negative (TN): The image was not of a particular animal and the model correctly predicted it as not that animal. For example, a picture of a car correctly identified as not a cat, not a dog, and not a horse.
  • False Positive (FP): The image was not of a particular animal, but the model incorrectly predicted it as that animal. For example, a picture of a horse mistakenly identified as a dog.
  • False Negative (FN): The image was of a particular animal, but the model incorrectly predicted it as a different animal. For example, a picture of a dog mistakenly identified as a cat.

Example with Numbers:

Let’s consider the scenario where the model processed 30 images:

Predicted CatPredicted DogPredicted Horse
Actual Cat811
Actual Dog2100
Actual Horse028

In this scenario:

  • Cats: 8 were correctly identified, 1 was misidentified as a dog, and 1 was misidentified as a horse.
  • Dogs: 10 were correctly identified, 2 were misidentified as cats.
  • Horses: 8 were correctly identified, 2 were misidentified as dogs.

To calculate true negatives, we need to know the total number of images that were NOT cats, dogs, or horses. Let’s assume there were 10 such images, and the model correctly classified all of them as “not cat,” “not dog,” and “not horse.”

Therefore:

  • True Negative (TN) Counts: 10 (for each class, as the model correctly identified each non-cat/dog/horse image as not belonging to that class)

Implementation of Confusion Matrix for Multi-Class classification using Python

Step 1: Import the necessary libraries

Python
import numpy as np
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, classification_report
import matplotlib.pyplot as plt

Step 2: Create the NumPy array for actual and predicted labels

Python
# Actual labels
y_true = ['Cat'] * 10 + ['Dog'] * 12 + ['Horse'] * 10

# Predicted labels 
y_pred = ['Cat'] * 8 + ['Dog'] + ['Horse'] + ['Cat'] * 2 + ['Dog'] * 10 + ['Horse'] * 8 + ['Dog'] * 2

# Classes
classes = ['Cat', 'Dog', 'Horse']

Step 3: Generate and Visualize the Confusion Matrix

Python
# Generate the confusion matrix
cm = confusion_matrix(y_true, y_pred, labels=classes)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=classes)
disp.plot(cmap=plt.cm.Blues)
plt.title('Confusion Matrix', fontsize=15, pad=20)
plt.xlabel('Prediction', fontsize=11)
plt.ylabel('Actual', fontsize=11)
#Customizations
plt.gca().xaxis.set_label_position('top')
plt.gca().xaxis.tick_top()
plt.gca().figure.subplots_adjust(bottom=0.2)
plt.gca().figure.text(0.5, 0.05, 'Prediction', ha='center', fontsize=13)

plt.show()

Output:

confusion-Matrix

Display the confusion matrix

Step 4: Print the Classification Report

Python
# Print classification report
print(classification_report(y_true, y_pred, target_names=classes))

Output:

precision recall f1-score support Cat 0.80 0.80 0.80 10 Dog 0.77 0.83 0.80 12 Horse 0.89 0.80 0.84 10 accuracy 0.81 32 macro avg 0.82 0.81 0.81 32 weighted avg 0.82 0.81 0.81 32

Conclusion

To sum up, the confusion matrix is an essential instrument for evaluating the effectiveness of classification models. Insights into a model’s accuracy, precision, recall, and general efficacy in classifying instances are provided by the thorough analysis of true positive, true negative, false positive, and false negative predictions it offers. The article provided examples to illustrate each metric’s computation and discussed its importance. It also demonstrated how confusion matrices can be implemented in Python for binary and multi-class classification scenarios. Practitioners can make well-informed decisions regarding model performance—particularly when dealing with imbalanced class distributions—by comprehending and applying these metrics.

FAQs on Confusion Matrix

How to interpret a confusion matrix?

A confusion matrix summarizes a classification model’s performance, with entries representing true positive, true negative, false positive, and false negative instances, providing insights into model accuracy and errors.

What are the advantages of using Confusion matrix?

The confusion matrix provides a comprehensive evaluation of a classification model’s performance, offering insights into true positives, true negatives, false positives, and false negatives, aiding nuanced analysis beyond basic accuracy.

What are some examples of confusion matrix applications?

Confusion matrices find applications in various fields, including medical diagnosis (identifying true/false positives/negatives for diseases), fraud detection, sentiment analysis, and image recognition accuracy assessment.

What is the confusion matrix diagram?

A confusion matrix diagram visually represents the performance of a classification model. It displays true positive, true negative, false positive, and false negative values in a structured matrix format.

What are the three values of the confusion matrix?

The three values of the confusion matrix are true positive (correctly predicted positive instances), true negative (correctly predicted negative instances), and false positive (incorrectly predicted positive instances).



Previous Article
Next Article

Similar Reads

Understanding PAC Learning: Theoretical Foundations and Practical Applications in Machine Learning
In the vast landscape of machine learning, understanding how algorithms learn from data is crucial. Probably Approximately Correct (PAC) learning stands as a cornerstone theory, offering insights into the fundamental question of how much data is needed for learning algorithms to reliably generalize to unseen instances. PAC learning provides a theor
8 min read
Getting started with Machine Learning || Machine Learning Roadmap
Machine Learning (ML) represents a branch of artificial intelligence (AI) focused on enabling systems to learn from data, uncover patterns, and autonomously make decisions. In today's era dominated by data, ML is transforming industries ranging from healthcare to finance, offering robust tools for predictive analytics, automation, and informed deci
11 min read
Compute Classification Report and Confusion Matrix in Python
In this article, we are going to see how to compute classification reports and confusion matrices of size 3*3 in Python. Confusion matrix and classification report, two are very commonly used and important library functions available in scikit learn library. But how many of those users can really implement these two functions from the scratch? Ther
7 min read
How to Plot Confusion Matrix with Labels in Sklearn?
Confusion matrices are a crucial tool in evaluating the performance of classification models. They provide a detailed breakdown of the model's predictions, showing the counts of true positives, true negatives, false positives, and false negatives. This article will guide you through the process of plotting a confusion matrix with labels using Sciki
4 min read
How to produce a confusion matrix and find the misclassification rate of the Naive Bayes Classifier in R?
Producing a confusion matrix and calculating the misclassification rate of a Naive Bayes Classifier in R involves a few straightforward steps. In this guide, we'll use a sample dataset to demonstrate how to interpret the results. Understanding Confusion MatrixA confusion matrix is a table that describes the performance of a classification model by
3 min read
Confusion Matrix from rpart
The rpart package allows us to create classification and regression trees, which can be used for a variety of predictive modeling tasks. A crucial step in evaluating the performance of these models is understanding their confusion matrix. This article will walk you through the process of building a classification model using rpart and interpreting
4 min read
Calculating Precision and Recall for Multiclass Classification Using Confusion Matrix
Multiclass classification is a common problem in machine learning where a model is required to predict one of several predefined categories. Evaluating the performance of such models can be complex, especially when dealing with imbalanced datasets. Two essential metrics for evaluating multiclass classification models are precision and recall. In th
6 min read
How to Normalize a Confusion Matrix
A confusion matrix is a fundamental tool in classification problems, providing insight into the performance of a classification model. It displays the true positive, false positive, true negative, and false negative predictions, giving a detailed view of how well the model is performing across different classes. Normalizing a confusion matrix can m
4 min read
How to Dump Confusion Matrix Using TensorBoard Logger in PyTorch Lightning
PyTorch Lightning is a lightweight wrapper for PyTorch that helps you scale your models and write less boilerplate code. TensorBoard, a popular visualization tool, can be integrated with PyTorch Lightning to monitor training processes. One valuable visualization is the confusion matrix, which provides insights into the accuracy of classifications m
5 min read
Understanding Cross Decomposition in Machine Learning
Usually, in real-world datasets, some of the features of the data are highly correlated with each other. Applying normal regression methods to highly correlated data is not an effective way to analyze such data, since multicollinearity makes the estimates highly sensitive to any change in the model. In this article, we will be diving deep into Cros
15 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read
Continual Learning in Machine Learning
As we know Machine Learning (ML) is a subfield of artificial intelligence that specializes in growing algorithms that learn from statistics and make predictions or choices without being explicitly programmed. It has revolutionized many industries by permitting computer systems to understand styles, make tips, and perform tasks that were soon consid
10 min read
Few-shot learning in Machine Learning
What is a Few-shot learning?Few-shot learning is a type of meta-learning process. It is a process in which a model possesses the capability to autonomously acquire knowledge and improve its performance through self-learning. It is a process like teaching the model to recognize things or do tasks, but instead of overwhelming it with a lot of example
8 min read
What Is Meta-Learning in Machine Learning in R
In traditional machine learning, models are typically trained on a specific dataset for a specific task, and their performance is optimized for that particular task. However, in R Programming Language the focus is on building models that can leverage prior knowledge or experience to quickly adapt to new tasks with minimal additional training data.
7 min read
Types of Federated Learning in Machine Learning
Federated Learning is a powerful technique that allow a single machine to learn from many different source and converting the data into small pieces sending them to different Federated Learning (FL) is a decentralized of the machine learning paradigm that can enables to model training across various devices while preserving your data the data priva
5 min read
Machine Learning-based Recommendation Systems for E-learning
In today's digital age, e-learning platforms are transforming education by giving students unprecedented access to a wide range of courses and resources. Machine learning-based recommendation systems have emerged as critical tools for effectively navigating this vast amount of content. The article delves into the role of recommendation systems in e
9 min read
One Shot Learning in Machine Learning
One-shot learning is a machine learning paradigm aiming to recognize objects or patterns from a limited number of training examples, often just a single instance. Traditional machine learning models typically require large amounts of labeled data for high performance. Still, one-shot learning seeks to overcome this limitation by enabling models to
7 min read
Difference Between Artificial Intelligence vs Machine Learning vs Deep Learning
Artificial Intelligence is basically the mechanism to incorporate human intelligence into machines through a set of rules(algorithm). AI is a combination of two words: "Artificial" meaning something made by humans or non-natural things and "Intelligence" meaning the ability to understand or think accordingly. Another definition could be that "AI is
14 min read
Difference Between Machine Learning and Deep Learning
If you are interested in building your career in the IT industry then you must have come across the term Data Science which is a booming field in terms of technologies and job availability as well. In this article, we will explore the Difference between Machine Learning and Deep Learning, two major fields within Data Science. Understanding these di
8 min read
AI vs. Machine Learning vs. Deep Learning vs. Neural Networks
Artificial Intelligence (AI), Machine Learning (ML), Deep Learning (DL), and Neural Networks (NN) are terms often used interchangeably. However, they represent different layers of complexity and specialization in the field of intelligent systems. This article will clarify the Difference between AI vs. machine learning vs. deep learning vs. neural n
6 min read
Matrices and Matrix Arithmetic for Machine Learning
In machine learning, the data often comes in multi-dimensional arrays so matrices are best to handle such inputs. So we need to have some general idea on basic arithmetic operations in matrices. In this article, we will discuss about matrices and matrix arithmetic for machine learning. What is a Matrix?Matrix is a two dimensional array where the da
6 min read
Sparse Matrix in Machine Learning
In the realm of mathematics and computer science a sparse matrix is a matrix in which most of the elements are zero. The Sparse matrices are prevalent in the many applications where the majority of the data entries are zero making them a crucial concept in the optimizing storage and computational efficiency. In this article, we will explore about W
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg