python - sklearn fusion_matrix 在错误的位置显示错误的尺寸/刻度线

标签 python scikit-learn confusion-matrix

我正在尝试显示一个混淆矩阵,但我无法弄清楚为什么它拒绝以适当的方式显示。这是我的代码:

import numpy as np
import itertools
from sklearn.metrics import confusion_matrix

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.winter):
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title, fontsize=30)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, fontsize=20)
    plt.yticks(tick_marks, classes, fontsize=20)

    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", fontsize=40)

    plt.tight_layout()
    plt.ylabel('True label', fontsize=30)
    plt.xlabel('Predicted label', fontsize=30)

    return plt

cm = confusion_matrix(y_test, y_predicted_counts)
fig = plt.figure(figsize=(10, 10))
plot = plot_confusion_matrix(cm, classes=['Unsure','No','Yes'], normalize=False, title='Confusion matrix')
plt.show()
print(cm)

这就是显示的内容:

bad confusion matrix

如有任何帮助,我们将不胜感激。提前致谢。

最佳答案

对于对 imshow 的调用,您需要指定 origin='lower' (默认为 'upper';他们可能在某个时候更改了此设置,并且 scikit-学习文档没有更新他们的 example )。因此,以下应该可以解决问题:

plt.imshow(cm, interpolation='nearest', cmap=cmap, origin='lower')
#                                                    ^
#                                                    |
# added origin='lower'  ------------------------------

关于python - sklearn fusion_matrix 在错误的位置显示错误的尺寸/刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110839/

相关文章:

python - 无论索引如何,按字母顺序对 QComboBox 项目进行排序

python - 拆分前的数据扩充

python - Pandas:将数据框除以列中的某些值

python - 在 0 和 1 之间进行归一化,忽略 NaN

python - 将函数结果附加到数据框

python - 从列表中删除值

python - For循环运行无限python

python - 简单的 Python 爬虫/蜘蛛运行时错误

python - Scikit 学习如何为混淆矩阵打印标签?

python - 使用 cross_validate 生成混淆矩阵