谐波在Python的功能是什么意思?(Harmonic mean in a python funct

2019-08-04 01:14发布

我有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)

Answer 1:

有了您的轻微变化F1功能,并且具有相同precisionrecall你定义的函数,我有这样的工作:

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功能。



Answer 2:

下面将与任意数量的参数工作:

def hmean(*args):
    return len(args) / sum(1. / val for val in args)

为了计算的调和平均precisionrecall ,使用:

result = hmean(precision, recall)

有两个问题与你的函数:

  1. 它没有返回值。
  2. 在Python中的某些版本中,它将使用整数除法的整数参数,截断结果。


文章来源: Harmonic mean in a python function?
标签: python mean