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()
相关推荐
合作小小程序员小小店23 分钟前
SDN安全开发环境中常见的框架,工具,第三方库,mininet常见指令介绍
python·安全·生成对抗网络·网络安全·网络攻击模型
后台开发者Ethan27 分钟前
Python需要了解的一些知识
开发语言·人工智能·python
北京_宏哥36 分钟前
Python零基础从入门到精通详细教程11 - python数据类型之数字(Number)-浮点型(float)详解
前端·python·面试
盼小辉丶1 小时前
PyTorch生成式人工智能——使用MusicGen生成音乐
pytorch·python·深度学习·生成模型
常利兵1 小时前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
幼稚园的山代王1 小时前
Kotlin-基础语法练习一
android·开发语言·kotlin
重生成为编程大王2 小时前
Java ConcurrentHashMap 深度解析
java·开发语言
tanyongxi662 小时前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
遗憾皆是温柔2 小时前
24. 什么是不可变对象,好处是什么
java·开发语言·面试·学习方法
wearegogog1232 小时前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互