accuracy for each class

Solutions on MaxInterview for accuracy for each class by the best coders in the world

showing results for - "accuracy for each class"
Alesandro
13 Jan 2017
1from sklearn.metrics import confusion_matrix
2import numpy as np
3
4y_true = [0, 1, 2, 2, 2]
5y_pred = [0, 0, 2, 2, 1]
6target_names = ['class 0', 'class 1', 'class 2']
7
8#Get the confusion matrix
9cm = confusion_matrix(y_true, y_pred)
10#array([[1, 0, 0],
11#   [1, 0, 0],
12#   [0, 1, 2]])
13
14#Now the normalize the diagonal entries
15cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
16#array([[1.        , 0.        , 0.        ],
17#      [1.        , 0.        , 0.        ],
18#      [0.        , 0.33333333, 0.66666667]])
19
20#The diagonal entries are the accuracies of each class
21cm.diagonal()
22#array([1.        , 0.        , 0.66666667])
23