Python绘制多分类ROC曲线

这篇具有很好参考价值的文章主要介绍了Python绘制多分类ROC曲线。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

1 数据集介绍

1.1 数据集简介

1.2 数据预处理

 2随机森林分类

2.1 数据加载

2.2 参数寻优

2.3 模型训练与评估

3 绘制十分类ROC曲线

第一步,计算每个分类的预测结果概率

第二步,画图数据准备

第三步,绘制十分类ROC曲线


Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

1 数据集介绍

1.1 数据集简介

分类数据集为某公司手机上网满意度数据集,数据如图所示,共7020条样本,关于手机满意度分类的特征有网络覆盖与信号强度、手机上网速度、手机上网稳定性等75个特征。

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

1.2 数据预处理

常规数据处理流程,详细内容见上期随机森林处理流程:

xxx 链接

  • 缺失值处理

  • 异常值处理

  • 数据归一化

  • 分类特征编码

处理完后的数据保存为 手机上网满意度.csv文件(放置文末)

 2随机森林分类

2.1 数据加载

第一步,导入包

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier# 随机森林回归
from sklearn.model_selection import train_test_split,GridSearchCV,cross_val_score
from sklearn.metrics import accuracy_score # 引入准确度评分函数
from sklearn.metrics import mean_squared_error
from sklearn import preprocessing
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc("font", family='Microsoft YaHei')

第二步,加载数据

net_data = pd.read_csv('手机上网满意度.csv')
Y = net_data.iloc[:,3]   
X= net_data.iloc[:, 4:]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=200)  # 随机数种子
print(net_data.shape)
net_data.describe()

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

2.2 参数寻优

第一步,对最重要的超参数n_estimators即决策树数量进行调试,通过不同数目的树情况下,在训练集和测试集上的均方根误差来判断

## 分析随着树数目的变化,在测试集和训练集上的预测效果
rfr1 = RandomForestClassifier(random_state=1)
n_estimators = np.arange(50,500,50) # 420,440,2
train_mse = []
test_mse = []
for n in n_estimators:
    rfr1.set_params(n_estimators = n) # 设置参数
    rfr1.fit(X_train,Y_train) # 训练模型
    rfr1_lab = rfr1.predict(X_train)
    rfr1_pre = rfr1.predict(X_test)
    train_mse.append(mean_squared_error(Y_train,rfr1_lab))
    test_mse.append(mean_squared_error(Y_test,rfr1_pre))

## 可视化不同数目的树情况下,在训练集和测试集上的均方根误差
plt.figure(figsize=(12,9))
plt.subplot(2,1,1)
plt.plot(n_estimators,train_mse,'r-o',label='trained MSE',color='darkgreen')
plt.xlabel('Number of trees')
plt.ylabel('MSE')
plt.grid()
plt.legend()

plt.subplot(2,1,2)
plt.plot(n_estimators,test_mse,'r-o',label='test MSE',color='darkgreen')
index = np.argmin(test_mse)
plt.annotate('MSE:'+str(round(test_mse[index],4)),
             xy=(n_estimators[index],test_mse[index]),
             xytext=(n_estimators[index]+2,test_mse[index]+0.000002),
             arrowprops=dict(facecolor='red',shrink=0.02))
plt.xlabel('Number of trees')
plt.ylabel('MSE')
plt.grid()
plt.legend()
plt.tight_layout()
plt.show()

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

以及最优参数和最高得分进行分析,如下所示

###调n_estimators参数
ScoreAll = []
for i in range(50,500,50):
    DT = RandomForestClassifier(n_estimators = i,random_state = 1) #,criterion = 'entropy'
    score = cross_val_score(DT,X_train,Y_train,cv=6).mean()
    ScoreAll.append([i,score])
ScoreAll = np.array(ScoreAll)

max_score = np.where(ScoreAll==np.max(ScoreAll[:,1]))[0][0] ##这句话看似很长的,其实就是找出最高得分对应的索引
print("最优参数以及最高得分:",ScoreAll[max_score])  
plt.figure(figsize=[20,5])
plt.plot(ScoreAll[:,0],ScoreAll[:,1],'r-o',label='最高得分',color='orange')
plt.xlabel('n_estimators参数')
plt.ylabel('分数')
plt.grid()
plt.legend()
plt.show()

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林很明显,决策树个数设置在400的时候回归森林预测模型的测试集均方根误差最小,得分最高,效果最显著。因此,我们通过网格搜索进行小范围搜索,构建随机森林预测模型时选取的决策树个数为400。

第二步,在确定决策树数量大概范围后,搜索决策树的最大深度的最高得分,如下所示

# 探索max_depth的最佳参数
ScoreAll = []  
for i in range(4,14,2):  
    DT = RandomForestClassifier(n_estimators = 400,random_state = 1,max_depth =i ) #,criterion = 'entropy'  
    score = cross_val_score(DT,X_train,Y_train,cv=6).mean()  
    ScoreAll.append([i,score])  
ScoreAll = np.array(ScoreAll)  
    
max_score = np.where(ScoreAll==np.max(ScoreAll[:,1]))[0][0] 
print("最优参数以及最高得分:",ScoreAll[max_score])    
plt.figure(figsize=[20,5])  
plt.plot(ScoreAll[:,0],ScoreAll[:,1]) 
plt.xlabel('max_depth最佳参数')
plt.ylabel('分数')
plt.grid()
plt.legend() 
plt.show()  

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

决策树的深度最终设置为10。

2.3 模型训练与评估

# 随机森林 分类模型  
model = RandomForestClassifier(n_estimators=400,max_depth=10,random_state=1) # min_samples_leaf=11
# 模型训练
model.fit(X_train, Y_train)
# 模型预测
y_pred = model.predict(X_test)
print('训练集模型分数:', model.score(X_train,Y_train))
print('测试集模型分数:', model.score(X_test,Y_test))
print("训练集准确率: %.3f" % accuracy_score(Y_train, model.predict(X_train)))
print("测试集准确率: %.3f" % accuracy_score(Y_test, y_pred))

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

绘制混淆矩阵:

# 混淆矩阵
from sklearn.metrics import confusion_matrix
import matplotlib.ticker as ticker

cm = confusion_matrix(Y_test, y_pred,labels=[1,2,3,4,5,6,7,8,9,10]) # ,
print('混淆矩阵:\n', cm)
labels=['1','2','3','4','5','6','7','8','9','10']
from sklearn.metrics import ConfusionMatrixDisplay
cm_display = ConfusionMatrixDisplay(cm,display_labels=labels).plot()

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林

3 绘制十分类ROC曲线

第一步,计算每个分类的预测结果概率

from sklearn.metrics import roc_curve,auc
df = pd.DataFrame()
pre_score = model.predict_proba(X_test)
df['y_test'] = Y_test.to_list()

df['pre_score1'] = pre_score[:,0]
df['pre_score2'] = pre_score[:,1]
df['pre_score3'] = pre_score[:,2]
df['pre_score4'] = pre_score[:,3]
df['pre_score5'] = pre_score[:,4]
df['pre_score6'] = pre_score[:,5]
df['pre_score7'] = pre_score[:,6]
df['pre_score8'] = pre_score[:,7]
df['pre_score9'] = pre_score[:,8]
df['pre_score10'] = pre_score[:,9]

pre1 = df['pre_score1']
pre1 = np.array(pre1)

pre2 = df['pre_score2']
pre2 = np.array(pre2)

pre3 = df['pre_score3']
pre3 = np.array(pre3)

pre4 = df['pre_score4']
pre4 = np.array(pre4)

pre5 = df['pre_score5']
pre5 = np.array(pre5)

pre6 = df['pre_score6']
pre6 = np.array(pre6)

pre7 = df['pre_score7']
pre7 = np.array(pre7)

pre8 = df['pre_score8']
pre8 = np.array(pre8)

pre9 = df['pre_score9']
pre9 = np.array(pre9)

pre10 = df['pre_score10']
pre10 = np.array(pre10)

第二步,画图数据准备

y_list = df['y_test'].to_list()
pre_list=[pre1,pre2,pre3,pre4,pre5,pre6,pre7,pre8,pre9,pre10]

lable_names=['1','2','3','4','5','6','7','8','9','10']
colors1 = ["r","b","g",'gold','pink','y','c','m','orange','chocolate']
colors2 = "skyblue"# "mistyrose","skyblue","palegreen"
my_list = []
linestyles =["-", "--", ":","-", "--", ":","-", "--", ":","-"]

第三步,绘制十分类ROC曲线

plt.figure(figsize=(12,5),facecolor='w')
for i in range(10):
    roc_auc = 0
     #添加文本信息
    if i==0:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=1)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.3, 0.01, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==1:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=2)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.3, 0.11, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==2:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=3)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.3, 0.21, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==3:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=4)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.3, 0.31, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==4:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=5)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.3, 0.41, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==5:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=6)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.6, 0.01, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==6:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=7)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.6, 0.11, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==7:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=8)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.6, 0.21, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==8:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=9)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.6, 0.31, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    elif i==9:
        fpr, tpr, threshold = roc_curve(y_list,pre_list[i],pos_label=10)
        # 计算AUC的值
        roc_auc = auc(fpr, tpr)
        plt.text(0.6, 0.41, "class "+lable_names[i]+' :ROC curve (area = %0.2f)' % roc_auc)
    my_list.append(roc_auc)
    # 添加ROC曲线的轮廓
    plt.plot(fpr, tpr, color = colors1[i],linestyle = linestyles[i],linewidth = 3,
             label = "class:"+lable_names[i])  #  lw = 1,
    #绘制面积图
    plt.stackplot(fpr, tpr, colors=colors2, alpha = 0.5,edgecolor = colors1[i]) #  alpha = 0.5,
   
# 添加对角线
plt.plot([0, 1], [0, 1], color = 'black', linestyle = '--',linewidth = 3)
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
plt.grid()
plt.legend()
plt.title("手机上网稳定性ROC曲线和AUC数值")
plt.show()

Python绘制多分类ROC曲线,科研绘图配色,python,分类,随机森林文章来源地址https://www.toymoban.com/news/detail-759850.html

到了这里,关于Python绘制多分类ROC曲线的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【SCI绘图】【小提琴系列1 python】绘制按分类变量分组的垂直小提琴图

    本期分享:  【SCI绘图】【小提琴系列1 python】绘制按分类变量分组的垂直小提琴图,文末附完整代码 小提琴图是一种常用的数据可视化工具,它结合了箱形图和密度图的特点,用于展示数据的分布情况和变化趋势。其外形类似于小提琴,因而得名。 数据样例: total_bill  

    2024年04月10日
    浏览(33)
  • 分类模型评估指标——准确率、精准率、召回率、F1、ROC曲线、AUC曲线

    机器学习模型需要有量化的评估指标来评估哪些模型的效果更好。 本文将用通俗易懂的方式讲解分类问题的混淆矩阵和各种评估指标的计算公式。将要给大家介绍的评估指标有:准确率、精准率、召回率、F1、ROC曲线、AUC曲线。 所有事情都需要评估好坏,尤其是量化的评估指

    2024年02月11日
    浏览(38)
  • ChatGPT科研绘图(基于python)【chatgpt使用指南-python绘图】

    chatgpt可以通过编写Python、matlab等代码实现绘图功能。经过试验, 其中以Python最为高效准确 ,基本不会出现报错。本文以Python绘图为例进行辅助绘图,其他编程语言类似,希望对大家能有帮助。 假如你有一张数据图片,可以通过图片转Excel将数据提取出来。例如以下网址 导出

    2024年02月05日
    浏览(42)
  • Python科研绘图--Task03

    目录 图类型 关系类型图 散点图的例子 数据分布型图 rugplot例子 分类数据型图  ​编辑回归模型分析型图 多子图网格型图 FacetGrid() 函数  PairGrid() 函数  绘图风格、颜色主题和绘图元素缩放比例 绘图风格 颜色主题  绘图元素缩放比列 图类型 关系类型图 数据集变量间的相互

    2024年02月11日
    浏览(23)
  • 使用Python Seaborn绘制热力图(heatmap)的时候怎么改变配色

    看到最近有些论文中会对Transformer encoder的attention weights进行可视化,通常会使用heatmap,我参考了一些博客,感觉已经总结得很详细了,例如这篇:python绘制热度图(heatmap)_黄思博呀的博客-CSDN博客_python heatmap 不过我觉得有一点说得不是很清楚,我看完之后还是不知道怎么可以

    2024年02月02日
    浏览(39)
  • SCI科研论文配图插图绘制推荐-博图汇科研绘图

    科研论文 期刊封面图、摘要图、图文摘要(Graphical Abstract)、TOC图(Table of Contents)、插图、配图、原理图、示意图、机制图、数据图等的设计和绘制 ,将科研学者的idea、概念、原理等以图表的形式展现出来,将艺术审美与严谨的科研相结合。

    2024年02月16日
    浏览(31)
  • 【超详细】机器学习sklearn之分类模型评估 混淆矩阵、ROC曲线、召回率与精度、F1分数

    机器学习之分类模型的评估 学习分类模型评估的方法: 1、混淆矩阵 2、分类结果汇总 3、ROC曲线 4、召回率与精度 5、F1分数 一、评估分类器性能的度量 1、真正(true positive, TP)或f++,对应的是被分类模型正确预测的正样本数。 2、假负(false negative, FN)或f±对应的是被分类模型错

    2023年04月08日
    浏览(78)
  • 3D科研绘图与学术图表绘制:从入门到精通

    💂 个人网站:【工具大全】【游戏大全】【神级源码资源网】 🤟 前端学习课程:👉【28个案例趣学前端】【400个JS面试题】 💅 寻找学习交流、摸鱼划水的小伙伴,请点击【摸鱼学习交流群】 3D科研绘图和学术图表绘制是科研和学术领域中不可或缺的一部分,可以帮助研究

    2024年02月08日
    浏览(37)
  • Origin:科研绘图与学术图表绘制从入门到精通

    Origin是一款功能强大的数据分析和科学绘图软件,广泛应用于科研、工程和技术领域。它提供了丰富的数据可视化工具,可以帮助用户轻松创建各种类型的图表,如折线图、柱状图、散点图、饼图等。本文将介绍Origin科研绘图与学术图表绘制从入门到精通的步骤和方法,帮助

    2024年02月04日
    浏览(88)
  • 《MATLAB科研绘图与学术图表绘制从入门到精通》

    解锁MATLAB科研绘图魅力,让数据可视化成为你的科研利器! 1.零基础快速入门:软件操作+实战案例+图文、代码结合讲解,从入门到精通快速高效。 2.多种科研绘图方法:科研绘图基础+变量图形+极坐标图形+3D图形+地理信息可视化等,绘图技巧全面掌握。 3.实用性和艺术性兼

    2024年04月13日
    浏览(52)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包