Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print labels and column names for Confusion Matrix?

I get the confusion matrix but since my actual data set has lot of classification categories, it's difficult to understand.

Example -

>>> from sklearn.metrics import confusion_matrix
>>> y_test
['a', 'a', 'b', 'c', 'd', 'd', 'e', 'a', 'c']
>>> y_pred
['b', 'a', 'b', 'c', 'a', 'd', 'e', 'a', 'c']
>>> 
>>> 
>>> confusion_matrix(y_test, y_pred)
array([[2, 1, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 2, 0, 0],
       [1, 0, 0, 1, 0],
       [0, 0, 0, 0, 1]], dtype=int64)

But how to print the labels/column names for better understanding?

I even tried this -

>>> pd.factorize(y_test)
(array([0, 0, 1, 2, 3, 3, 4, 0, 2], dtype=int64), array(['a', 'b', 'c', 'd', 'e'], dtype=object))
>>> pd.factorize(y_pred)
(array([0, 1, 0, 2, 1, 3, 4, 1, 2], dtype=int64), array(['b', 'a', 'c', 'd', 'e'], dtype=object))

Any help please?

like image 970
ranit.b Avatar asked Jan 02 '23 05:01

ranit.b


1 Answers

Try something like this:

from sklearn.metrics import confusion_matrix
import pandas as pd
import numpy as np
y_test = ['a', 'a', 'b', 'c', 'd', 'd', 'e', 'a', 'c']
y_pred = ['b', 'a', 'b', 'c', 'a', 'd', 'e', 'a', 'c']


labels = np.unique(y_test)
a =  confusion_matrix(y_test, y_pred, labels=labels)

pd.DataFrame(a, index=labels, columns=labels)

Output:

   a  b  c  d  e
a  2  1  0  0  0
b  0  1  0  0  0
c  0  0  2  0  0
d  1  0  0  1  0
e  0  0  0  0  1
like image 111
Scott Boston Avatar answered Jan 03 '23 19:01

Scott Boston