有没有办法为多标签分类器实现 2x2 混淆矩阵?

Is there a way to implement a 2x2 confusion matrix for multilabel classifier?

我有兴趣为多标签分类问题创建一个 2x2 混淆矩阵,它只显示总数 false/true positives/negatives.

我有一段代码生成了一个完整的混淆矩阵,但是有 98 个标签,几乎不可能看到任何东西。我不太在意是否有一个完整的矩阵,所以只显示上述四个属性的 2x2 是最理想的,我只是不确定如何实现它。

这是代码片段,如果对您有帮助的话:

predictions_d7 = model_d7.predict(x_test_d7)

y_pred = np.argmax(predictions_d7, axis=1)
y_test = np.argmax(Y_test_d7, axis=1)

print(y_test)
print(y_pred)

cm = confusion_matrix(y_test, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[label_list)
fig, ax = plt.subplots(figsize=(20,20))
disp.plot(ax=ax, values_format="d", cmap='gray')
disp.im_.colorbar.remove()
print( classification_report(y_test,y_pred))

在您希望的情况下得到 2x2 矩阵的原因是恰好有两个标签。你可以把它想象成标签1和2,真假都无所谓。

但是,请尝试添加第三个标签并考虑如何计算“真阳性”。有可能吗?

不,它必须是一个 3x3 矩阵,因为每个 class 有 3 种可能性,因此总共有 9 种可能性 - 例如:它是 class 1 而你预测 class 1. 它是 class 1 但你预测 class 2,依此类推。

也许您应该使用收到的 nxn 混淆矩阵,然后使用一些通用指标来评估您的模型(准确性、精确度、召回率等)。你仍然可以在 n 维中进行。有关描述,请参阅此堆栈交换 post:https://stats.stackexchange.com/questions/91044/how-to-calculate-precision-and-recall-in-a-3-x-3-confusion-matrix

您可以按如下方式计算 2 x 2 混淆矩阵:

import numpy as np

def confusion_matrix(y_true, y_pred):

    tp = np.logical_and(y_pred == 1, y_true == 1).sum()
    tn = np.logical_and(y_pred == 0, y_true == 0).sum()
    fp = np.logical_and(y_pred == 1, y_true == 0).sum()
    fn = np.logical_and(y_pred == 0, y_true == 1).sum()

    return tp, tn, fp, fn

from sklearn.datasets import make_multilabel_classification
from sklearn.ensemble import RandomForestClassifier

X, y = make_multilabel_classification(random_state=42)

clf = RandomForestClassifier(max_depth=3, random_state=42)
clf.fit(X, y)

y_pred = clf.predict(X)

tp, tn, fp, fn = confusion_matrix(y, y_pred)
print(tp, tn, fp, fn)
# 114 314 7 65