×

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 Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.