I am trying to implement the F1 score shown here in Python.
The inputs for my function are a list of predictions and a list of actual correct values. I thought that the most efficient way of calculating the number of true positive, false negatives and false positives would be to convert the two lists into two sets then use set intersection and differences to find the quantities of interest. Here is my code
def F1_score(tags,predicted):
tags=set(tags)
predicted=set(predicted)
tp=len(tags.intersection(predicted))
fp=len(predicted.difference(tags))
fn=len(tags.difference(predicted))
if tp>0:
precision=float(tp)/(tp+fp)
recall=float(tp)/(tp+fn)
return 2*((precision*recall)/(precision+recall))
else:
return 0