How to know my labels are arranged properly in confusion matrix in python?

Viewed 362

I have created a confusion matrix for my data as follows:

knn = KNeighborsClassifier(n_neighbors = 85).fit(x_train, y_train)
accuracy = knn.score(x_test, y_test)
knn_pred = knn.predict(x_test)
print(knn_pred)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, knn_pred)

In the above code y_test is a list of labels containing emotions ['neutral', 'happy','sad', 'angry','fearful','surprised','calm','disgust']. Now when I ran the above code to print the confusion matrix the output I got as follows:

[[31  2  0  0  6  0  0  9]
 [ 0 38  5  0  0  1  4  0]
 [ 8  6 13  1  3  0  0 17]
 [12  5  6 13  2  0  1  9]
 [ 5 10  4  4 10  0  1 14]
 [ 0 16  5  0  1  0  1  1]
 [ 5 24  6  2  2  1  2  6]
 [ 6  8  2  2  7  0  0 23]]

Now I have doubt here that the rows in the above matrix corresponds to which emotion. How to find the emotion label corresponding to a row in the confusion matrix that I got above. Also tell me how to plot the confusion matrix on a heatmap with labels.

1 Answers

The third argument of confusion_matrix is used just for that. Quoting from the documentation:

labels: array-like of shape (n_classes), default=None List of labels to index the matrix. This may be used to reorder or select a subset of labels. If None is given, those that appear at least once in y_true or y_pred are used in sorted order.

So, your rows and columns are in alphabetical order. If you want a different order, just pass the labels as list to confusion_matrix and it will use the order you specified.

Related