Example 1: confusion matrix python code
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_predicted)
cm
import seaborn as sn
plt.figure(figsize = (10,7))
sn.heatmap(cm, annot=True)
plt.xlabel('Predicted')
plt.ylabel('Truth')
Example 2: compute confusion matrix using python
import numpy as np
currentDataClass = [1, 3, 3, 2, 5, 5, 3, 2, 1, 4, 3, 2, 1, 1, 2]
predictedClass = [1, 2, 3, 4, 2, 3, 3, 2, 1, 2, 3, 1, 5, 1, 1]
def comp_confmat(actual, predicted):
classes = np.unique(actual)
matrix = np.zeros((len(classes), len(classes)))
for i in range(len(classes)):
for j in range(len(classes)):
matrix[i, j] = np.sum((actual == classes[i]) & (predicted == classes[j]))
return matrix
comp_confmat(currentDataClass, predictedClass)
array([[3., 0., 0., 0., 1.],
[2., 1., 0., 1., 0.],
[0., 1., 3., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 1., 1., 0., 0.]])