Python 留一交叉验证的过采样

Python 留一交叉验证的过采样,python,machine-learning,roc,precision-recall,oversampling,Python,Machine Learning,Roc,Precision Recall,Oversampling,我正在为我的研究项目处理一个极其不平衡的数据集,总共有44个样本。这是一个二元分类问题,有3/44个少数类样本,我使用的是遗漏交叉验证。如果我在LOOCV循环之前对整个数据集进行SMOTE过采样,ROC曲线的预测精度和AUC分别接近90%和0.9。然而,如果我只对LOOCV循环内的训练集进行过采样(这恰好是一种更符合逻辑的方法),ROC曲线的AUC将降至0.3 我还尝试了精确回忆曲线和分层k-折叠交叉验证,但在循环内外过采样的结果中面临类似的区别。 请告诉我什么是进行过采样的正确位置,并尽可能解

我正在为我的研究项目处理一个极其不平衡的数据集,总共有44个样本。这是一个二元分类问题,有3/44个少数类样本,我使用的是遗漏交叉验证。如果我在LOOCV循环之前对整个数据集进行SMOTE过采样,ROC曲线的预测精度和AUC分别接近90%和0.9。然而,如果我只对LOOCV循环内的训练集进行过采样(这恰好是一种更符合逻辑的方法),ROC曲线的AUC将降至0.3

我还尝试了精确回忆曲线和分层k-折叠交叉验证,但在循环内外过采样的结果中面临类似的区别。 请告诉我什么是进行过采样的正确位置,并尽可能解释其区别

环路内的过采样:-

i=0
acc_dec = 0
y_test_dec=[] #Store y_test for every split
y_pred_dec=[] #Store probablity for positive label for every split

for train, test in loo.split(X):    #Leave One Out Cross Validation
    #Create training and test sets for split indices
    X_train = X.loc[train]  
    y_train = Y.loc[train]
    X_test = X.loc[test]
    y_test = Y.loc[test]

    #oversampling minority class using SMOTE technique
    sm = SMOTE(sampling_strategy='minority',k_neighbors=1)
    X_res, y_res = sm.fit_resample(X_train, y_train)

    #KNN
    clf = KNeighborsClassifier(n_neighbors=5) 
    clf = clf.fit(X_res,y_res)
    y_pred = clf.predict(X_test)
    acc_dec = acc_dec +  metrics.accuracy_score(y_test, y_pred)
    y_test_dec.append(y_test.to_numpy()[0])
    y_pred_dec.append(clf.predict_proba(X_test)[:,1][0])
    i+=1

# Compute ROC curve and ROC area for each class
fpr,tpr,threshold=metrics.roc_curve(y_test_dec,y_pred_dec,pos_label=1)
roc_auc = metrics.auc(fpr, tpr)
print(str(acc_dec/i*100)+"%")
AUC:0.25

准确率:68.1%

环路外的过采样:

acc_dec=0 #accuracy for decision tree classifier
y_test_dec=[] #Store y_test for every split
y_pred_dec=[] #Store probablity for positive label for every split
i=0
#Oversampling before the loop
sm = SMOTE(k_neighbors=1)
X, Y = sm.fit_resample(X, Y)   
X=pd.DataFrame(X)
Y=pd.DataFrame(Y)
for train, test in loo.split(X):    #Leave One Out Cross Validation

    #Create training and test sets for split indices
    X_train = X.loc[train]  
    y_train = Y.loc[train]
    X_test = X.loc[test]
    y_test = Y.loc[test]

    #KNN
    clf = KNeighborsClassifier(n_neighbors=5) 
    clf = clf.fit(X_res,y_res)
    y_pred = clf.predict(X_test)
    acc_dec = acc_dec +  metrics.accuracy_score(y_test, y_pred)
    y_test_dec.append(y_test.to_numpy()[0])
    y_pred_dec.append(clf.predict_proba(X_test)[:,1][0])
    i+=1

# Compute ROC curve and ROC area for each class
fpr,tpr,threshold=metrics.roc_curve(y_test_dec,y_pred_dec,pos_label=1)
roc_auc = metrics.auc(fpr, tpr)
print(str(acc_dec/i*100)+"%")
AUC:0.99

准确率:90.24%

这两种方法如何导致如此不同的结果?我应该遵循什么?

在分割数据之前进行上采样(如SMOTE)意味着测试集中存在有关训练集的信息。这有时被称为“泄漏”。不幸的是,您的第一次设置是正确的

解决这个问题