Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot Confusion Matrix with scikit-learn without a Classifier

I have a confusion matrix created with sklearn.metrics.confusion_matrix.

Now, I would like to plot it with sklearn.metrics.plot_confusion_matrix, but the first parameter is the trained classifier, as specified in the documentation. The problem is that I don't have a classifier; the results were obtained doing manual calculations.

Is it still possible to plot the confusion matrix in one line via scikit-learn, or do I have to code it myself with matplotlib?

like image 265
Irina Avatar asked Dec 03 '19 20:12

Irina


People also ask

How do you visualize the Sklearn confusion matrix?

Plot the confusion matrix given an estimator, the data, and the label. Plot the confusion matrix given the true and predicted labels. Plot Confusion Matrix given an estimator and some data. Plot Confusion Matrix given true and predicted labels.

How do you make a confusion matrix without Sklearn?

You can derive the confusion matrix by counting the number of instances in each combination of actual and predicted classes as follows: import numpy as np def comp_confmat(actual, predicted): # extract the different classes classes = np. unique(actual) # initialize the confusion matrix confmat = np.

How do you make a confusion matrix in Sklearn?

In order to create the confusion matrix we need to import metrics from the sklearn module. Once metrics is imported we can use the confusion matrix function on our actual and predicted values. To create a more interpretable visual display we need to convert the table into a confusion matrix display.


1 Answers

The fact that you can import plot_confusion_matrix directly suggests that you have the latest version of scikit-learn (0.22) installed. So you can just look at the source code of plot_confusion_matrix() to see how its using the estimator.

From the latest sources here, the estimator is used for:

  1. computing confusion matrix using confusion_matrix
  2. getting the labels (unique values of y which correspond to 0,1,2.. in the confusion matrix)

So if you have those two things already, you just need the below part:

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

disp = ConfusionMatrixDisplay(confusion_matrix=cm,
                              display_labels=display_labels)


# NOTE: Fill all variables here with default values of the plot_confusion_matrix
disp = disp.plot(include_values=include_values,
                 cmap=cmap, ax=ax, xticks_rotation=xticks_rotation)

plt.show()

Do look at the NOTE in comment.

For older versions, you can look at how the matplotlib part is coded here

like image 141
Vivek Kumar Avatar answered Oct 04 '22 03:10

Vivek Kumar