# How to Visualize Confusion Matrix using Scikit-Learn

by Hans Updated: Apr 5, 2023

Solution Kit

You will learn how to build a code function that calculates and visualizes a confusion matrix for a classification problem. We'll use the Scikit-Learn library in Python.

A confusion matrix is a table that summarizes the performance of a classification algorithm by showing the number of true positives, true negatives, false positives, and false negatives for each class. This helps users to evaluate the performance of a classification algorithm and understand its strengths and weaknesses.

Here's a preview of the output. Let's get started - follow three easy steps to build your confusion matrix.

## STEP 1 - Copy this code. This will help us generate a confusion matrix

I found this code snippet by searching for "Confusion Matrix Display" in kandi. You can find millions of code snippets to build any function on kandi!

How does this code work?

- The confusion_matrix() function from scikit-learn takes the y_true and y_pred arrays as inputs and calculates a confusion matrix, which shows the number of true positives, true negatives, false positives, and false negatives for each class.

- The ConfusionMatrixDisplay() function from scikit-learn takes the confusion matrix as input and creates a plot of the matrix. The resulting plot displays the confusion matrix as a grid of colored squares, where the color of each square represents the number of data points that fall into that category.

- The plt.show() function displays the plot on the screen. Matplotlib is used to plot the confusion matrix generated by the Scikit-Learn library. The ConfusionMatrixDisplay() function from Scikit-Learn creates a plot of the confusion matrix using Matplotlib.

## STEP 2 - Paste the code in a Python file in an IDE of your choice. Ensure you have the dependent library scikit-learn installed in your environment (LINK below)

Paste the code in your IDE. Here we are using vscode. You can add this to your favorite IDE.

IMPORTANT: You need scikit-learn installed. If you do not have this you can install using the link below.

scikit-learnby scikit-learn

Python 54584 Version:1.2.2

scikit-learn: machine learning in Python

Support
Quality
Security
Reuse

scikit-learnby scikit-learn

Python 54584 Version:1.2.2 License: Permissive (BSD-3-Clause)

scikit-learn: machine learning in Python
Support
Quality
Security
Reuse

You can search for millions of open source library on kandi. Try searching Scikit-learn.

## STEP 3 - Run the code in your IDE to view the confusion matrix

That's it. You should see the confusion matrix below.

Congrats! You can use this to evaluate the performance of a classification algorithm and understand its strengths and weaknesses.

# Need Help?

Need help? Use this chat to connect with experts to guide you. For further learning resources, visit the Open Weaver Community learning page.

See similar Kits and Libraries