Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot_confusion_matrix without estimator

I'm trying to use plot_confusion_matrix,

from sklearn.metrics import confusion_matrix

y_true = [1, 1, 0, 1]
y_pred = [1, 1, 0, 0]

confusion_matrix(y_true, y_pred)

Output:

array([[1, 0],
       [1, 2]])

Now, while using the followings; using 'classes' or without 'classes'

from sklearn.metrics import plot_confusion_matrix

plot_confusion_matrix(y_true, y_pred, classes=[0,1], title='Confusion matrix, without normalization')

or

plot_confusion_matrix(y_true, y_pred, title='Confusion matrix, without normalization')

I expect to get similar output like this except the numbers inside,

enter image description here

Plotting simple diagram, it should not require the estimator.

Using mlxtend.plotting,

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

binary1 = np.array([[4, 1],
                   [1, 2]])

fig, ax = plot_confusion_matrix(conf_mat=binary1)
plt.show()

It provides same output.

Based on this

it requires a classifier,

disp = plot_confusion_matrix(classifier, X_test, y_test,
                                 display_labels=class_names,
                                 cmap=plt.cm.Blues,
                                 normalize=normalize)

Can I plot it without a classifier?

like image 292
Rakibul Hassan Avatar asked Mar 20 '20 15:03

Rakibul Hassan


1 Answers

plot_confusion_matrix expects a trained classifier. If you look at the source code, what it does is perform the prediction to generate y_pred for you:

y_pred = estimator.predict(X)
    cm = confusion_matrix(y_true, y_pred, sample_weight=sample_weight,
                          labels=labels, normalize=normalize)

So in order to plot the confusion matrix without specifying a classifier, you'll have to go with some other tool, or do it yourself. A simple option is to use seaborn:

import seaborn as sns

cm = confusion_matrix(y_true, y_pred)
f = sns.heatmap(cm, annot=True)

enter image description here

like image 126
yatu Avatar answered Oct 06 '22 20:10

yatu