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: sklearn plot confusion matrix
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, plot_confusion_matrix
clf =
clf.fit(X, y)
y_pred = clf.predict(X)
M = confusion_matrix(y, y_pred)
tn, fp, fn, tp = M.ravel()
plot_confusion_matrix(clf, X, y)
plt.show()
Example 3: confusion matrix python
df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)
Example 4: 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.]])