Skip to main content
 首页 » 编程设计

python之绘制 K 折交叉验证的 ROC 曲线

2024年11月01日8kevingrace

我正在处理一个不平衡的数据集。在应用 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 曲线的代码是否正确。

请您参考如下方法:

The problem is that I do not clearly understand cross-validation. In the for loop range, I have passed the training sets of X and y variables. Does cross-validation work like this?

撇开 SMOTE 和不平衡问题不谈,它们不包含在您的代码中,您的程序看起来是正确的。

更详细地说,对于您的每一个 n_splits=10:

  • 您创建train 和test 折叠

  • 您使用 train fold 拟合模型:

      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 拆分开始,正如您所做的那样,在类不平衡情况下变得必不可少):

  • 创建train 和test 折叠
  • 使用 SMOTE 对您的 train 折叠进行上采样
  • 使用上采样的 train fold 拟合模型
  • 使用test 折叠(未上采样)预测概率

有关基本原理的详细信息,请参阅数据科学 SE 线程中自己的答案 Why you shouldn't upsample before cross validation .