網站首頁 編程語言 正文
多條ROC曲線繪制函數
def multi_models_roc(names, sampling_methods, colors, X_test, y_test, save=True, dpin=100): """ 將多個機器模型的roc圖輸出到一張圖上 Args: names: list, 多個模型的名稱 sampling_methods: list, 多個模型的實例化對象 save: 選擇是否將結果保存(默認為png格式) Returns: 返回圖片對象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
繪制效果
調用格式與方法
調用方法時,需要把模型本身(如clf_xx)、模型名字(如GBDT)和對應顏色(如crimson)按照順序、以列表形式傳入函數作為參數。
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')
詳細解釋和說明
1.關鍵函數
(1)plt.figure(figsize=(20, 20), dpi=dpin)
在for循環外繪制圖片的大體框架。figsize控制圖片大小,dpin控制圖片的信息量(其實可以理解為清晰度?documentation的說明是The resolution of the figure in dots-per-inch)
(2)zip()
函數用于將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。
(3)roc_curve()
fpr, tpr, thresholds = roc_curve(y_test, y_test_predprob, pos_label=1)
該函數的傳入參數為目標特征的真實值y_test和模型的預測值y_test_predprob。需要為pos_label賦值,指明正樣本的值。
該函數的返回值 fpr、tpr和thresholds 均為ndarray, 為對應每一個不同的閾值下計算出的不同的真陽性率和假陽性率。這些值,就對應著ROC圖中的各個點。
(4)auc()
plt.plot(fpr, tpr, lw=5, label='{} (AUC={:.3f})'.format(name, auc(fpr, tpr)),color = colorname)
函數auc(),傳入參數為fpr和tpr,返回結果為模型auc值,即曲線下面積值。
以上代碼在使用fpr和tpr繪制ROC曲線的同時,也確定了標簽(圖例)的內容和格式。
2. 參數解釋
(1)sampling_methods
是包含多個模型名字的list。所有模型不需要fit過再傳入函數,只需要定義好即可。
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 兩個參數用于傳入函數后計算各個模型的預測值。
y_test_predprob = method.predict_proba(X_test)[:,1] fpr, tpr, thresholds = roc_curve(y_test, y_test_predprob, pos_label=1)
如果需要繪制的是訓練集的ROC曲線,則可以在對應參數位置分別傳入X_trian和y_train即可。
(3)names 和 colors
這兩個參數均為字符串列表形式。注意,這兩個列表的值要和模型參數中的模型順序一一對應。
如有需要繪制更多的模型,只需要對應增加列表中的值即可。
需要注意的小小坑
1.同一張圖片的同一種方法只能調用一次!!!
plt.legend(loc='lower right') plt.legend(fontsize=10)
如果像上圖中的我一樣,把同一張圖片plt的方法legend()調用兩次,那么下一個的方法中的參數就會將上一個的參數覆蓋!這種情況下,我就發現第一個方法賦值的location完全不起作用……
這個時候就需要將這個函數整合如下圖~(其實本來就是應該這么寫的,我也不知道為啥我腦子一抽寫了兩個,可能是ggplot給我的美好印象揮之不去吧)
plt.legend(loc='lower right',fontsize=10)
補充
根據小伙伴的評論提問,在這里進行一下解釋說明:
1.這個函數是適用于所有數據集的,只需要導入數據集后進行訓練集和測試集的劃分即可。(我在“調用格式與方法”部分調用函數使用的是X_train 和y_train,繪制出的則是不同模型在訓練集表現的ROC曲線)
劃分訓練集和測試集的代碼如下(以使用8:2劃分訓練集測試集為例)
# 8:2劃分訓練集測試集 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:導入數據集
target:目標特征(y)
train_size:訓練集占比80%
random_state: 隨機數種子,不同隨機數種子劃分的訓練集和測試集會有不同。
總結
原文鏈接:https://blog.csdn.net/ylqDiana/article/details/118764019
相關推薦
- 2022-08-13 Redis - 時間序列數據類型的保存方案和消息隊列實現
- 2022-07-06 R語言繪制條形圖及分布密度圖代碼總結_python
- 2022-05-08 react實現原生下拉刷新_React
- 2022-11-08 云原生系列Kubernetes深度解析YAML文件使用_云其它
- 2024-02-29 UNI-APP項目在引用官方提供的Uni-App-Demo實例中的組件時應該注意的問題
- 2022-08-22 Git遠程刪除某個歷史提交記錄方法詳解_相關技巧
- 2022-10-29 python中正則表達式findall的用法實例_python
- 2022-04-04 快應用開發自定義事件 快應用層級 圖片對象Image 獲取元素的寬高
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支