混淆矩阵不支持多标签指示符。

39

multilabel-indicator is not supported 这是我运行以下代码时遇到的错误信息:

confusion_matrix(y_test, predictions)

y_test 是一个形状为 DataFrame 的对象:

Horse | Dog | Cat
1       0     0
0       1     0
0       1     0
...     ...   ...

predictions 是一个 numpy array

[[1, 0, 0],
 [0, 1, 0],
 [0, 1, 0]]

我已经搜索了一下错误信息,但没有找到可应用的东西。有什么提示吗?


3
如果有人正在寻找正确的方法来可视化多标签分类器的误差,我想要加入自己的看法:你的预测数组似乎是来自一个多类别分类器。对于多标签分类,混淆矩阵并不适用,因为会同时预测多个标签。 - Thilo
4个回答

77

不,你输入到confusion_matrix的必须是一个预测列表,而不是OHE(one hot encodings)。在y_testy_pred上调用argmax,你应该能得到你期望的结果。

confusion_matrix(
    y_test.values.argmax(axis=1), predictions.argmax(axis=1))

array([[1, 0],
       [0, 2]])

第三行发生了什么? - rumble_shark

14

混淆矩阵需要一个标签向量(而不是one-hot编码)。你应该运行

confusion_matrix(y_test.values.argmax(axis=1), predictions.argmax(axis=1))

5
如果您拥有numpy.ndarray,可以尝试以下操作。

import seaborn as sns

T5_lables = ['4TCM','WCM','WSCCM','IWCM','CCM']    

ax= plt.subplot()

cm = confusion_matrix(np.asarray(Y_Test).argmax(axis=1), np.asarray(Y_Pred).argmax(axis=1))
sns.heatmap(cm, annot=True, fmt='g', ax=ax);  #annot=True to annotate cells, ftm='g' to disable scientific notation

# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); 
ax.set_title('Confusion Matrix'); 
ax.xaxis.set_ticklabels(T5_lables); ax.yaxis.set_ticklabels(T5_lables);


image


4
from sklearn.metrics import confusion_matrix

predictions_one_hot = model.predict(test_data)
cm = confusion_matrix(labels_one_hot.argmax(axis=1), predictions_one_hot.argmax(axis=1))
print(cm)

输出的结果大致是这样的:

[[298   2  47  15  77   3  49]
 [ 14  31   2   0   5   1   2]
 [ 64   5 262  22  94  38  43]
 [ 16   1  20 779  15  14  34]
 [ 49   0  71  33 316   7 118]
 [ 14   0  42  23   5 323   9]
 [ 20   1  27  32  97  13 436]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接