我正在使用分类器的多类多标签输出。类的总数为14,实例可以具有多个关联的类。例如:
y_true = np.array([[0,0,1], [1,1,0],[0,1,0])
y_pred = np.array([[0,0,1], [1,0,1],[1,0,0])
我现在制作混乱矩阵的方式:
matrix = confusion_matrix(y_true.argmax(axis=1), y_pred.argmax(axis=1))
print(matrix)
给出的输出如下:
[[ 79 0 0 0 66 0 0 151 1 8 0 0 0 0]
[ 4 0 0 0 11 0 0 27 0 0 0 0 0 0]
[ 14 0 0 0 21 0 0 47 0 1 0 0 0 0]
[ 1 0 0 0 4 0 0 25 0 0 0 0 0 0]
[ 18 0 0 0 50 0 0 63 0 3 0 0 0 0]
[ 4 0 0 0 3 0 0 19 0 0 0 0 0 0]
[ 2 0 0 0 3 0 0 11 0 2 0 0 0 0]
[ 22 0 0 0 20 0 0 138 1 5 0 0 0 0]
[ 12 0 0 0 9 0 0 38 0 1 0 0 0 0]
[ 10 0 0 0 3 0 0 40 0 4 0 0 0 0]
[ 3 0 0 0 3 0 0 14 0 3 0 0 0 0]
[ 0 0 0 0 2 0 0 3 0 0 0 0 0 0]
[ 2 0 0 0 11 0 0 32 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 3 0 0 0 0 0 7]]
现在,我不确定sklearn的混淆矩阵是否能够处理多标签多类数据。有人可以帮我吗?
答案 0 :(得分:2)
您需要做的是生成多个二进制混淆矩阵(因为实际上您拥有的是多个二进制标签)
类似的东西:
import numpy as np
from sklearn.metrics import confusion_matrix
y_true = np.array([[0,0,1], [1,1,0],[0,1,0]])
y_pred = np.array([[0,0,1], [1,0,1],[1,0,0]])
labels = ["A", "B", "C"]
conf_mat_dict={}
for label_col in range(len(labels)):
y_true_label = y_true[:, label_col]
y_pred_label = y_pred[:, label_col]
conf_mat_dict[labels[label_col]] = confusion_matrix(y_pred=y_pred_label, y_true=y_true_label)
for label, matrix in conf_mat_dict.items():
print("Confusion matrix for label {}:".format(label))
print(matrix)
答案 1 :(得分:0)
现在您可以使用(0.21版)sklearn.metrics.multilabel_confusion_matrix
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.multilabel_confusion_matrix.html
我们尝试为每个示例预测两个标签
import sklearn.metrics as skm
y_true = np.array([
[0,0], [0,1], [1,1], [0,1], [0,1], [1,1]
])
y_pred = np.array([
[1,1], [0,1], [0,1], [1,0], [0,1], [1,1]
])
cm = skm.multilabel_confusion_matrix(y_true, y_pred)
print(cm)
print( skm.classification_report(y_true,y_pred))
标签的混淆矩阵:
[[[2 2]
[1 1]]
[[0 1]
[1 4]]]
分类报告:
precision recall f1-score support
0 0.33 0.50 0.40 2
1 0.80 0.80 0.80 5
micro avg 0.62 0.71 0.67 7
macro avg 0.57 0.65 0.60 7
weighted avg 0.67 0.71 0.69 7
samples avg 0.67 0.58 0.61 7