如何在考虑所有 类 的情况下找到所有真阳性、阴性以及假阳性和阴性

How to find all the True Positives,negatives and False Positives and Negatives considering all the classes

我可以对我知道所需输出的较小数据集执行相同的操作

例如: 我有数据集:

y_true=[1,1,0,1]
y_pred=[1,0,0,0]

我能够编写函数来查找所有真假阳性和阴性:

def measures(y_pred, y_true):
    TP = 0
    FP = 0
    TN = 0
    FN = 0

    for i in range(len(y_pred)): 
        if y_true[i]==y_pred[i]==1:
           TP += 1
        if y_pred[i]==1 and y_true[i]!=y_pred[i]:
           FP += 1
        if y_true[i]==y_pred[i]==0:
           TN += 1
        if y_pred[i]==0 and y_true[i]!=y_pred[i]:
           FN += 1

    return(TP, FP, TN, FN)

但是如果我想为多个标签找到相同的东西,就像这样:

y_true=[1,2,0,1,3]
y_pred=[1,0,3,2,1]

所以我想找到所有 TP_total、TN_total、FP_total 和 FN_total 考虑每个标签 '1','2','0','3'

我该怎么做

在 Python 中,scikit-learn 包 (https://scikit-learn.org/stable/index.html) provides a function which will return the confusion matrix of a classification problem (binary or multiclass), the confusion_matrix function (see https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html)。使用混淆矩阵,您可以获得问题的真阳性、真阴性、假阳性和假阴性。

下图(取自 https://scikit-learn.org/stable/auto_examples/miscellaneous/plot_display_object_visualization.html#sphx-glr-auto-examples-miscellaneous-plot-display-object-visualization-py)说明了使用 scikit-learn 生成的二进制 class 化的混淆矩阵。在图中,假阳性在左上角 (140),真阳性在右下角 (5),假阴性在左下角 (39),假阳性在右上角 (3)。

在多class设置中,解释是相似的。但是,您的错误将与多个 class 相关联,而不仅仅是一个 class(例如在二进制 classification 设置中)。

希望对您有所帮助!

由于您在问题中标记了 Scikit-Learn,除了各种分类指标(例如精度、召回率、准确度、 F1-Score 和 Support ... 直接使用 Classification Report and the Confusion Matrix returns 你想要的(示例):

tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()

或者您可以使用 Plot Confusion Matrix.

绘制它

(示例在链接中)


下面是一些示例: