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):



    if tp>0:

        return 2*((precision*recall)/(precision+recall))
        return 0

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.