Multiclass confusion matrix in python

Question:

I’m trying to create a single multiclass confusion matrix in Python.

df_true = pd.DataFrame({
    "y_true": [0,0,1,1,0,2]
})

df_pred = pd.DataFrame({
    "y_pred": [0,1,2,0,1,2]
})

And I want a single confusion matrix that tells me the actual and predict value for each case. Like this:

enter image description here

Asked By: juanmac

||

Answers:

If I understand correctly, you’re asking how to make a confusion matrix plot. This can be done with sklearn.metrics.ConfusionMatrixDisplay using the result from sklearn.metrics.confusion_matrix.

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import pandas as pd

df_true = pd.DataFrame({
    "y_true": [0,0,1,1,0,2]
})

df_pred = pd.DataFrame({
    "y_pred": [0,1,2,0,1,2]
})

cm = confusion_matrix(df_true.y_true, df_pred.y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
                              display_labels=[0,1,2],)
disp.plot(cmap="Blues")

Answered By: jared