DEV Community

Sameer Aftab
Sameer Aftab

Posted on

Introduction to Confusion matrix in Machine Learning

Today we will be talking about confusion matrix

  1. What is a Confusion Matrix
  2. Why we use confusion Matrix
  3. How Confusion Matrix Works

What is a Confusion Matrix

Confusion Matrix is a Performance Measuring Technique.

Why we use confusion Matrix
Confusion matrix is a technique used to measure the Accuracy/Performance of the Classification Model based on the dataset given to the model

How Confusion Matrix Work
The confusion matrix visualizes the accuracy of a classifier by comparing the actual and predicted classes. The binary confusion matrix is composed of squares
Binary classification Confusion Matrix

Code

#Example of a confusion matrix in Python
from sklearn.metrics import confusion_matrix

expected =  [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]
predicted = [1, 0, 0, 1, 0, 0, 1, 1, 1, 0]
results = confusion_matrix(expected, predicted)
print(results)
Enter fullscreen mode Exit fullscreen mode

Code Explanation

from sklearn.metrics import confusion_matrix
Enter fullscreen mode Exit fullscreen mode

This Line is used to import the Sklearn package
in sklearn there are different function we only want matrix functionalities so imported matrix and in matrix class we want to use confusion matrix so we only imported that particular part from from whole sklearn package

expected =  [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

In this Line we declared an array with all the expected values (what we are expecting)

predicted = [1, 0, 0, 1, 0, 0, 1, 1, 1, 0]
Enter fullscreen mode Exit fullscreen mode

In this Line we declared an array with all the Predicted values that our model has predicted

results = confusion_matrix(expected, predicted)
Enter fullscreen mode Exit fullscreen mode

here we are just using a confusion matrix function that is pre-defined in sklearn package

print(results)
Enter fullscreen mode Exit fullscreen mode

It is just a simple print statement used to print results

Top comments (0)