【问题标题】:Scikit-learn: How to calculate the True NegativeScikit-learn:如何计算真阴性
【发布时间】:2015-09-29 11:53:20
【问题描述】:

我正在使用 Scikit-learning,我需要从如下混淆矩阵中计算真阳性 (TP)、假阳性 (FP)、真阴性 (TN) 和假阴性 (FN):

[[2 0 3 4]
 [0 4 5 1]
 [1 0 3 2]
 [5 0 0 4]]

我知道如何计算 TP、FP 和 FN,但我不知道如何获得 TN。谁能告诉我?

【问题讨论】:

标签: python machine-learning scikit-learn supervised-learning


【解决方案1】:

我认为您应该以一对一的方式对待这种多类分类(因此每个 2x2 表 i 衡量一个二元分类问题的性能,即每个 obs 是否属于标签 i 或不是)。因此,您可以计算每个标签的 TP、FP、FN、TN。

import numpy as np

confusion_matrix = np.array([[2,0,3,4],
                             [0,4,5,1],
                             [1,0,3,2],
                             [5,0,0,4]])

def process_cm(confusion_mat, i=0, to_print=True):
    # i means which class to choose to do one-vs-the-rest calculation
    # rows are actual obs whereas columns are predictions
    TP = confusion_mat[i,i]  # correctly labeled as i
    FP = confusion_mat[:,i].sum() - TP  # incorrectly labeled as i
    FN = confusion_mat[i,:].sum() - TP  # incorrectly labeled as non-i
    TN = confusion_mat.sum().sum() - TP - FP - FN
    if to_print:
        print('TP: {}'.format(TP))
        print('FP: {}'.format(FP))
        print('FN: {}'.format(FN))
        print('TN: {}'.format(TN))
    return TP, FP, FN, TN

for i in range(4):
    print('Calculating 2x2 contigency table for label{}'.format(i))
    process_cm(confusion_matrix, i, to_print=True)

Calculating 2x2 contigency table for label0
TP: 2
FP: 6
FN: 7
TN: 19
Calculating 2x2 contigency table for label1
TP: 4
FP: 0
FN: 6
TN: 24
Calculating 2x2 contigency table for label2
TP: 3
FP: 8
FN: 3
TN: 20
Calculating 2x2 contigency table for label3
TP: 4
FP: 7
FN: 5
TN: 18

【讨论】:

  • 很好的答案!为了增加讨论,我将指出scikit-learn 也具有多类评分指标的功能。如果您计划将 TP、FP、FN 和 TN 聚合到 ROC 中,我建议使用documented here 并在the user guide here 中解决的评分度量方法。当引入大量类时,F1-score 等指标会变得非常混乱,因此这些指标非常有用。
【解决方案2】:

我认为对于像这样的多类问题,你必须决定这 4 个类中的哪一个可以被认为是正类,并且你必须将其余 3 类组合为负类来计算真正的负类。详细讨论已完成 here

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 2021-11-15
    • 2016-02-03
    • 2014-07-28
    • 2021-02-10
    • 2014-07-13
    • 2015-10-19
    • 2020-05-07
    相关资源
    最近更新 更多