【问题标题】:Confusion matrix fails to show all labels混淆矩阵无法显示所有标签
【发布时间】:2021-08-15 16:47:17
【问题描述】:

我为多标签分类创建了一个分类矩阵,以评估 MLPClassifier 模型的性能。混淆矩阵输出应该是 10x10,但有时我得到 8x8,因为它没有显示 1 或 2 个类标签的标签值,正如您在运行整个 Jupyter 笔记本时从代码下方的混淆矩阵热图中看到的那样。真实标签和预测标签的类别标签从 1 到 10(无序)。是因为代码错误,还是仅取决于测试数据集在将数据拆分为训练集和测试集时接受的随机输入样本?我应该如何解决这个问题?代码的实现如下所示:

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
str(cm)

Out:    [[20  0  0  1  0  5  1  0]
         [ 3  0  0  0  0  0  0  0]
         [ 1  1  0  1  0  1  0  0]
         [ 3  0  0  0  0  3  1  1]
         [ 0  0  0  0  0  1  0  0]
         [ 3  0  0  1  0  2  1  1]
         [ 3  0  0  0  0  0  0  2]
         [ 1  0  0  0  0  0  0  1]]

'[[20  0  0  1  0  5  1  0]\n [ 3  0  0  0  0  0  0  0]\n [ 1  1  0  1  0  
 1  0  0]\n [ 3  0  0  0  0  3  1  1]\n [ 0  0  0  0  0  1  0  0]\n [ 3  0  
 0  1  0  2  1  1]\n [ 3  0  0  0  0  0  0  2]\n [ 1  0  0  0  0  0  0  
 1]]'

import matplotlib.pyplot as plt
import seaborn as sns
side_bar = [1,2,3,4,5,6,7,8,9,10]
f, ax = plt.subplots(figsize=(12,12))
sns.heatmap(cm, annot=True, linewidth=.5, linecolor="r", fmt=".0f", ax = ax)
ax.set_xticklabels(side_bar)
ax.set_yticklabels(side_bar)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()

confusion matrix heatmap

【问题讨论】:

  • 我猜这不是 sklearn 实现中的错误,而是您的代码中的某些内容,可能与您的拆分有关。你检查过assert len(set(y_test)) == 10吗?
  • 这能回答你的问题吗? Stratified Train/Test-split in scikit-learn
  • 我现在使用 assert len(set(y_Test_ == 10) 进行了检查,但出现错误“TypeError: unhashable type: 'numpy.ndarray'”。
  • 我也尝试了您共享的分层训练/测试拆分链接中建议的解决方案,但我收到错误“ValueError:y 中人口最少的班级只有 1 个成员,太少了。任何类的最小组数不能少于 2。"
  • 使用side_bar = np.unique(y_test) 怎么样?y_test 中显然只使用了 8 个标签?与previous question 相比,你有什么改变?混淆矩阵从不包含不属于数据的值的行/列。请注意,如果您没有足够的数据来确保测试集包含所有标签,那么您的分类器将无法正常工作。在测试和训练数据中,您确实需要为每个标签提供足够多的示例。

标签: python matplotlib confusion-matrix multilabel-classification


【解决方案1】:

我认为这里有混乱!混淆矩阵是 set(y_test) + set(y_pred)。所以如果这是 8。那么矩阵将是 8 X 8。现在,如果你有更多的标签,你想打印,即使它是否全为零也没关系。然后在构建矩阵时,您需要提供“标签”参数。

y_true = [2, 0, 2, 2, 0, 1,5]
y_pred = [0, 0, 2, 2, 0, 2,4]
confusion_matrix = confusion_matrix(y_true, y_pred,labels=[0,1,2,3,4,5,6])

如您所见,y_true 或 y_pred 中确实不存在 6,您将为其归零。

【讨论】:

  • 谢谢,它有效,所有标签都打印在混淆矩阵中。
猜你喜欢
  • 2020-01-22
  • 1970-01-01
  • 2020-07-31
  • 2018-11-06
  • 2018-04-07
  • 2013-10-14
  • 2020-03-09
  • 2021-11-11
  • 2020-08-15
相关资源
最近更新 更多