# Implementing F1 score

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


## 1 Answer

To compute the length of a set difference, you only need to subtract the length of the intersection from the length of the set. You could make use of the intersection when computing the differences. Subtracting the intersection gives the same result but processes fewer elements.

tags = set(tags)
predicted = set(predicted)

tp = len(tags & predicted)
fp = len(predicted) - tp
fn = len(tags) - tp


Note that I added spaces around operators to improve readability. I also used the & operator instead of the intersection method as a matter of preference.