混淆矩阵怎样显示整数形式呢?

混淆矩阵怎样显示整数形式呢?

设置了false,为什么最终结果还是百分百呢?

img

【以下回答由 GPT 生成】

可以通过在设置plt.imshow时添加vminvmax参数来设置颜色映射范围,从而实现将混淆矩阵以整数形式呈现。具体步骤如下:

  1. 修改plot_confusion_matrix函数,将plt.imshow的调用语句修改如下:
plt.imshow(cm, interpolation='nearest', cmap=cmap, vmin=np.min(cm), vmax=np.max(cm))
  1. 修改使用示例,将plot_confusion_matrix函数调用的参数normalize改为False
plot_confusion_matrix(cm, classes, normalize=False)

修改后的代码如下:

import numpy as np
import matplotlib.pyplot as plt

def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("显示百分比:")
    else:
        print("显示具体数字:")

    np.set_printoptions(formatter={'float': '{: 0.0f}'.format})
    plt.imshow(cm, interpolation='nearest', cmap=cmap, vmin=np.min(cm), vmax=np.max(cm))
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.0f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in 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')

# 使用示例
cm = [[42, 0, 0],
      [3, 44, 5],
      [0, 0, 51]]
classes = ['Class 1', 'Class 2', 'Class 3']

plot_confusion_matrix(cm, classes, normalize=False)
plt.show()

运行以上代码,即可将混淆矩阵以整数形式显示出来。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^