python get confusion matrix code example
Example 1: confusion matrix python
By definition, entry i,j in a confusion matrix is the number of
observations actually in group i, but predicted to be in group j.
Scikit-Learn provides a confusion_matrix function:
from sklearn.metrics import confusion_matrix
y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
confusion_matrix(y_actu, y_pred)
Example 2: how to find the labels of the confusion matrix in python
""" In order to find the labels just use the Counter function to count
the records from y_test and then check row-wise sum of the confusion
matrix. Then apply the labels to the corresponding rows using the
inbuilt seaborn plot as shown below"""
from collections import Counter
Counter(y_test).keys()
Counter(y_test).values()
import seaborn as sns
import matplotlib.pyplot as plt
ax= plt.subplot()
sns.heatmap(cm, annot=True, fmt='g', ax=ax);
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);