我正在使用 Python 2.7。我有两个 tsv 数据文件,我读入了两个字典,我想计算recall它们的分数,所以我需要计算tp和fn。这些是我的字典的样子:
gold = {'A11':'cat', 'A22':'cat', 'B3':'mouse'}
results = {'A2':'cat', 'B2':'dog'}
我的代码主要是迭代的gold字典,并在年底消除数字gold字典key以及results key。然后,检查键是否匹配以查找它们的值是否匹配以计算tp. 但是,我的代码似乎总是增加fn. 这是我的可运行代码:
from __future__ import division
import string
def eval():
tp=0 #true positives
fn=0 #false negatives
fp=0#false positives
gold = {'A11':'cat', 'A22':'cat', 'B3':'mouse'}
results = {'A2':'cat', 'B2':'dog'}
#iterate gold dictionary
for i,j in gold.items():
#remove the digits off gold keys
i_stripped = i.rstrip(string.digits)
#iterate results dictionary
for k,v in results.items():
#remove the digits off results keys
k_stripped = k.rstrip(string.digits)
# check if key match!
if i_stripped == k_stripped:
#check if values match then increment tp
if j == v:
tp += 1
#delete dictionary entries to avoid counting them again
del gold_copy[i]
del results_copy[k]
#get out of this loop we found a match!
break
continue
# NO match was found in the results, then consider it as fn
fn += 1 #<------ wrong calculations caused in this line
print 'tp = %.2f fn = %.2f recall = %.2f ' % (tp, fn, float(tp)/(tp+fn))
这是输出:
tp = 1.00 fn = 3.00 recall = 0.25
fn是不正确的,应该是2而不是3。如何停止fn在每次迭代中递增?任何指导将不胜感激。
谢谢,
森栏
HUX布斯
相关分类