2
\$\begingroup\$

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
asked Nov 26, 2013 at 1:59
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.

answered Nov 26, 2013 at 9:44
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.