Blog_Banner_Asset
    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
Views
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 = iris.data

y = iris.target

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,cmap=plt.cm.Blues)

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.

Conclusion

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

Profile

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

Artificial Intelligence course fees
5356
Artificial intelligence (AI) was one of the most used words in 2023, which emphasizes how important and widespread this technology has become. If you
Read More

by venkatesh Rajanala

29 Feb 2024

Artificial Intelligence in Banking 2024: Examples & Challenges
6044
Introduction Millennials and their changing preferences have led to a wide-scale disruption of daily processes in many industries and a simultaneous g
Read More

by Pavan Vadapalli

27 Feb 2024

Top 9 Python Libraries for Machine Learning in 2024
75532
Machine learning is the most algorithm-intense field in computer science. Gone are those days when people had to code all algorithms for machine learn
Read More

by upGrad

19 Feb 2024

Top 15 IoT Interview Questions & Answers 2024 – For Beginners & Experienced
64382
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

19 Feb 2024

Data Preprocessing in Machine Learning: 7 Easy Steps To Follow
152470
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

18 Feb 2024

Artificial Intelligence Salary in India [For Beginners & Experienced] in 2024
908544
Artificial Intelligence (AI) has been one of the hottest buzzwords in the tech sphere for quite some time now. As Data Science is advancing, both AI a
Read More

by upGrad

18 Feb 2024

24 Exciting IoT Project Ideas & Topics For Beginners 2024 [Latest]
758751
Summary: In this article, you will learn the 24 Exciting IoT Project Ideas & Topics. Take a glimpse at the project ideas listed below. Smart Agr
Read More

by Kechit Goyal

18 Feb 2024

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

by Pavan Vadapalli

17 Feb 2024

45+ Interesting Machine Learning Project Ideas For Beginners [2024]
327883
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

16 Feb 2024

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