簡體   English   中英

繪制 K 折交叉驗證的 ROC 曲線

[英]Plotting the ROC curve of K-fold Cross Validation

我正在處理不平衡的數據集。 在應用 ML 模型之前,將數據集拆分為測試集和訓練集后,我已應用 SMOTE 算法來平衡數據集。 我想應用交叉驗證並繪制每個折疊的 ROC 曲線,顯示每個折疊的 AUC,並在圖中顯示 AUC 的平均值。 我將重采樣的訓練集變量命名為 X_train_res 和 y_train_res,以下是代碼:

cv = StratifiedKFold(n_splits=10)
classifier = SVC(kernel='sigmoid',probability=True,random_state=0)

tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
plt.figure(figsize=(10,10))
i = 0
for train, test in cv.split(X_train_res, y_train_res):
    probas_ = classifier.fit(X_train_res[train], y_train_res[train]).predict_proba(X_train_res[test])
    # Compute ROC curve and area the curve
    fpr, tpr, thresholds = roc_curve(y_train_res[test], probas_[:, 1])
    tprs.append(interp(mean_fpr, fpr, tpr))
    tprs[-1][0] = 0.0
    roc_auc = auc(fpr, tpr)
    aucs.append(roc_auc)
    plt.plot(fpr, tpr, lw=1, alpha=0.3,
             label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))

    i += 1
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
         label='Chance', alpha=.8)

mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
plt.plot(mean_fpr, mean_tpr, color='b',
         label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
         lw=2, alpha=.8)

std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                 label=r'$\pm$ 1 std. dev.')

plt.xlim([-0.01, 1.01])
plt.ylim([-0.01, 1.01])
plt.xlabel('False Positive Rate',fontsize=18)
plt.ylabel('True Positive Rate',fontsize=18)
plt.title('Cross-Validation ROC of SVM',fontsize=18)
plt.legend(loc="lower right", prop={'size': 15})
plt.show()

以下是輸出:

在此處輸入圖片說明

請告訴我用於繪制交叉驗證的 ROC 曲線的代碼是否正確。

問題是我不清楚交叉驗證。 在 for 循環范圍內,我已經通過了 X 和 y 變量的訓練集。 交叉驗證是這樣工作的嗎?

將 SMOTE 和不平衡問題放在一邊,它們未包含在您的代碼中,您的過程看起來是正確的。

更詳細地說,對於你的每一個n_splits=10

  • 您創建traintest折疊

  • 您使用train折疊擬合模型:

     classifier.fit(X_train_res[train], y_train_res[train])
  • 然后您使用test折疊預測概率:

     predict_proba(X_train_res[test])

這正是交叉驗證背后的想法。

因此,由於您有n_splits=10 ,您將獲得 10 條 ROC 曲線和各自的 AUC 值(及其平均值),完全符合預期。

但是

由於類不平衡的必要性(SMOTE)采樣改變了正確的程序,並把你的整個過程不正確的:你應該上采樣您最初的數據集; 相反,您需要將上采樣過程合並到 CV 過程中。

因此,這里每個n_splits的正確程序變為(請注意,從分層 CV 拆分開始,正如您所做的那樣,在類不平衡情況下變得必不可少):

  • 創建traintest折疊
  • 使用 SMOTE 對您的train折疊進行上采樣
  • 使用上采樣train折疊擬合模型
  • 使用test折疊預測概率(未上采樣)

有關基本原理的詳細信息,請參閱 Data Science SE 線程中為什么您不應該在交叉驗證之前上采樣中的自己的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM