2

I have 2 functions that give out precision and recall scores, I need to make a harmonic mean function defined in the same library that uses these two scores. The functions looks like this:

here are the functions:

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

What would the harmonic mean function look like? All I have is this but I know its not right:

def F1(precision, recall):
    (2*precision*recall)/(precision+recall)
4

2 回答 2

3

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

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

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

result = hmean(precision, recall)

您的功能有两个问题:

  1. 它无法返回值。
  2. 在某些版本的 Python 上,它会对整数参数使用整数除法,从而截断结果。
于 2012-12-13T08:10:50.573 回答
0

稍微改变你的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函数。

于 2012-12-13T09:02:56.670 回答