用Python法计算灵敏度和特异性

2024-04-26 03:45:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算2个numpy数组的灵敏度和特异性(test,truth)。两个数组的形状相同,只存储数字0(test/truth false),1(test/truth true)。因此我必须计算假阳性,真阳性,假阴性和真阴性。我是这样做的:

true_positive = 0
false_positive = 0
false_negative = 0
true_negative = 0

for y in range(mask.shape[0]):
    for x in range(mask.shape[1]):
        if (mask[y,x] == 255 and truth[y,x] == 255):
            true_positive = true_positive + 1
        elif (mask[y,x] == 255 and truth[y,x] == 0):
            false_positive = false_positive + 1
        elif (mask[y,x] == 0 and truth[y,x] == 255):
            false_negative = false_negative + 1
        elif (mask[y,x] == 0 and truth[y,x] == 0):
            true_negative = true_negative + 1

sensitivity = true_positive / (true_positive + false_negative)
specificity = true_negative / (false_positive + true_negative)
<>我认为可能存在一个更容易(更可读)的方式,因为它是Python而不是C++…首先,我尝试了如下操作:true_positive = np.sum(mask == 255 and truth == 255)但是我得到了一个错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有没有一种更像Python的方法来计算敏感性和特异性?在

谢谢!在


Tags: andintestfalsetrueformask数组
3条回答

通过NumPy支持的^{}操作、^{}和{a3}来关注紧性,这里有一个方法-

C = (((mask==255)*2 + (truth==255)).reshape(-1,1) == range(4)).sum(0)
sensitivity, specificity = C[3]/C[1::2].sum(), C[0]/C[::2].sum()

另一种方法是,稍微用一点数学运算,我们可以用^{}来计算C

^{pr2}$

为了确保我们得到的是浮点数作为比率,首先,我们需要使用:from __future__ import division。在

四个数组可以这样找到和组织:

categories=dstack((mask&truth>0,mask>truth,mask<truth,mask|truth==0))

然后是分数:

^{pr2}$

最终结果是:

sensitivity,specificity = tp/(tp+fn),tn/(tf+fp)

测试相同形状:

a = np.random.rand(4,4)
b = np.random.rand(4,4)
print(a.shape == b.shape) #prints true

检验真值:

^{pr2}$

相关问题 更多 >