gpt4 book ai didi

python - 一次性计算精度、召回率和 F 分数 - python

转载 作者:太空狗 更新时间:2023-10-29 18:19:10 26 4
gpt4 key购买 nike

Accuracy, precision, recall and f-score是机器学习系统中系统质量的度量。它取决于真/假阳性/阴性的混淆矩阵。

给定一个二元分类任务,我尝试了以下方法来获得一个返回准确度、精确度、召回率和 f-score 的函数:

gold = [1] + [0] * 9
predicted = [1] * 10

def evaluation(gold, predicted):
true_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==1)
true_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==0)
false_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==0)
false_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==1)
try:
recall = true_pos / float(true_pos + false_neg)
except:
recall = 0
try:
precision = true_pos / float(true_pos + false_pos)
except:
precision = 0
try:
fscore = 2*precision*recall / (precision + recall)
except:
fscore = 0
try:
accuracy = (true_pos + true_neg) / float(len(gold))
except:
accuracy = 0
return accuracy, precision, recall, fscore

但似乎我已经冗余地循环遍历数据集 4 次以获得真/假阳性/阴性。

此外,用于捕获 ZeroDivisionError 的多个 try-excepts 也有点多余。

那么在没有多次循环遍历数据集的情况下获取真/假阳性/阴性计数的 pythonic 方法是什么?

如何在没有多个 try-excepts 的情况下以 python 方式捕获 ZeroDivisionError


我也可以在一个循环中执行以下操作来计算真/假阳性/阴性,但是是否有另一种方法没有多个 if:

for p,g in zip(predicted, gold):
if p==1 and g==1:
true_pos+=1
if p==0 and g==0:
true_neg+=1
if p==1 and g==0:
false_pos+=1
if p==0 and g==1:
false_neg+=1

最佳答案

what is the pythonic way to get the counts of the True/False Positives/Negatives without multiple loops through the dataset?

我会使用 collections.Counter ,最后您对所有 if 所做的大致操作(您应该使用 elif,因为您的条件是互斥的):

counts = Counter(zip(predicted, gold))

然后例如true_pos = counts[1, 1]

How do I pythonically catch the ZeroDivisionError without the multiple try-excepts?

首先,您应该(几乎)永远不要使用裸except:。如果您正在捕获 ZeroDivisionError,则编写 except ZeroDivisionError。你也可以考虑 "look before you leap"方法,在尝试除法之前检查分母是否为 0,例如

accuracy = (true_pos + true_neg) / float(len(gold)) if gold else 0

关于python - 一次性计算精度、召回率和 F 分数 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com