How to Implement f1 score in Sklearn ? : Step By Step Solution

Implement f1 score in Sklearn

f1 score is the weighted average of precision and recall.  In this article, we will explore, How to implement f1 score Sklearn. In this article, We will also explore the formula for the f1 score.

 

Syntax for f1 score Sklearn –

Actually, In order to implement the f1 score matrix, we need to import the below package. As F1 score is the part of
sklearn.metrics package.

from sklearn.metrics import f1_score

Here is the complete syntax for F1 score function.

sklearn.metrics.f1_score(y_true, y_pred, *, labels=None, pos_label=1, average='binary', sample_weight=None, zero_division='warn')

Here y_true and y_pred are the required parameters. Others are optional and not required parameter.

 

The formula for f1 score –

Here is the formula for the f1 score of the predict values.

F1 = 2 * (precision * recall) / (precision + recall)

 

Implementation of f1 score Sklearn –

As I have already told you that f1 score is a model performance evaluation matrices. Hence if need to practically implement the f1 score matrices. We need a complete trained model. But if we do so, It will be too much time-consuming. Even though, it will not be topic centric. So what to do? Hey, do not worry! I have a solution for you. We can use the mocking technique to give you a real demo.

We can create two arrays. One for y_true ( real dataset outcome) and the other for y_pred ( From the model ).

y_true = [0, 1, 0, 0, 1, 0]
y_pred = [0, 1, 1, 0, 1, 1]

Now lets call the f1_score() for the final matrices for f1_score value.

f1_score(y_true, y_pred)

Here is the complete code together.

f1 score Sklearn
f1 score Sklearn

Note –

The important thing here is that we have not used the average parameter is the f1_score(). Actually, the dummy array was for binary classification. But in the case of a multi-classification problem, we need to use the average parameter with the possible values average {‘micro’, ‘macro’, ‘samples’,’ weighted’, ‘binary’} or None and default=’binary’.

I hope you must like this article, please let us know if you need some discussion on the f1_score(). You may comment below in the comment box for more discussion on f1_score() sklearn.


Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages Datasciencelearner.com, where he and his team share knowledge and help others learn more about data science.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner