我有2个函数可以给出精度和召回分数,我需要在使用这两个分数的同一个库中定义一个调和均值函数。功能如下:
这是功能:
def precision(ref, hyp):
"""Calculates precision.
Args:
- ref: a list of 0's and 1's extracted from a reference file
- hyp: a list of 0's and 1's extracted from a hypothesis file
Returns:
- A floating point number indicating the precision of the hypothesis
"""
(n, np, ntp) = (len(ref), 0.0, 0.0)
for i in range(n):
if bool(hyp[i]):
np += 1
if bool(ref[i]):
ntp += 1
return ntp/np
def recall(ref, hyp):
"""Calculates recall.
Args:
- ref: a list of 0's and 1's extracted from a reference file
- hyp: a list of 0's and 1's extracted from a hypothesis file
Returns:
- A floating point number indicating the recall rate of the hypothesis
"""
(n, nt, ntp) = (len(ref), 0.0, 0.0)
for i in range(n):
if bool(ref[i]):
nt += 1
if bool(hyp[i]):
ntp += 1
return ntp/nt
谐波平均功能是什么样的? 我只有这个,但我知道它不对:
def F1(precision, recall):
(2*precision*recall)/(precision+recall)
答案 0 :(得分:2)
以下内容适用于任意数量的参数:
def hmean(*args):
return len(args) / sum(1. / val for val in args)
要计算precision
和recall
的调和平均值,请使用:
result = hmean(precision, recall)
您的功能有两个问题:
答案 1 :(得分:0)
稍加更改F1
功能,并使用您定义的相同precision
和recall
功能,我就可以了:
def F1(precision, recall):
return (2*precision*recall)/(precision+recall)
r = [0,1,0,0,0,1,1,0,1]
h = [0,1,1,1,0,0,1,0,1]
p = precision(r, h)
rec = recall(r, h)
f = F1(p, rec)
print f
特别回顾我所拥有的变量的使用。您必须计算每个函数的结果并将它们传递给F1
函数。