-1

I wish to add on text to each cell of a confusion matrix object from scikit-learn. More specifically, I wish to put True Positive in the top left cell, False Positive in the top right cell etc. Is there a easy to way to do so, or do I have to use annotate and specify the coordinates?

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.tight_layout

cm_benign = metrics.ConfusionMatrixDisplay.from_predictions(
    y_true, y_pred, ax=ax1, labels=["benign", "malignant"], colorbar=False
)
ax1.set_title("Confusion Matrix (Benign as +)")
cm_malignant = metrics.ConfusionMatrixDisplay.from_predictions(
    y_true, y_pred, ax=ax2, labels=["malignant", "benign"], colorbar=False
)
ax2.set_title("Confusion Matrix (Malignant as +)")
fig.subplots_adjust(wspace=0.8)
plt.show();
ilovewt
  • 911
  • 2
  • 10
  • 18

1 Answers1

0

You can use seaborn to put the labels on your figure. You may also be able to use the display_labels parameter along with labels as you currently have, I'm not sure if it'll work as well since the list of labels wouldn't be the same, even for the same confusion matrix.

import seaborn as sns
from sklearn.metrics import confusion_matrix

x_labels = ["False Positive", "False Negative"]
y_labels = ["True Positive", "True Negative"]
cm = confusion_matrix(x, y)
heatmap = sns.heatmap(cm, annot=True, fmt='d', xticklabels=x_labels, yticklabels=y_labels)
figure = heatmap.get_figure()
# show or save figure
plt.close(cm)
Djinn
  • 663
  • 5
  • 12