【问题标题】:How can I make my confusion matrix plot better?如何使我的混淆矩阵图更好?
【发布时间】:2020-02-28 17:22:09
【问题描述】:

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

在计算出我的混淆矩阵后,我使用了plot_confusion_matrix 描述的here

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

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

如何让它看起来更好?

附:您可以找到 confution 矩阵作为 csv 文件here

【问题讨论】:

  • 试试这个可能会得到一些提示:stackoverflow.com/questions/35572000/…
  • @jtweeder 我已经尝试过了。它看起来好多了,但正如您所见here,该图在顶部和底部被截断。此外,数字几乎不适合正方形。

标签: python matplotlib


【解决方案1】:

我最终使用了 seaborn,但我遇到了一个问题。混淆矩阵看起来像this。这实际上是 seaborn 的最新版本 (3.1.1) 中的一个错误(参见 issue)。解决方案是使用以前的版本(在我的例子中是 3.1.0)。

【讨论】:

  • 是的,纠正它是一个错误,有必要重新定义情节的限制,但由于错误已经纠正,所以不在乎哈哈。
【解决方案2】:

由于您没有指定 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]) ,这需要是您拥有的变量数。

希望这是有用的。

【讨论】:

  • 感谢您的回答。我已经尝试过这样做,但我遇到了一个问题。混淆矩阵看起来像this。这实际上是 seaborn 最新版本 (3.1.1) 中的一个错误(请参阅issue 此处)。解决方案是使用以前的版本(在我的例子中是 3.1.0)。
猜你喜欢
  • 2020-02-23
  • 1970-01-01
  • 2017-03-20
  • 2017-03-07
  • 2016-07-25
  • 2021-09-29
  • 2014-06-11
  • 2014-07-09
  • 2017-02-25
相关资源
最近更新 更多