how can I save a scikit-learn confusion matrix as png

Viewed 432

How can I save a confusion matrix as png? I've saw this answer:

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

from sklearn.metrics import plot_confusion_matrix

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

IC = type('IdentityClassifier', (), {"predict": lambda i : i, "_estimator_type": "classifier"})

cm = plot_confusion_matrix(IC, y_pred, y_true, normalize='true',  values_format='.2%')
    
cm.figure_.savefig('confusion_matrix.png')

The result that I'm getting is just a black png image.

1 Answers

I think, you should update sklearn to the latest version and then use:

from sklearn.metrics import ConfusionMatrixDisplay


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

IC = type('IdentityClassifier', (), {"predict": lambda i : i, "_estimator_type": "classifier"})

cm=ConfusionMatrixDisplay.from_estimator(IC, y_pred, y_true, normalize='true',  values_format='.2%')

cm.figure_.savefig('confusion_matrix.png')
Related