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()
相关推荐
上单带刀不带妹4 分钟前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
im_AMBER24 分钟前
学习日志05 python
python·学习
大虫小呓29 分钟前
Python 处理 Excel 数据 pandas 和 openpyxl 哪家强?
python·pandas
哪 吒42 分钟前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
-凌凌漆-44 分钟前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼1 小时前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
军训猫猫头1 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
真的想上岸啊2 小时前
学习C++、QT---18(C++ 记事本项目的stylesheet)
开发语言·c++·学习
明天好,会的2 小时前
跨平台ZeroMQ:在Rust中使用zmq库的完整指南
开发语言·后端·rust
摸爬滚打李上进2 小时前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习