I came across a weird issue. The error message is :
global name 'id2tag' is not defined.
I have read this post Accessing class variables from a list comprehension in the class definition. But obviously id2tag
is not a class variable. The code is listed below.
class evaluater:
def evaluate_topk(self, ground_truth_dict, predicted_dict, setting_name, setting, data,
eval_root_dir = './', file_name = 'result',k = 5,output_entry = 100 ):
#this part of code is not relevant
recall = {}
for key, ground_truth in ground_truth_dict.items():
recall[key] = recall_at_k(ground_truth, predicted_dict[key])
mean_recall = np.mean([value for key,value in recall.items()])
filepath = eval_root_dir + file_name
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
#HERE IS WHERE id2tag DEFINED
id2tag = {row[0]:row[1] for row in data[config.TYPE_TAG] }
with open( filepath , 'a' ) as file:
for itemid in sorted(ground_truth_dict.keys())[1:100]:
file.write(str(itemid) + '\n')
file.write('gnd:'+str([id2tag[id] for id in ground_truth_dict[itemid]] ) + '\n')
file.write('prt' + str([ id2tag[id] for id in predicted_dict[itemid]]) + '\n' )
#if i use the below code instead, then would be fine
#gnd_tags = []
#prt_tags = []
#for id in ground_truth_dict[itemid]:
# gnd_tags.append(id2tag[id])
#
#for id in predicted_dict[itemid]:
# prt_tags.append(id2tag[id])
#
#file.write('gnd:'+str( gnd_tags ) + '\n')
#file.write('prt' + str(prt_tags) + '\n' )
return mean_recall