Python繪制多分類ROC曲線

目錄

1 數據集介紹

1.1 數據集簡介

1.2 數據預處理

?2隨機森林分類

2.1 數據加載

2.2 參數尋優

2.3 模型訓練與評估

3 繪制十分類ROC曲線

第一步,計算每個分類的預測結果概率

第二步,畫圖數據準備

第三步,繪制十分類ROC曲線


1 數據集介紹

1.1 數據集簡介

分類數據集為某公司手機上網滿意度數據集,數據如圖所示,共7020條樣本,關于手機滿意度分類的特征有網絡覆蓋與信號強度、手機上網速度、手機上網穩定性等75個特征。

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()

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()

以及最優參數和最高得分進行分析,如下所示

###調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()

很明顯,決策樹個數設置在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()  

決策樹的深度最終設置為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))

繪制混淆矩陣:

# 混淆矩陣
from sklearn.metrics import confusion_matrix
import matplotlib.ticker as tickercm = 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()

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()

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/210986.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/210986.shtml
英文地址,請注明出處:http://en.pswp.cn/news/210986.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【數據結構】——排序篇(上)

前言:前面我們已經學過了許許多多的排序方法,如冒泡排序,選擇排序,堆排序等等,那么我們就來將排序的方法總結一下。 我們的排序方法包括以下幾種,而快速排序和歸并排序我們后面進行詳細的講解。 直接插入…

Qt實現二維碼生成和識別

一、簡介 QZxing開源庫: 生成和識別條碼和二維碼 下載地址:https://gitcode.com/mirrors/ftylitak/qzxing/tree/master 二、編譯與使用 1.下載并解壓,解壓之后如圖所示 2.編譯 打開src目錄下的QZXing.pro,選擇合適的編譯器進行編譯 最后生…

util.js

一、util.js是什么? 1、util.js是Node.js提供的一個工具庫,主要用于輔助實現JavaScript代碼的通用功能。 2、除了Node.js中內置的模塊外,util.js是Node.js中最核心的模塊之一。 3、通過util.js,開發者可以輕松實現JavaScript常…

Unity 資源管理之StreamingAssets

StreamingAssets也是Unity中特殊的文件夾,用于存放運行時可以直接訪問的資源。StreamingAssets一般存放數據或配置文件、圖片、視頻資源等。 StreamingAssets的文件路徑可以通過Application.streamingAssetsPath來獲取。 加載或訪問使用WWW類或UnityWebRequest類。…

MIT6S081-Lab2總結

大家好,我叫徐錦桐,個人博客地址為www.xujintong.com,github地址為https://github.com/xjintong。平時記錄一下學習計算機過程中獲取的知識,還有日常折騰的經驗,歡迎大家訪問。 Lab2就是了解一下xv6的系統調用流程&…

Java - Synchronized的鎖升級之路

Synchronized鎖 Synchronized在Java JVM里的實現是基于進入和退出Monitor對象來實現方法同步和代碼塊同步的 monitor enter指令是在編譯后插入到同步代碼塊的開始位置 而monitor exit是插入到方法結束處和異常處 JVM要保證每個monitor enter必須有對應的monitor exit與之配對。…

解決服務端渲染程序SSR運行時報錯: ReferenceError: document is not defined

現象: 原因: 該錯誤表明在服務端渲染 (SSR) 過程中,有一些代碼嘗試在沒有瀏覽器環境的情況下執行與瀏覽器相關的操作。這在服務端渲染期間是一個常見的問題,因為在服務端渲染期間是沒有瀏覽器 API。 解決辦法: 1. 修…

bat腳本之while

在批處理(BAT)腳本中,while循環是一種常用的控制流結構,用于在滿足特定條件的情況下重復執行一段代碼。 while循環的基本語法如下: while [ condition ] do command1 command2 ... commandN done這里的 cond…

【2023傳智杯-新增場次】第六屆傳智杯程序設計挑戰賽AB組-DEF題復盤解題分析詳解【JavaPythonC++解題筆記】

本文僅為【2023傳智杯-第二場】第六屆傳智杯程序設計挑戰賽-題目解題分析詳解的解題個人筆記,個人解題分析記錄。 本文包含:第六屆傳智杯程序設計挑戰賽題目、解題思路分析、解題代碼、解題代碼詳解 文章目錄 一.前言二.賽題題目D題題目-E題題目-F題題目-二.賽題題解D題題解-…

深入理解Sentinel系列-1.初識Sentinel

👏作者簡介:大家好,我是愛吃芝士的土豆倪,24屆校招生Java選手,很高興認識大家📕系列專欄:Spring源碼、JUC源碼、Kafka原理、分布式技術原理🔥如果感覺博主的文章還不錯的話&#xff…

待做-待補充-每個節點做事,時間,以及與角度的關系

文章目錄 待定內容紅黑樹應用場景限制什么是二叉樹遍歷遞歸遍歷1.前序遍歷 進入節點時2.中序遍歷 遍歷完左子樹回到節點。此操作需要等到所有左樹節點做完后才會做3.后序遍歷 遍歷完左右子樹回到節點。左右子樹的所有節點都做完操作后,回到當前節點才會做此操作 …

如何搭建自己的直播電商系統?

當下,傳統的圖文電商模式已經走向沒落,視頻電商備受追捧。抖音、快手、小紅書、京東、淘寶、拼多多都在發力直播電商業務,尤其是以抖音為首的直播電商備受用戶歡迎,它具有實時直播和強互動的特點,是傳統電商所不具備的…

<HarmonyOS第一課>保存應用數據【課后考核】

【習題】保存應用數據 判斷題 首選項是關系型數據庫。 錯誤(False) 應用中涉及到Student信息,如包含姓名,性別,年齡,身高等信息可以用首選項來存儲。 錯誤(False) 同一應用或進程中每個文件僅存在一個Preferences實例。 正確(T…

最長子串問題(LCS)--動態規劃解法

題目描述: 如果Z既是X的子串,又是Y的子串,則稱Z為X和Y的公共子串。 如果給定X、Y,求出最長Z及其長度。 注意:這里求的不是子序列,兩者的意思并不相同。子串要求連續,子序列并不需要。 如果想…

simulinkveristandlabview聯合仿真環境搭建

目錄 開篇廢話 軟件版本 明確需求 軟件安裝 matlab2020a veristand2020 R4 VS2017 VS2010 軟件安裝驗證 軟件資源分享 開篇廢話 推免之后接到的第一個讓人難繃的活,網上開源的軟件資料和成功的案例很少,查來查去就那么幾篇,而且版本…

SpringData

1.為什么要學習SpringData? 是因為對數據存儲的框架太多了,全部都要學習成本比較高,SpringData對這些數據存儲層做了一個統一,學習成本大大降低。

SQL命令---修改字段的數據類型

介紹 使用sql語句修改字段的數據類型。 命令 alter table 表明 modify 字段名 數據類型;例子 有一張a表,表里有一個id字段,長度為11。使用命令將長度修改為12 下面使用命令進行修改: alter table a modify id int(12) NOT NULL;下面使修…

stm32使用多串口不輸出無反應的問題(usart1、usart2)

在使用stm32c8t6單片機時,由于需要使用兩個串口usart1 、usart2。usart1用作程序燒錄、調試作用,串口2用于與其它模塊進行通信。 使用串口1時,正常工作,使用串口2時,無反應。查閱了相關資料串口2在PA2\PA3 引腳上。RX…

[僅供學習,禁止用于違法]編寫一個程序來手動設置Windows的全局代理開或關,實現對所有網絡請求攔截和數據包捕獲(抓包或VPN的應用)

文章目錄 介紹一、實現原理二、通過注冊表設置代理2.1 開啟代理2.2 關閉代理2.3 添加代理地址2.4 刪除代理設置信息 三、代碼實戰3.1 程序控制代理操作控制3.1.1 開啟全局代理3.1.2 添加代理地址3.1.3 關閉代理開關3.1.4 刪除代理信息 3.2 攔截所有請求 介紹 有一天突發奇想&am…

在git使用SSH密鑰進行github身份認證學習筆記

1.生成ssh密鑰對 官網文檔:Https://docs.github.com/zh/authentication(本節內容對應的官方文檔,不清晰的地方可參考此內容) 首先,啟動我們的git bush(在桌面右鍵,點擊 Git Bush Here &#xf…