python函数的调和平均值?

2024-06-16 10:31:19 发布

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

我有两个函数,给出精度和召回分数,我需要做一个调和平均函数,定义在同一个库中,使用这两个分数。函数如下所示:

功能如下:

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

调和平均函数是什么样子? 我只有这个,但我知道这是不对的:

^{pr2}$

Tags: andofthe函数fromrefiflist
2条回答

以下参数适用于任意数量的参数:

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

要计算precision和{}的调和平均值,请使用:

^{pr2}$

您的功能有两个问题:

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

只需稍微修改一下您的F1函数,并使用您定义的相同的precision和{}函数,我可以这样做:

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函数。在

相关问题 更多 >