Skip to main content
 首页 » 编程设计

python之float 在预定义函数中的行为不像 float

2025年05月04日7duanxz

我正在寻找使用预定义函数的垃圾邮件过滤器的精确度和召回率

当使用预定义函数时,我无法让它们返回值 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) 

请您参考如下方法:

您在函数中将字符串视为数字。 如果字符串不为空,则测试 bool(aString) 将始终为真。

在将有效字段传递给函数之前,或者在遍历值时在函数内将有效字段转换为 float 。

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

如果一切总是 True 那么 1/1 == 1 和 100/100 == 1

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

    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) 

然后你将只有有效的 float ,不需要弹出。