计算灵敏度和特异性的 Pythonic 方法

标签 python numpy

我想计算 2 个 numpy 数组(测试、真相)的灵敏度和特异性。两个数组具有相同的形状,并且仅存储数字 0(测试/真相为假)、1(测试/真相为真)。因此,我必须计算 false_positives、true_positives、false_negative 和 true_negative 值。我是这样做的:

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()

是否有更 pythonic 的方法来计算灵敏度和特异性?

谢谢!

最佳答案

通过支持 NumPy 关注紧凑性 ufunc-vectorized操作,broadcastingarray-slicing , 这是一种方法 -

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()

或者,使用 NumPythonic,我们可以用 np.bincount 计数 C -

C = np.bincount(((mask==255)*2 + (truth==255)).ravel())

为了确保我们得到 float 的 pt 数字作为比率,在开始时,我们需要使用:from __future__ import division

关于计算灵敏度和特异性的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938613/

相关文章:

python - Django rest framework : serializers. ReadOnlyField() 不在可浏览的 api 中显示字段

python - Cythonized 函数出乎意料地慢

python - NumPy 数组数组到 PyOpenCL vecs 数组

Python Pandas 不读取 csv 文件的第一行

python - Pandas 数据透视表中的多维乘法

php - 从数据库服务器端创建绘图并在客户端可视化

python - 获取 Django View 中的复选框列表

python - 使用cgi python区分不同形式

python - 在 Python 进程之间共享一个大的(只读的)二进制字符串?

python:具有多个条件的 pandas np.where 与 df.loc