float的行为与预定义函数中的float不同

2024-09-30 02:26:54 发布

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

我正在寻找的精度和召回的垃圾邮件过滤器使用预定义的功能

当使用预定义函数时,我不能让它们返回值1.0以外的任何值。你知道吗

我知道这是不正确的,因为我应该得到一个精度为0.529411764706的结果。你知道吗

另外,我使用pop是因为由于某些原因,每个列表的第一个条目不是一个数字,所以我不能使用append(int(。。。你知道吗

功能如下:

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

这是我的密码:

import hw10_lib
from hw10_lib import precision
from hw10_lib import recall

actual = []
for line in open("/path/hw10.ref", 'r'):
    actual.append(line.strip().split('\t')[-1])
actual.pop(0)

predicted = []
for line in open("/path/hw10.hyp", 'r'):
    predicted.append(line.strip().split('\t')[-1])
predicted.pop(0)

prec = precision(actual, predicted)
rec = recall(actual, predicted)

print ('Precision: ', prec)
print ('Recall: ', rec)

Tags: andoffromreflistprecisionfilehypothesis
1条回答
网友
1楼 · 发布于 2024-09-30 02:26:54

在函数中将字符串视为数字。 如果字符串不是空的,那么Testing bool(aString)总是true。你知道吗

在将有效字段传递给函数之前,或者在值上循环时,将有效字段转换为float。你知道吗

bool("0") # True
bool("1") # True

如果一切都是真的,那么1/1==1和100/100==1

还要记住划分浮点而不是整数,以保持浮点精度。你知道吗

    for i in range(n):
        if float(hyp[i]):
            np += 1.0
            if float(ref[i]):
                ntp += 1.0
    return ntp/np

也可以将值正确地附加到原始列表中:

for line in open("/path/hw10.ref", 'r'):
    try:
        val = float(line.strip().split('\t')[-1])
    except:
        continue
    actual.append(val)

那么你将只有有效的浮动,没有必要弹出。你知道吗

相关问题 更多 >

    热门问题