Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

scikit-learn's ConfusionMatrixDisplay() with figsize()

Using figsize() in the following code creates two plots of the confusion matrix, one with the desired size but wrong labels ("Figure 1") and another with the default/wrong size but correct labels ("Figure 2") (image attached below). Second plot is what I want, but with the specified size 8x6in. How do I do this? Thanks!

import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.metrics import ConfusionMatrixDisplay

# import data
iris = datasets.load_iris()
X, y = iris.data, iris.target

# Run classifier
classifier = svm.SVC(kernel="linear")
y_pred = classifier.fit(X, y).predict(X)

# plot confusion matrix
fig, ax = plt.subplots(figsize=(8, 6))
cmp = ConfusionMatrixDisplay.from_predictions(y, y_pred, normalize="true", values_format=".0%")
cmp.plot(ax=ax)
plt.show()

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is not figsize() which is generating two plots rather you are calling ConfusionMatrixDisplay.from_predictions() twice which is generating the two plots. The ConfusionMatrixDisplay itself returns a visualization plot so you don’t need to call cmp.plot() again.

Replace the following code:

# plot confusion matrix
fig, ax = plt.subplots(figsize=(8, 6))
cmp = ConfusionMatrixDisplay.from_predictions(y, y_pred, normalize="true", values_format=".0%")
cmp.plot(ax=ax)
plt.show()

with this:

# plot confusion matrix
fig, ax = plt.subplots(figsize=(8, 6))
cmp = ConfusionMatrixDisplay.from_predictions(y, y_pred, normalize="true", values_format=".0%", ax = ax)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading