首页 > 解决方案 > 如何使我的混淆矩阵图更好?

问题描述

我正在研究一个有 20 个类的分类问题。我正在尝试使用matplotlib通过混淆矩阵来可视化结果。

在计算了我的混淆矩阵之后,我使用了这里plot_confusion_matrix描述的。

def plot_confusion_matrix(y_true, y_pred, classes,
                      normalize=False,
                      title=None,
                      cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
    if normalize:
        title = 'Normalized confusion matrix'
    else:
        title = 'Confusion matrix, without normalization'

# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
classes = classes[unique_labels(y_true, y_pred)]
if normalize:
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    print("Normalized confusion matrix")
else:
    print('Confusion matrix, without normalization')

print(cm)

fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
       yticks=np.arange(cm.shape[0]),
       # ... and label them with the respective list entries
       xticklabels=classes, yticklabels=classes,
       title=title,
       ylabel='True label',
       xlabel='Predicted label')

# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
         rotation_mode="anchor")

# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
    for j in range(cm.shape[1]):
        ax.text(j, i, format(cm[i, j], fmt),
                ha="center", va="center",
                color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
return ax

这是它的样子: 在此处输入图像描述 看起来问题来自于处理太多的类,所以一个自然的解决方案是扩大情节。但这样做会扭曲它。另外,如何选择正确的比例/尺寸?

我该如何继续使它看起来更好?

PS 你可以在这里找到作为 csv 文件的 confution 矩阵。

标签: pythonmatplotlib

解决方案


由于您没有指定 matplotlib 的严格使用,我建议您使用 seaborn 库,它非常容易和简单,如果您想更改一些奇怪的东西,如果我没有错的话,用 matplolib 构建。使用 seaborn 是:

import seaborn as sns 

plt.figure(figsize = (10,10))  #This is the size of the image
heatM = sns.heatmap(cov_vals, vmin = -1, vmax = 1,center = 0, cmap = sns.diverging_palette(20, 220, n = 200),  square = True, annot = True) #this are the caracteristics of the heatmap
heatM.set_ylim([10,0]) # This is the limit in y axis (number of features)

这就是结果。也要小心 x 的限制 heatM.set_ylim([10,0]) ,这需要是你拥有的变量的数量。

希望这很有用。

在此处输入图像描述


推荐阅读