python分类指标评测

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import roc_curve, auc, confusion_matrix, \
    precision_recall_curve, average_precision_score
from sklearn.metrics import roc_auc_score
# 生成假数据
y_true = [0, 1, 0, 1, 1, 0]
y_pred = [0.2, 0.6, 0.3, 0.8, 0.2, 0.1]

# 计算AUC
fpr, tpr, thresholds = roc_curve(y_true, y_pred)
roc_auc = auc(fpr, tpr)

# 绘制ROC曲线
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label='AUC = %0.2f' % roc_auc)
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'r--')
plt.xlim([-0.1, 1.1])
plt.ylim([-0.1, 1.1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()

# 计算混淆矩阵
tn, fp, fn, tp = confusion_matrix(y_true, [1 if i > 0.5 else 0 for i in y_pred]).ravel()

# 绘制混淆矩阵图
labels = ['True Negative', 'False Positive', 'False Negative', 'True Positive']
categories = ['Negative', 'Positive']
sns.heatmap([[tn, fp], [fn, tp]], annot=True, fmt='d', xticklabels=categories, yticklabels=categories, cmap="YlGnBu")
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()

# 计算Precision-Recall曲线和AUC
precision, recall, thresholds = precision_recall_curve(y_true, y_pred)
average_precision = average_precision_score(y_true, y_pred)

# 绘制Precision-Recall曲线图
plt.step(recall, precision, color='b', alpha=0.2,
         where='post')
plt.fill_between(recall, precision, step='post', alpha=0.2,
                 color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('Precision-Recall curve: AP={0:0.2f}'.format(average_precision))
plt.show()

plt.show()
相关推荐
APItesterCris2 分钟前
TypeScript 与淘宝 API:构建类型安全的商品数据查询前端 / Node.js 服务
开发语言·php
ftpeak6 分钟前
《Cargo 参考手册》第二十一章:Cargo 包命令
开发语言·rust
可触的未来,发芽的智生7 分钟前
触摸未来2025-10-18:生成文字的小宇宙矩阵溯源
人工智能·python·神经网络·程序人生·自然语言处理
_码力全开_9 分钟前
P1005 [NOIP 2007 提高组] 矩阵取数游戏
java·c语言·c++·python·算法·矩阵·go
陈一Tender12 分钟前
JavaWeb后端实战(登录认证 & 令牌技术 & 拦截器 & 过滤器)
java·开发语言·spring boot·mysql
Camel卡蒙13 分钟前
红黑树详细介绍(五大规则、保持平衡操作、Java实现)
java·开发语言·算法
jerryinwuhan17 分钟前
机器人模拟器(python)
开发语言·python·机器人
AhriProGramming24 分钟前
Flask-SQLAlchemy精读-双语精选文章
python·算法·flask
列兵阿甘27 分钟前
知微传感Dkam系列3D相机SDK例程篇:Python获取内外参
python·数码相机·3d
孤廖39 分钟前
吃透 C++ 栈和队列:stack/queue/priority_queue 用法 + 模拟 + STL 标准实现对比
java·开发语言·数据结构·c++·人工智能·深度学习·算法