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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With