Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (47.6k points)

I want to plot a confusion matrix to visualize the classifier's performance, but it shows only the numbers of the labels, not the labels themselves:

from sklearn.metrics import confusion_matrix

import pylab as pl 

y_test=['business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business'] pred=array(['health', 'business', 'business', 'business', 'business', 'business', 'health', 'health', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'health', 'health', 'business', 'health'], dtype='|S8') 

cm = confusion_matrix(y_test, pred) 

pl.matshow(cm) 

pl.title('Confusion matrix of the classifier') 

pl.colorbar() 

pl.show()

How can I add the labels (health, business..etc) to the confusion matrix?

1 Answer

0 votes
by (33.1k points)

In your problem, you can plot a confusion matrix using scikit-learn’s metric class, but you need to store the figure first to plot the confusion matrix. The lower-level API’s in matplotlib can store the figure. You can either replace the x-axis and y-axis ticks with ticks labels or you can pass the labels argument in confusion matrix module.

from sklearn.metrics import confusion_matrix

From matplotlib.pyplot import plt

labels = ['business', 'health'] 

cm = confusion_matrix(y_test, pred, labels) 

print(cm) 

fig = plt.figure() 

ax = fig.add_subplot(111) 

cax = ax.matshow(cm) 

plt.title('Confusion matrix of the classifier') 

fig.colorbar(cax) 

ax.set_xticklabels([''] + labels) 

ax.set_yticklabels([''] + labels) 

plt.xlabel('Predicted') 

plt.ylabel('True') 

plt.show()

Output:

image

Hope this answer helps.

If you wish to learn more about Machine Learning, visit Machine Learning tutorial and Machine Learning course by Intellipaat.

Browse Categories

...