Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconArtificial Intelligencebreadcumb forward arrow iconDemystifying Confusion Matrix in Machine Learning [Astonishing]

Demystifying Confusion Matrix in Machine Learning [Astonishing]

Last updated:
7th Dec, 2020
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
Demystifying Confusion Matrix in Machine Learning [Astonishing]

Machine Learning is an umbrella term under which it accumulates Data processing, deriving meaningful insights from the Data, and Data modeling. After being done with Data modeling, the model needs to be measured for its performance evaluation, and other industry-based parameters and one of the most common metrics is the Confusion Matrix.

Best Machine Learning and AI Courses Online

What is the Confusion Matrix and Why it is used?

It is a performance metric used in classification problems where the output classes maybe two or more and this matrix represents all the combinations of predicted values by a model with actual values associated with that input. It’s called ‘confusion matrix’ because going by the definitions it seems easy, but as we move forward to derive more valuable parameters, confusion arises regarding which parameter is best suited at a particular place.

It is used in places where the classification problem is highly imbalanced and one class dominates over other classes. In such scenarios, you may be surprised to see the accuracy of the model peaking at 99% but in reality, the model is highly biased towards the dominant class. There is very little possibility that you will get predictions for minority classes. Therefore, to test such an imbalanced dataset, we consider the confusion matrix.

Ads of upGrad blog

In-demand Machine Learning Skills

Get Machine Learning Certification from the World’s top Universities. Earn Masters, Executive PGP, or Advanced Certificate Programs to fast-track your career.

Structure of the Confusion Matrix

The size of the matrix is directly proportional to the number of output classes. It is a square matrix where we assume the column headers as actual values and the row headers as model predictions. The values which are true and predicted true by the model are True Positives (TP), correct negative value predictions are True Negatives (TN), values which were negative but predicted as true are False Positives (FP) and positive values predicted as negative are False Negatives (FN). Have a look at this image:

Read: Types of classification algorithm in machine learning

What can we learn from this?

A valid question arises that what we can do with this matrix. There are some important terminologies based on this:

  1. Precision: It is the portion of values that are identified by the model as correct and are relevant to the problem statement solution. We can also quote this as values, which are a portion of the total positive results given by the model and are positive. Therefore, we can give its formula as TP/ (TP + FP).
  2. Recall: It is the portion of values that are correctly identified as positive by the model. It is also termed as True Positive Rate or Sensitivity. Its formula comes out to be TP/ (TP+FN).
  3. F-1 Score: It is the harmonic mean of Precision and Recall. It means that if we were to compare two models, then this metric will suppress the extreme values and consider both False Positives and False Negatives at the same time. It can be quoted as 2*Precision*Recall/ (Precision+Recall).
  4. Accuracy: It is the portion of values that are identified correctly irrespective of whether they are positives or negatives. It means that all True positives and True negatives are included in this. The formula for this is (TP+TN)/ (TP+TN+FP+FN).

Out of all the terms, precision and recall are most widely used. Their tradeoff is a useful measure of the success of a prediction. The desired model is supposed to have high precision and high recall, but this is only in perfectly separable data. In practical use cases, the data is highly unorganized and imbalanced.

How to create code for Confusion Matrix in Python?

The sklearn library provides a variety of functionalities to perform all the machine learning tasks with utmost accuracy and almost everything has been implemented here. Consider the famous Iris dataset with all import statements already done, the code for confusion matrix would be:

iris = datasets.load_iris()

X =

y =

class_names = iris.target_names

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

classifier = svm.SVC(kernel=‘linear’, C=0.01).fit(X_train, y_train)

plot_confusion_matrix(classifier, X_test, y_test,display_labels=class_names,

Note: The matrix returned by this has reversed sides, here on the left we have actual values and on the top, we have predicted values. If you want to avoid confusion, execute this function to get a detailed summary (classification report)  instead of calculating it manually:

print(classification_report(y_true=y_test, y_pred=y_pred, target_names=class_names))

Also Read: Deep Learning Algorithm

Which one to use and where?

This is the most common question that arises while modeling the Data and the solution lies in the problem’s statement domain. Consider these two cases:

  1. Suppose you are predicting whether the person will get a cardiac arrest. In this scenario, you can’t afford any misclassification and all the predictions made should be accurate. With that said, the cost of False Negatives is high, so the person was prone to attack but was predicted as safe. These cases should be avoided. In these situations, we need a model with high recall.
  2. Suppose a search engine provided random results that are all predicted as positive by the model, then there is very little possibility that the user will rely on it. Therefore, in this scenario, we need a model with high precision so that user experience improves, and the website grows in the right direction.


Ads of upGrad blog

The confusion matrix is a great method to evaluate a classification model. It gives the actual insight into how accurately the model has classified the classes based upon the inputs provided and how this class can be misclassified.

If you’re interested to learn more about machine learning, check out IIIT-B & upGrad’s PG Diploma in Machine Learning & AI which is designed for working professionals and offers 450+ hours of rigorous training, 30+ case studies & assignments, IIIT-B Alumni status, 5+ practical hands-on capstone projects & job assistance with top firms.

Popular AI and ML Blogs & Free Courses


Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Popular Machine Learning Course

Explore Free Courses

Suggested Blogs

Data Preprocessing in Machine Learning: 7 Easy Steps To Follow
Summary: In this article, you will learn about data preprocessing in Machine Learning: 7 easy steps to follow. Acquire the dataset Import all the cr
Read More

by Kechit Goyal

29 Oct 2023

Natural Language Processing (NLP) Projects & Topics For Beginners [2023]
What are Natural Language Processing Projects? NLP project ideas advanced encompass various applications and research areas that leverage computation
Read More

by Pavan Vadapalli

04 Oct 2023

15 Interesting MATLAB Project Ideas & Topics For Beginners [2023]
Learning about MATLAB can be tedious. It’s capable of performing many tasks and solving highly complex problems of different domains. If youR
Read More

by Pavan Vadapalli

03 Oct 2023

Top 16 Artificial Intelligence Project Ideas & Topics for Beginners [2023]
Summary: In this article, you will learn the 16 AI project ideas & Topics. Take a glimpse below. Predict Housing Price Enron Investigation Stock
Read More

by Pavan Vadapalli

27 Sep 2023

Top 15 Deep Learning Interview Questions & Answers
Although still evolving, Deep Learning has emerged as a breakthrough technology in the field of Data Science. From Google’s DeepMind to self-dri
Read More

by Prashant Kathuria

21 Sep 2023

Top 8 Exciting AWS Projects & Ideas For Beginners [2023]
AWS Projects & Topics Looking for AWS project ideas? Then you’ve come to the right place because, in this article, we’ve shared multiple AWS proj
Read More

by Pavan Vadapalli

19 Sep 2023

Top 15 IoT Interview Questions & Answers 2023 – For Beginners & Experienced
These days, the minute you indulge in any technology-oriented discussion, interview questions on cloud computing come up in some form or the other. Th
Read More

by Kechit Goyal

15 Sep 2023

45+ Interesting Machine Learning Project Ideas For Beginners [2023]
Summary: In this Article, you will learn Stock Prices Predictor Sports Predictor Develop A Sentiment Analyzer Enhance Healthcare Prepare ML Algorith
Read More

by Jaideep Khare

14 Sep 2023

Why GPUs for Machine Learning? Ultimate Guide
In the realm of modern technology, the convergence of data and algorithms has paved the way for groundbreaking advancements in artificial intelligence
Read More

by Pavan Vadapalli

14 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
footer sticky close icon