日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python如何將多個(gè)模型的ROC曲線繪制在一張圖(含圖例)_python

作者:柳奈奈 ? 更新時(shí)間: 2022-04-27 編程語(yǔ)言

多條ROC曲線繪制函數(shù)

 def multi_models_roc(names, sampling_methods, colors, X_test, y_test, save=True, dpin=100):
        """
        將多個(gè)機(jī)器模型的roc圖輸出到一張圖上
        
        Args:
            names: list, 多個(gè)模型的名稱
            sampling_methods: list, 多個(gè)模型的實(shí)例化對(duì)象
            save: 選擇是否將結(jié)果保存(默認(rèn)為png格式)
            
        Returns:
            返回圖片對(duì)象plt
        """
        plt.figure(figsize=(20, 20), dpi=dpin)

        for (name, method, colorname) in zip(names, sampling_methods, colors):
            
            method.fit(X_train, y_train)
            y_test_preds = method.predict(X_test)
            y_test_predprob = method.predict_proba(X_test)[:,1]
            fpr, tpr, thresholds = roc_curve(y_test, y_test_predprob, pos_label=1)
            
            plt.plot(fpr, tpr, lw=5, label='{} (AUC={:.3f})'.format(name, auc(fpr, tpr)),color = colorname)
            plt.plot([0, 1], [0, 1], '--', lw=5, color = 'grey')
            plt.axis('square')
            plt.xlim([0, 1])
            plt.ylim([0, 1])
            plt.xlabel('False Positive Rate',fontsize=20)
            plt.ylabel('True Positive Rate',fontsize=20)
            plt.title('ROC Curve',fontsize=25)
            plt.legend(loc='lower right',fontsize=20)

        if save:
            plt.savefig('multi_models_roc.png')
            
        return plt

繪制效果

調(diào)用格式與方法

調(diào)用方法時(shí),需要把模型本身(如clf_xx)、模型名字(如GBDT)和對(duì)應(yīng)顏色(如crimson)按照順序、以列表形式傳入函數(shù)作為參數(shù)。

names = ['Logistic Regression',
         'Random Forest',
         'XGBoost',
         'AdaBoost',
         'GBDT',
         'LGBM']

sampling_methods = [clf_lr,
                    clf_rf,
                    clf_xgb,
                    clf_adb,
                    clf_gbdt,
                    clf_lgbm
                   ]

colors = ['crimson',
          'orange',
          'gold',
          'mediumseagreen',
          'steelblue', 
          'mediumpurple'  
         ]

#ROC curves
train_roc_graph = multi_models_roc(names, sampling_methods, colors, X_train, y_train, save = True)
train_roc_graph.savefig('ROC_Train_all.png')

詳細(xì)解釋和說(shuō)明

1.關(guān)鍵函數(shù)

(1)plt.figure(figsize=(20, 20), dpi=dpin)

在for循環(huán)外繪制圖片的大體框架。figsize控制圖片大小,dpin控制圖片的信息量(其實(shí)可以理解為清晰度?documentation的說(shuō)明是The resolution of the figure in dots-per-inch)

(2)zip()

函數(shù)用于將可迭代的對(duì)象作為參數(shù),將對(duì)象中對(duì)應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的列表。

(3)roc_curve()

fpr, tpr, thresholds = roc_curve(y_test, y_test_predprob, pos_label=1)

該函數(shù)的傳入?yún)?shù)為目標(biāo)特征的真實(shí)值y_test和模型的預(yù)測(cè)值y_test_predprob。需要為pos_label賦值,指明正樣本的值。

該函數(shù)的返回值 fpr、tpr和thresholds 均為ndarray, 為對(duì)應(yīng)每一個(gè)不同的閾值下計(jì)算出的不同的真陽(yáng)性率和假陽(yáng)性率。這些值,就對(duì)應(yīng)著ROC圖中的各個(gè)點(diǎn)。

(4)auc()

 plt.plot(fpr, tpr, lw=5, label='{} (AUC={:.3f})'.format(name, auc(fpr, tpr)),color = colorname)

函數(shù)auc(),傳入?yún)?shù)為fpr和tpr,返回結(jié)果為模型auc值,即曲線下面積值。

以上代碼在使用fpr和tpr繪制ROC曲線的同時(shí),也確定了標(biāo)簽(圖例)的內(nèi)容和格式。

2. 參數(shù)解釋

(1)sampling_methods

是包含多個(gè)模型名字的list。所有模型不需要fit過(guò)再傳入函數(shù),只需要定義好即可。

clf = RandomForestClassifier(n_estimators = 100, max_depth=3, min_samples_split=0.2, random_state=0)

(2)X_test, y_test

X_test 和 y_test 兩個(gè)參數(shù)用于傳入函數(shù)后計(jì)算各個(gè)模型的預(yù)測(cè)值。

y_test_predprob = method.predict_proba(X_test)[:,1]
fpr, tpr, thresholds = roc_curve(y_test, y_test_predprob, pos_label=1)

如果需要繪制的是訓(xùn)練集的ROC曲線,則可以在對(duì)應(yīng)參數(shù)位置分別傳入X_trian和y_train即可。

(3)names 和 colors

這兩個(gè)參數(shù)均為字符串列表形式。注意,這兩個(gè)列表的值要和模型參數(shù)中的模型順序一一對(duì)應(yīng)。

如有需要繪制更多的模型,只需要對(duì)應(yīng)增加列表中的值即可。

需要注意的小小坑

1.同一張圖片的同一種方法只能調(diào)用一次!!!

plt.legend(loc='lower right')
plt.legend(fontsize=10)

如果像上圖中的我一樣,把同一張圖片plt的方法legend()調(diào)用兩次,那么下一個(gè)的方法中的參數(shù)就會(huì)將上一個(gè)的參數(shù)覆蓋!這種情況下,我就發(fā)現(xiàn)第一個(gè)方法賦值的location完全不起作用……

這個(gè)時(shí)候就需要將這個(gè)函數(shù)整合如下圖~(其實(shí)本來(lái)就是應(yīng)該這么寫(xiě)的,我也不知道為啥我腦子一抽寫(xiě)了兩個(gè),可能是ggplot給我的美好印象揮之不去吧)

plt.legend(loc='lower right',fontsize=10)

補(bǔ)充

根據(jù)小伙伴的評(píng)論提問(wèn),在這里進(jìn)行一下解釋說(shuō)明:

1.這個(gè)函數(shù)是適用于所有數(shù)據(jù)集的,只需要導(dǎo)入數(shù)據(jù)集后進(jìn)行訓(xùn)練集和測(cè)試集的劃分即可。(我在“調(diào)用格式與方法”部分調(diào)用函數(shù)使用的是X_train 和y_train,繪制出的則是不同模型在訓(xùn)練集表現(xiàn)的ROC曲線)

劃分訓(xùn)練集和測(cè)試集的代碼如下(以使用8:2劃分訓(xùn)練集測(cè)試集為例)

# 8:2劃分訓(xùn)練集測(cè)試集
X, y = df.drop(target,axis=1), df[target]
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=0)

df:導(dǎo)入數(shù)據(jù)集

target:目標(biāo)特征(y)

train_size:訓(xùn)練集占比80%

random_state: 隨機(jī)數(shù)種子,不同隨機(jī)數(shù)種子劃分的訓(xùn)練集和測(cè)試集會(huì)有不同。

總結(jié)

原文鏈接:https://blog.csdn.net/ylqDiana/article/details/118764019

欄目分類
最近更新