You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何可视化ResNet50模型的混淆矩阵?绘制时遇问题求解

可行的混淆矩阵可视化方法

你用sklearn.metrics.plot_confusion_matrix(matrix)报错是因为该函数不能直接传入混淆矩阵,它需要模型、测试特征等参数。以下是三种实用的可视化方案:

方法1:Matplotlib手动绘制(高度自定义)

直接用Matplotlib配合Numpy实现,样式完全可控:

import matplotlib.pyplot as plt
import numpy as np

# 你的归一化混淆矩阵
matrix = np.array([[1, 0], [1, 2]], dtype=int64)
class_labels = ["类别0", "类别1"]  # 替换为你的实际类别名称

plt.figure(figsize=(8, 6))
# 绘制热力图
plt.imshow(matrix, cmap="Blues", interpolation="nearest")
plt.title("归一化混淆矩阵(基于预测值)")
plt.colorbar()

# 设置坐标轴标签
tick_marks = np.arange(len(class_labels))
plt.xticks(tick_marks, class_labels, rotation=45)
plt.yticks(tick_marks, class_labels)

# 添加矩阵数值标注
thresh = matrix.max() / 2
for i in range(matrix.shape[0]):
    for j in range(matrix.shape[1]):
        plt.text(j, i, matrix[i, j],
                 ha="center", va="center",
                 color="white" if matrix[i, j] > thresh else "black")

plt.ylabel("真实标签")
plt.xlabel("预测标签")
plt.tight_layout()
plt.show()

方法2:Seaborn热力图(简洁美观)

借助Seaborn快速生成专业样式的热力图:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

matrix = np.array([[1, 0], [1, 2]], dtype=int64)
class_labels = ["类别0", "类别1"]

plt.figure(figsize=(8, 6))
sns.heatmap(matrix, annot=True, fmt="d", cmap="Blues",
            xticklabels=class_labels, yticklabels=class_labels)
plt.title("归一化混淆矩阵(基于预测值)")
plt.ylabel("真实标签")
plt.xlabel("预测标签")
plt.show()
  • annot=True 显示矩阵数值,fmt="d" 指定整数格式(若为小数可改用fmt=".2f")

方法3:Scikit-learn官方推荐的ConfusionMatrixDisplay

新版Scikit-learn已弃用plot_confusion_matrix,推荐用ConfusionMatrixDisplay直接传入混淆矩阵:

from sklearn.metrics import ConfusionMatrixDisplay
import matplotlib.pyplot as plt
import numpy as np

matrix = np.array([[1, 0], [1, 2]], dtype=int64)
class_labels = ["类别0", "类别1"]

disp = ConfusionMatrixDisplay(confusion_matrix=matrix, display_labels=class_labels)
disp.plot(cmap="Blues", values_format="d")
plt.title("归一化混淆矩阵(基于预测值)")
plt.show()
  • 若Scikit-learn版本过旧,可先升级:pip install --upgrade scikit-learn

内容的提问来源于stack exchange,提问作者user22290650

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:37:15