Plotting already calculated Confusion Matrix using Python

Viewed 6931

How can I plot in Python a Confusion Matrix similar do the one shown here for already given values of the Confusion Matrix?

In the code they use the method sklearn.metrics.plot_confusion_matrix which computes the Confusion Matrix based on the ground truth and the predictions.

But in my case, I already have calculated my Confusion Matrix. So for example, my Confusion Matrix is (values in percentages):

[[0.612, 0.388]
 [0.228, 0.772]]
3 Answers

If you check the source for sklearn.metrics.plot_confusion_matrix, you can see how the data is processed to create the plot. Then you can reuse the constructor ConfusionMatrixDisplay and plot your own confusion matrix.

import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay

cm = [0.612, 0.388, 0.228, 0.772] # your confusion matrix
ls = [0, 1] # your y labels
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=ls)
disp.plot(include_values=include_values, cmap=cmap, ax=ax, xticks_rotation=xticks_rotation)
plt.show()

I saw that someone already answered this question, but I'm adding a new one that can be useful for the author or even for other users.

It is possible to plot in Python an already Confusion Matrix computed through mlxtend package:

Mlxtend (machine learning extensions) is a Python library of useful tools for the day-to-day data science tasks.

Snippet code:

# Imports
from mlxtend.plotting import plot_confusion_matrix
import matplotlib.pyplot as plt
import numpy as np

# Your Confusion Matrix
cm = np.array([[0.612, 0.388],
               [0.228, 0.772]])

# Classes
classes = ['class A', 'class B']

figure, ax = plot_confusion_matrix(conf_mat = cm,
                                   class_names = classes,
                                   show_absolute = False,
                                   show_normed = True,
                                   colorbar = True)

plt.show()

The output will be:

enter image description here

I use a heatmap from seaborn. You can define a method:

import numpy as np
import seaborn as sns; sns.set_theme()
sns.set(font_scale=2)

def plot_matrix(cm, classes, title):
  ax = sns.heatmap(cm, cmap="Blues", annot=True, xticklabels=classes, yticklabels=classes, cbar=False)
  ax.set(title=title, xlabel="predicted label", ylabel="true label")

and use:

cm = np.array([[0.612, 0.388], [0.228, 0.772]])
classes = ['class A', 'class B']
title = "title example"

plot_matrix(cm, classes, title)

the output is like this: enter image description here

Related