sklearn 计算 precision、recall、auc、F1 score

本文介绍如何使用Python的Scikit-learn库计算机器学习模型的AUC、Precision、Recall和F1分数,并通过绘制PR曲线确定最佳阈值。通过生成随机数据进行演示,展示了如何调整阈值以优化F1分数。
import numpy as np
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import roc_auc_score
from sklearn.metrics import precision_recall_curve
from numpy.random import random
import matplotlib.pyplot as plt
%matplotlib inline

生成数据

N = 100
y_score = [random() for i in range(N)]
y_pred = [int(y_score[i]>0.5) for i in range(N)]
y_true = [int(y_score[i]>0.4) if random()>0.5 else 0 for i in range(N)]
plt.plot(y_pred,'.r',label='pred')
plt.plot(y_true,'.b',label='true')
plt.legend()
plt.show()

在这里插入图片描述
计算 AUC, Precision, Recall, F1

prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average="binary")
auc = roc_auc_score(y_true, y_score)
print("AUC: %.4f Prec: %.4f Rec: %.4f F1: %.4f"%(auc, prec, rec, f1))

'''
AUC: 0.7640 Prec: 0.5417 Rec: 0.7429 F1: 0.6265
'''

根据 F1 score 找出最佳阈值

def return_best_thr(y_true, y_score):
    precs, recs, thrs = precision_recall_curve(y_true, y_score)
    
    plt.plot(recs,precs)
    plt.title('PR curve')
    plt.show()
    
    f1s = 2 * precs * recs / (precs + recs)
    f1s = f1s[:-1]
    thrs = thrs[~np.isnan(f1s)]
    f1s = f1s[~np.isnan(f1s)]
    best_thr = thrs[np.argmax(f1s)]
    return best_thr

print('best threshold: ',return_best_thr(y_true, y_score))
'''
best threshold:  0.4036266180809812
'''

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值