Example 1: import sklearn.metrics from plot_confusion_matrix
from sklearn.metrics import plot_confusion_matrix
Example 2: 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 3: 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.]])