Issue
Of all the answers I see on stackoverflow, such as 1, 2 and 3 are color-coded.
In my case, I wouldn´t like it to be colored, especially since my dataset is largely imbalanced, minority classes are always shown in light color. I would instead, prefer it display the number of actual/predicted in each cell.
Currently, I use:
def plot_confusion_matrix(cm, classes, title,
normalize=False,
file='confusion_matrix',
cmap=plt.cm.Blues):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm_title = "Normalized confusion matrix"
else:
cm_title = title
# print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(cm_title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.3f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True class')
plt.xlabel('Predicted class')
plt.tight_layout()
plt.savefig(file + '.png')
Output:
So I want the number shown only.
Solution
Use seaborn.heatmap
with a grayscale colormap and set vmin=0, vmax=0
:
import seaborn as sns
sns.heatmap(cm, fmt='d', annot=True, square=True,
cmap='gray_r', vmin=0, vmax=0, # set all to white
linewidths=0.5, linecolor='k', # draw black grid lines
cbar=False) # disable colorbar
# re-enable outer spines
sns.despine(left=False, right=False, top=False, bottom=False)
Complete function:
def plot_confusion_matrix(cm, classes, title,
normalize=False,
file='confusion_matrix',
cmap='gray_r',
linecolor='k'):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm_title = 'Confusion matrix, with normalization'
else:
cm_title = title
fmt = '.3f' if normalize else 'd'
sns.heatmap(cm, fmt=fmt, annot=True, square=True,
xticklabels=classes, yticklabels=classes,
cmap=cmap, vmin=0, vmax=0,
linewidths=0.5, linecolor=linecolor,
cbar=False)
sns.despine(left=False, right=False, top=False, bottom=False)
plt.title(cm_title)
plt.ylabel('True class')
plt.xlabel('Predicted class')
plt.tight_layout()
plt.savefig(f'{file}.png')
Answered By - tdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.