【问题标题】:How to find true positives, true negatives, false positives, false negatives in Python [closed]如何在 Python 中找到真阳性、真阴性、假阳性、假阴性 [关闭]
【发布时间】:2015-03-30 15:54:11
【问题描述】:

我在 Python 中训练了一个分类器,我想在进行新分类时找到真阳性、真阴性、假阳性、假阴性。 问题是,我的 true_labels 每次都包含一个值点,因为在我正在调查的问题中,我只有一个标签,我想看看分类器在识别这个标签时在新数据上的表现如何。例如:

labels_true = [2, 2, 2, 2, ..., 2]
labels_predicted = [2, 2, 23, 2, 2, 2, 2, 21, ..., 2, 2, 2, 2]

当然是`len(labels_true)=len(labels_predicted)。由于我只有一个真正的标签,我该如何计算上述指标?

【问题讨论】:

    标签: python classification metrics


    【解决方案1】:

    如果您的 label_true 仅包含 true 值,则您只能找到真阳性 (TP) 和假阴性 (FN),因为没有可以找到的假值(真阴性 TN)或遗漏(假阳性) FP)

    TP,TN,FP,FN 适用于二分类问题。要么分析整个混淆矩阵,要么进行分箱以获得二元问题

    这是一个分箱解决方案:

    from collections import Counter
    
    truth      = [1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 4, 1]
    prediction = [1, 1, 2, 1, 1, 2, 1, 2, 1, 4, 4, 3]
    
    confusion_matrix = Counter()
    
    #say class 1, 3 are true; all other classes are false
    positives = [1, 3]
    
    binary_truth = [x in positives for x in truth]
    binary_prediction = [x in positives for x in prediction]
    print binary_truth
    print binary_prediction
    
    for t, p in zip(binary_truth, binary_prediction):
        confusion_matrix[t,p] += 1
    
    print "TP: {} TN: {} FP: {} FN: {}".format(confusion_matrix[True,True], confusion_matrix[False,False], confusion_matrix[False,True], confusion_matrix[True,False])
    

    编辑:这是一个完整的混淆矩阵

    from collections import Counter
    
    truth      = [1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 4, 1]
    prediction = [1, 1, 2, 1, 1, 2, 1, 2, 1, 4, 4, 3]
    
    # make confusion matrix
    confusion_matrix = Counter()
    for t, p in zip(truth, prediction):
        confusion_matrix[t,p] += 1
    
    # print confusion matrix
    labels = set(truth + prediction)
    print "t/p",
    for p in sorted(labels):
        print p,
    print
    for t in sorted(labels):
        print t,
        for p in sorted(labels):
            print confusion_matrix[t,p],
        print
    

    【讨论】:

    • 谢谢。我怎样才能稍微修改混淆矩阵索引以便对许多数据集进行迭代?
    • @gelazari:我不确定我是否正确理解了您的问题。查看我的编辑。
    猜你喜欢
    • 2016-02-03
    • 2018-04-22
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2021-11-15
    • 2021-12-14
    • 2020-10-31
    相关资源
    最近更新 更多