首页 > 解决方案 > PyTorch 混淆矩阵图

问题描述

我遇到了绘制混淆矩阵的问题。上下线放错了。当我绘制它时,它看起来像这样。

在此处输入图像描述

我认为我的代码没有任何问题,因为我完全是从这个 YouTube 中获取的。

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' 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 label')
    plt.xlabel('Predicted label')

# Graphical analytics
cm = confusion_matrix(train_set.targets, train_preds.argmax(dim=1))
names = ('T-shirt/top','Trouser','Pullover','Dress','Coat','Sandal','Shirt','Sneaker','Bag','Ankle boot')
plt.figure(figsize=(10,10))
plot_confusion_matrix(cm, names)

标签: pythonmatplotlibpytorchconfusion-matrix

解决方案


您可以手动更改y轴的范围。

plt.ylim(-0.5, len(names) - 0.5)

由于某种原因,估计轴范围的启发式方法不会让您不仅对正在绘制的点感兴趣,而且对两个轴上的 (-0.5; +0.5) 周围的点感兴趣。

最低点的y坐标为 0,最高点的y坐标为len(names) - 1


推荐阅读