1. 程式人生 > 其它 >python 將多個模型的ROC曲線繪製在一張圖裡(含圖例)

python 將多個模型的ROC曲線繪製在一張圖裡(含圖例)

多條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)
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)
1
函式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)
1
(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)
1
2
如果像上圖中的我一樣,把同一張圖片plt的方法legend()呼叫兩次,那麼下一個的方法中的引數就會將上一個的引數覆蓋!這種情況下,我就發現第一個方法賦值的location完全不起作用……

這個時候就需要將這個函式整合如下圖~(其實本來就是應該這麼寫的,我也不知道為啥我腦子一抽寫了兩個,可能是ggplot給我的美好印象揮之不去吧)

plt.legend(loc='lower right',fontsize=10)
1
補充
根據小夥伴的評論提問,在這裡進行一下解釋說明:

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: 隨機數種子,不同隨機數種子劃分的訓練集和測試集會有不同。
————————————————
版權宣告:本文為CSDN博主「柳奈奈」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/ylqDiana/article/details/118764019