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()
相关推荐
xiaopengbc7 分钟前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@13 分钟前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.16 分钟前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
SHUIPING_YANG21 分钟前
如何让dify分类器更加精准的分类?
人工智能·分类·数据挖掘
偷心伊普西隆24 分钟前
Python EXCEL 理论探究:格式转换时处理缺失值方法
python·excel
zhangfeng113333 分钟前
R 语法高亮为什么没有,是需要安装专用的编辑软件,R语言自带的R-gui 功能还是比较简单
开发语言·r语言
精灵vector1 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain