How to save Confusion Matrix plot so that I can call it for future reference?

Viewed 4144

I was using this latest function, sklearn.metrics.plot_confusion_matrix to plot my confusion matrix.

cm = plot_confusion_matrix(classifier,X , y_true,cmap=plt.cm.Greens)

And when I execute that cell, the confusion matrix plot showed up as expected. My problem is I want to use the plot for another cell later. When I called cm in another cell, it only shows the location of that object.

>>> cm
>>> <sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x1af790ac6a0>

Calling plt.show() doesn't work either

2 Answers

For your problem to work as you expect it you should do cm.plot()

Proof

Let's try to do it in a reproducible fashion:

from sklearn.metrics import plot_confusion_matrix
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier

np.random.seed(42)
X, y = make_classification(1000, 10, n_classes=2)
clf = RandomForestClassifier()
clf.fit(X,y)
cm = plot_confusion_matrix(clf, X , y, cmap=plt.cm.Greens)

enter image description here

You can plot your cm object later as:

cm.plot(cmap=plt.cm.Greens);

enter image description here

For your reference. You can access methods available for cm object as:

[method for method in dir(cm) if not method.startswith("__")]
['ax_',
 'confusion_matrix',
 'display_labels',
 'figure_',
 'im_',
 'plot',
 'text_']
cm.figure_.savefig('conf_mat.png',dpi=300)
Related