简体   繁体   中英

How to compute precision,recall and f1 score of an balanced logistic regression model in python

i need my precision,recall and f1 score results to be like the output below

precision  0.98
recall     0.98 
f1 score   0.93

the numbers are just an example

here is my data head在此处输入图像描述

here is my code

    #training and test sample :
x1_training_data, x1_test_data, y1_training_data, y1_test_data = train_test_split(x1_data, y1_data, test_size = 0.3)

    # Estimation result:
logit_model=sm.Logit(y1_training_data,x1_training_data)
result1=logit_model.fit()
print(result1.summary2())

    # Model Evaluation:
logreg=LogisticRegression()
logreg.fit(x1_training_data,y1_training_data)
y1_pred=logreg.predict(x1_test_data)
print('Logistic regression model accuracy:{:.2f}'.format(logreg.score(x1_test_data,y1_test_data)))
print("Logistic Regression F1 Score :",f1_score(y1_test_data,logreg.predict(x1_test_data),average=None))

here is my results of the code

logistic Regression Accuracy after undersampling : 0.902297169964584
Logistic Regression F1 Score after undersampling : [0.90023556 0.9042753 ]

i had two numbers for the F1 score i wanted to be just one number and i do not know how and i tried to find a code to find out the precision or the recall and i could not find any

please help me at least with the F1 score output Thank you

From sklearn import the metrics

from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score

Split data and train the model

#training and test sample :
x1_training_data, x1_test_data, y1_training_data, y1_test_data = train_test_split(x1_data, y1_data, test_size = 0.3)

# Estimation result:
logit_model=sm.Logit(y1_training_data,x1_training_data)
result1=logit_model.fit()
print(result1.summary2())

# Model Evaluation:
logreg=LogisticRegression()
logreg.fit(x1_training_data,y1_training_data)
y1_pred=logreg.predict(x1_test_data)

Print the metrics, here for the average parameter you can change it check sklearn for details

print('precision: %.2f' % precision_score(y1_data, y1_pred,average='weighted'))
print('recall: %.2f' % recall_score(y1_data, y1_pred,average='weighted'))
print('f1_score: %.2f' % f1_score(y1_data, y1_pred,average='weighted'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM