Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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.title('Confusion matrix of the classifier') 


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) 


fig = plt.figure() 

ax = fig.add_subplot(111) 

cax = ax.matshow(cm) 

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


ax.set_xticklabels([''] + labels) 

ax.set_yticklabels([''] + labels) 





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