简体   繁体   English

如何从 Python 中的二进制值对计算 TP/TN/FP/FN?

[英]How to calculate TP/TN/FP/FN from binary value pairs in Python?

I want to write a Python function that on a binary value input pair (truth, prediction) gives back True Positive/True Negative/False Positive/False Negative values according their input.我想编写一个 Python 函数,它在二进制值输入对(真值,预测)上根据输入返回真阳性/真阴性/假阳性/假阴性值。 So far I have reached the required output with this:到目前为止,我已经达到了所需的输出:

def func(truth, prediction):
    
    if prediction == 1:
        
        if truth == 1:
            return "TP"
        else:
            return "FP"

    elif truth == 1:
        return "FN"

    else:
        return "TN"

However, this seems a but clunky solution, is there a shorter, more elegant way?然而,这似乎是一个笨拙的解决方案,有没有更短、更优雅的方法?

(The input pair is supposed to be a binary integer 0/1) (输入对应该是二进制整数 0/1)

The comment from Johnny Mopp is pretty cool (though I think the order should be ['TN', 'FN', 'FP', 'TP'] , but if I came across it in code I'd have to think twice. (I can count on one hand the number of times I've seen bit-shift operations in production code.) Johnny Mopp的评论非常酷(虽然我认为顺序应该是['TN', 'FN', 'FP', 'TP'] ,但如果我在代码中遇到它,我必须三思而后行。 (一方面我可以数出我在生产代码中看到移位操作的次数。)

There's a new way to handle things like this in Python 3.10: structural pattern matching .在 Python 3.10 中有一种处理此类事情的新方法: 结构模式匹配 Now, this is the first time I've tried to use this new feature, but here's how it might look:现在,这是我第一次尝试使用这个新功能,但它看起来是这样的:

def get_result(true, pred):
    """Decide if TP, FP, TN or FN"""
    match [true, pred]:
        case [1, 1]: return 'TP'
        case [1, 0]: return 'FN'
        case [0, 0]: return 'TN'
        case [0, 1]: return 'FP'

Seems to work:似乎工作:

>>> y = [1, 0, 1, 0]  # TP, FP, FN, TN
>>> ŷ = [1, 1, 0, 0]

>>> for yi, ŷi in zip(y, ŷ):
>>>     print(get_result(yi, ŷi))
TP
FP
FN
TN

If you need to use Python 3.9 or below, then you could compactify your approach with something like this:如果您需要使用 Python 3.9 或更低版本,那么您可以通过以下方式压缩您的方法:

def get_result(true, pred):
    """Decide if TP, FP, TN or FN"""
    if pred:
        return 'TP' if true else 'FP'
    return 'FN' if true else 'TN'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM