国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python繪制多分類ROC曲線

這篇具有很好參考價值的文章主要介紹了Python繪制多分類ROC曲線。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

目錄

1 數(shù)據(jù)集介紹

1.1 數(shù)據(jù)集簡介

1.2 數(shù)據(jù)預(yù)處理

?2隨機森林分類

2.1 數(shù)據(jù)加載

2.2 參數(shù)尋優(yōu)

2.3 模型訓(xùn)練與評估

3 繪制十分類ROC曲線

第一步,計算每個分類的預(yù)測結(jié)果概率

第二步,畫圖數(shù)據(jù)準(zhǔn)備

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


Python繪制多分類ROC曲線,科研繪圖配色,python,分類,隨機森林

1 數(shù)據(jù)集介紹

1.1 數(shù)據(jù)集簡介

分類數(shù)據(jù)集為某公司手機上網(wǎng)滿意度數(shù)據(jù)集,數(shù)據(jù)如圖所示,共7020條樣本,關(guān)于手機滿意度分類的特征有網(wǎng)絡(luò)覆蓋與信號強度、手機上網(wǎng)速度、手機上網(wǎng)穩(wěn)定性等75個特征。

Python繪制多分類ROC曲線,科研繪圖配色,python,分類,隨機森林

1.2 數(shù)據(jù)預(yù)處理

常規(guī)數(shù)據(jù)處理流程,詳細(xì)內(nèi)容見上期隨機森林處理流程:

xxx 鏈接

  • 缺失值處理

  • 異常值處理

  • 數(shù)據(jù)歸一化

  • 分類特征編碼

處理完后的數(shù)據(jù)保存為?手機上網(wǎng)滿意度.csv文件(放置文末)

?2隨機森林分類

2.1 數(shù)據(jù)加載

第一步,導(dǎo)入包

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 # 引入準(zhǔn)確度評分函數(shù)
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')

第二步,加載數(shù)據(jù)

net_data = pd.read_csv('手機上網(wǎng)滿意度.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)  # 隨機數(shù)種子
print(net_data.shape)
net_data.describe()

Python繪制多分類ROC曲線,科研繪圖配色,python,分類,隨機森林

2.2 參數(shù)尋優(yōu)

第一步,對最重要的超參數(shù)n_estimators即決策樹數(shù)量進行調(diào)試,通過不同數(shù)目的樹情況下,在訓(xùn)練集和測試集上的均方根誤差來判斷

## 分析隨著樹數(shù)目的變化,在測試集和訓(xùn)練集上的預(yù)測效果
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) # 設(shè)置參數(shù)
    rfr1.fit(X_train,Y_train) # 訓(xùn)練模型
    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))

## 可視化不同數(shù)目的樹情況下,在訓(xùn)練集和測試集上的均方根誤差
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,分類,隨機森林

以及最優(yōu)參數(shù)和最高得分進行分析,如下所示

###調(diào)n_estimators參數(shù)
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] ##這句話看似很長的,其實就是找出最高得分對應(yīng)的索引
print("最優(yōu)參數(shù)以及最高得分:",ScoreAll[max_score])  
plt.figure(figsize=[20,5])
plt.plot(ScoreAll[:,0],ScoreAll[:,1],'r-o',label='最高得分',color='orange')
plt.xlabel('n_estimators參數(shù)')
plt.ylabel('分?jǐn)?shù)')
plt.grid()
plt.legend()
plt.show()

Python繪制多分類ROC曲線,科研繪圖配色,python,分類,隨機森林很明顯,決策樹個數(shù)設(shè)置在400的時候回歸森林預(yù)測模型的測試集均方根誤差最小,得分最高,效果最顯著。因此,我們通過網(wǎng)格搜索進行小范圍搜索,構(gòu)建隨機森林預(yù)測模型時選取的決策樹個數(shù)為400。

第二步,在確定決策樹數(shù)量大概范圍后,搜索決策樹的最大深度的最高得分,如下所示

# 探索max_depth的最佳參數(shù)
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("最優(yōu)參數(shù)以及最高得分:",ScoreAll[max_score])    
plt.figure(figsize=[20,5])  
plt.plot(ScoreAll[:,0],ScoreAll[:,1]) 
plt.xlabel('max_depth最佳參數(shù)')
plt.ylabel('分?jǐn)?shù)')
plt.grid()
plt.legend() 
plt.show()  

Python繪制多分類ROC曲線,科研繪圖配色,python,分類,隨機森林

決策樹的深度最終設(shè)置為10。

2.3 模型訓(xùn)練與評估

# 隨機森林 分類模型  
model = RandomForestClassifier(n_estimators=400,max_depth=10,random_state=1) # min_samples_leaf=11
# 模型訓(xùn)練
model.fit(X_train, Y_train)
# 模型預(yù)測
y_pred = model.predict(X_test)
print('訓(xùn)練集模型分?jǐn)?shù):', model.score(X_train,Y_train))
print('測試集模型分?jǐn)?shù):', model.score(X_test,Y_test))
print("訓(xùn)練集準(zhǔn)確率: %.3f" % accuracy_score(Y_train, model.predict(X_train)))
print("測試集準(zhǔn)確率: %.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曲線

第一步,計算每個分類的預(yù)測結(jié)果概率

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)

第二步,畫圖數(shù)據(jù)準(zhǔn)備

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("手機上網(wǎng)穩(wěn)定性ROC曲線和AUC數(shù)值")
plt.show()

Python繪制多分類ROC曲線,科研繪圖配色,python,分類,隨機森林文章來源地址http://www.zghlxwxcb.cn/news/detail-759850.html

到了這里,關(guān)于Python繪制多分類ROC曲線的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 【SCI繪圖】【小提琴系列1 python】繪制按分類變量分組的垂直小提琴圖

    【SCI繪圖】【小提琴系列1 python】繪制按分類變量分組的垂直小提琴圖

    本期分享:? 【SCI繪圖】【小提琴系列1 python】繪制按分類變量分組的垂直小提琴圖,文末附完整代碼 小提琴圖是一種常用的數(shù)據(jù)可視化工具,它結(jié)合了箱形圖和密度圖的特點,用于展示數(shù)據(jù)的分布情況和變化趨勢。其外形類似于小提琴,因而得名。 數(shù)據(jù)樣例: total_bill ?

    2024年04月10日
    瀏覽(23)
  • 分類模型評估指標(biāo)——準(zhǔn)確率、精準(zhǔn)率、召回率、F1、ROC曲線、AUC曲線

    分類模型評估指標(biāo)——準(zhǔn)確率、精準(zhǔn)率、召回率、F1、ROC曲線、AUC曲線

    機器學(xué)習(xí)模型需要有量化的評估指標(biāo)來評估哪些模型的效果更好。 本文將用通俗易懂的方式講解分類問題的混淆矩陣和各種評估指標(biāo)的計算公式。將要給大家介紹的評估指標(biāo)有:準(zhǔn)確率、精準(zhǔn)率、召回率、F1、ROC曲線、AUC曲線。 所有事情都需要評估好壞,尤其是量化的評估指

    2024年02月11日
    瀏覽(98)
  • ChatGPT科研繪圖(基于python)【chatgpt使用指南-python繪圖】

    ChatGPT科研繪圖(基于python)【chatgpt使用指南-python繪圖】

    chatgpt可以通過編寫Python、matlab等代碼實現(xiàn)繪圖功能。經(jīng)過試驗, 其中以Python最為高效準(zhǔn)確 ,基本不會出現(xiàn)報錯。本文以Python繪圖為例進行輔助繪圖,其他編程語言類似,希望對大家能有幫助。 假如你有一張數(shù)據(jù)圖片,可以通過圖片轉(zhuǎn)Excel將數(shù)據(jù)提取出來。例如以下網(wǎng)址 導(dǎo)出

    2024年02月05日
    瀏覽(21)
  • Python科研繪圖--Task03

    Python科研繪圖--Task03

    目錄 圖類型 關(guān)系類型圖 散點圖的例子 數(shù)據(jù)分布型圖 rugplot例子 分類數(shù)據(jù)型圖? ?編輯回歸模型分析型圖 多子圖網(wǎng)格型圖 FacetGrid() 函數(shù) ?PairGrid() 函數(shù) ?繪圖風(fēng)格、顏色主題和繪圖元素縮放比例 繪圖風(fēng)格 顏色主題 ?繪圖元素縮放比列 圖類型 關(guān)系類型圖 數(shù)據(jù)集變量間的相互

    2024年02月11日
    瀏覽(14)
  • 使用Python Seaborn繪制熱力圖(heatmap)的時候怎么改變配色

    使用Python Seaborn繪制熱力圖(heatmap)的時候怎么改變配色

    看到最近有些論文中會對Transformer encoder的attention weights進行可視化,通常會使用heatmap,我參考了一些博客,感覺已經(jīng)總結(jié)得很詳細(xì)了,例如這篇:python繪制熱度圖(heatmap)_黃思博呀的博客-CSDN博客_python heatmap 不過我覺得有一點說得不是很清楚,我看完之后還是不知道怎么可以

    2024年02月02日
    瀏覽(15)
  • SCI科研論文配圖插圖繪制推薦-博圖匯科研繪圖

    SCI科研論文配圖插圖繪制推薦-博圖匯科研繪圖

    科研論文 期刊封面圖、摘要圖、圖文摘要(Graphical Abstract)、TOC圖(Table of Contents)、插圖、配圖、原理圖、示意圖、機制圖、數(shù)據(jù)圖等的設(shè)計和繪制 ,將科研學(xué)者的idea、概念、原理等以圖表的形式展現(xiàn)出來,將藝術(shù)審美與嚴(yán)謹(jǐn)?shù)目蒲邢嘟Y(jié)合。

    2024年02月16日
    瀏覽(22)
  • 【超詳細(xì)】機器學(xué)習(xí)sklearn之分類模型評估 混淆矩陣、ROC曲線、召回率與精度、F1分?jǐn)?shù)

    【超詳細(xì)】機器學(xué)習(xí)sklearn之分類模型評估 混淆矩陣、ROC曲線、召回率與精度、F1分?jǐn)?shù)

    機器學(xué)習(xí)之分類模型的評估 學(xué)習(xí)分類模型評估的方法: 1、混淆矩陣 2、分類結(jié)果匯總 3、ROC曲線 4、召回率與精度 5、F1分?jǐn)?shù) 一、評估分類器性能的度量 1、真正(true positive, TP)或f++,對應(yīng)的是被分類模型正確預(yù)測的正樣本數(shù)。 2、假負(fù)(false negative, FN)或f±對應(yīng)的是被分類模型錯

    2023年04月08日
    瀏覽(27)
  • 3D科研繪圖與學(xué)術(shù)圖表繪制:從入門到精通

    3D科研繪圖與學(xué)術(shù)圖表繪制:從入門到精通

    ?? 個人網(wǎng)站:【工具大全】【游戲大全】【神級源碼資源網(wǎng)】 ?? 前端學(xué)習(xí)課程:??【28個案例趣學(xué)前端】【400個JS面試題】 ?? 尋找學(xué)習(xí)交流、摸魚劃水的小伙伴,請點擊【摸魚學(xué)習(xí)交流群】 3D科研繪圖和學(xué)術(shù)圖表繪制是科研和學(xué)術(shù)領(lǐng)域中不可或缺的一部分,可以幫助研究

    2024年02月08日
    瀏覽(18)
  • 《MATLAB科研繪圖與學(xué)術(shù)圖表繪制從入門到精通》

    《MATLAB科研繪圖與學(xué)術(shù)圖表繪制從入門到精通》

    解鎖MATLAB科研繪圖魅力,讓數(shù)據(jù)可視化成為你的科研利器! 1.零基礎(chǔ)快速入門:軟件操作+實戰(zhàn)案例+圖文、代碼結(jié)合講解,從入門到精通快速高效。 2.多種科研繪圖方法:科研繪圖基礎(chǔ)+變量圖形+極坐標(biāo)圖形+3D圖形+地理信息可視化等,繪圖技巧全面掌握。 3.實用性和藝術(shù)性兼

    2024年04月13日
    瀏覽(34)
  • Origin:科研繪圖與學(xué)術(shù)圖表繪制從入門到精通

    Origin:科研繪圖與學(xué)術(shù)圖表繪制從入門到精通

    Origin是一款功能強大的數(shù)據(jù)分析和科學(xué)繪圖軟件,廣泛應(yīng)用于科研、工程和技術(shù)領(lǐng)域。它提供了豐富的數(shù)據(jù)可視化工具,可以幫助用戶輕松創(chuàng)建各種類型的圖表,如折線圖、柱狀圖、散點圖、餅圖等。本文將介紹Origin科研繪圖與學(xué)術(shù)圖表繪制從入門到精通的步驟和方法,幫助

    2024年02月04日
    瀏覽(68)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包