×

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for binary classification.

If you've already fitted a logistic regression model, you may use the confusion matrix function in sklearn to automatically generate the matrix.

The following code generates a confusion matrix by fitting a Logistic Regression Model to the data. Predictors' data is in data frame X, whereas the target category's data is in data frame y.

SYNTAX

from sklearn.linear_model import LogisticRegression

from sklearn.metrics import confusion_matrix

#Fit the model

logreg = LogisticRegression(C=1e5)

logreg.fig(X,y)

#Generate predictions with the model using our X values

y_pred = logreg.predict(X)

#Get the confusion matrix

cf_matrix = confusion_matrix(y, y_pred)

print(cf_matrix)

OUTPUT

array([[23,  5],

       [ 3, 30]])

The results are accurate, but the presentation is a disgrace. Fortunately, we have access to a heatmap from the Seaborn library that makes it look good.

SYNTAX

import seaborn as sns

sns.heatmap(cf_matrix, annot=True)

OUTPUT

Confusion Matrix Visualization Python

See the pie chart to see what percentage of your data is in each of the four corners.

This is how it's done:

SYNTAX

sns.heatmap(cf_matrix/np.sum(cf_matrix), annot=True,

            fmt='.2%', cmap='Blues')

OUTPUT

Confusion Matrix Visualization Python

Likewise, this is rather cool. I even used the cmap property to alter the colour to something more pleasing to the eye... What if I want to view both the count and the percentage at the same time? Is there a way for me to view a label as well? Fortunately, the seaborn heatmap's annotation field can accept text labels.

Making a heatmap with labels:

SYNTAX

labels = [‘True Neg’,’False Pos’,’False Neg’,’True Pos’]

labels = np.asarray(labels).reshape(2,2)

sns.heatmap(cf_matrix, annot=labels, fmt=‘’, cmap='Blues')

OUTPUT

Confusion Matrix Visualization Python

This is very neat. The fmt field was included to prevent formatting from being applied to the manual label. … However, as a result of using this visualisation, I've been stripped of all the relevant details.

With the annotation string's ability to add a new label, I realised I could build custom labels with all the information I wanted.

Strings that include all of the information I need can be created and applied to the heatmap to show it all at once, if that's possible.

SYNTAX

group_names = [‘True Neg’,’False Pos’,’False Neg’,’True Pos’]

group_counts = [“{0:0.0f}”.format(value) for value in

                cf_matrix.flatten()]

group_percentages = [“{0:.2%}”.format(value) for value in

                     cf_matrix.flatten()/np.sum(cf_matrix)]

labels = [f”{v1}\n{v2}\n{v3}” for v1, v2, v3 in

          zip(group_names,group_counts,group_percentages)]

labels = np.asarray(labels).reshape(2,2)

sns.heatmap(cf_matrix, annot=labels, fmt=‘’, cmap='Blues')

OUTPUT

Confusion Matrix Visualization Python

This is amazing, I tell you what! I have a list of names, numbers, and percentages for various groups.

That being the case, what if I combined it all into a single function with visibility choices for each argument, as well as some additional seaborn options like the colormap or displaying a colour bar? What if I included a few summary statistics like Accuracy, Precision, Recall, and F-Score? That would be really convenient. As a result of these considerations, I developed a function that performs the desired action. 

The function expects a 2-D Numpy array as input, which represents a confusion matrix. There are a slew of choices for customising the output. By default, everything is displayed (rather than hidden). The function's documentation includes a docstring that lists all available parameters. To make things easier, I've provided the following docstring:

This function will make a pretty plot of an sklearn Confusion Matrix cm using a Seaborn heatmap visualization.

SYNTAX

Arguments

---------

cf:            confusion matrix to be passed in

group_names:   List of strings that represent the labels row by row

               to be shown in each square.

categories:    List of strings containing the categories to be

               displayed on the x,y axis. Default is 'auto'

count:         If True, show the raw number in the confusion matrix.

               Default is True.

normalize:     If True, show the proportions for each category.

               Default is True.

cbar:          If True, show the color bar. The cbar values are

               based off the values in the confusion matrix.

               Default is True.

xyticks:       If True, show x and y ticks. Default is True.

xyplotlabels:  If True, show 'True Label' and 'Predicted Label' on

               the figure. Default is True.

sum_stats:     If True, display summary statistics below the figure.

               Default is True.

figsize:       Tuple representing the figure size. Default will be

               the matplotlib rcParams value.

cmap:          Colormap of the values displayed from

               matplotlib.pyplot.cm. Default is 'Blues'

Related Topics

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have...

4 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

4 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.