进行“离开一个组出去”交叉验证时如何应用过采样?

npm*_*npm 6 python machine-learning pandas scikit-learn cross-validation

我正在处理用于分类的不平衡数据,并且之前尝试使用综合少数族裔过采样技术(SMOTE)对培训数据进行过采样。但是,这一次我认为我还需要使用“离开一个组出去”(LOGO)交叉验证,因为我想在每个简历上都留出一个主题。

我不确定我能否很好地解释它,但是据我所知,要使用SMOTE进行k折CV,我们可以在每一折上循环进行SMOTE,正如我在另一篇文章中的代码中所看到的那样。以下是在K折CV上实施SMOTE的示例。

from sklearn.model_selection import KFold
from imblearn.over_sampling import SMOTE
from sklearn.metrics import f1_score

kf = KFold(n_splits=5)

for fold, (train_index, test_index) in enumerate(kf.split(X), 1):
    X_train = X[train_index]
    y_train = y[train_index]  
    X_test = X[test_index]
    y_test = y[test_index]  
    sm = SMOTE()
    X_train_oversampled, y_train_oversampled = sm.fit_sample(X_train, y_train)
    model = ...  # classification model example
    model.fit(X_train, y_train)  
    y_pred = model.predict(X_test)
    print(f'For fold {fold}:')
    print(f'Accuracy: {model.score(X_test, y_test)}')
    print(f'f-score: {f1_score(y_test, y_pred)}')
Run Code Online (Sandbox Code Playgroud)

没有SMOTE,我试图这样做来做LOGO CV。但是通过这样做,我将使用超不平衡数据集。

X = X
y = np.array(df.loc[:, df.columns == 'label'])
groups = df["cow_id"].values #because I want to leave cow data with same ID on each run
logo = LeaveOneGroupOut()

logo.get_n_splits(X_std, y, groups)

cv=logo.split(X_std, y, groups)

scores=[]
for train_index, test_index in cv:
    print("Train Index: ", train_index, "\n")
    print("Test Index: ", test_index)
    X_train, X_test, y_train, y_test = X[train_index], X[test_index], y[train_index], y[test_index]
    model.fit(X_train, y_train.ravel())
    scores.append(model.score(X_test, y_test.ravel()))
Run Code Online (Sandbox Code Playgroud)

我的问题是:我应该如何在“留一小组”的简历循环中实施SMOTE,我对如何为综合训练数据定义小组列表感到困惑。

我很乐意提供更多信息。谢谢!

小智 1

这里建议的方法LOOCV对于留一交叉验证更有意义。留下一组将用作测试集,并对另一剩余组进行过采样。在所有过采样数据上训练您的分类器,并在测试集上测试您的分类器。

在您的情况下,以下代码是在 LOGO CV 循环内实现 SMOTE 的正确方法。

for train_index, test_index in cv:
    print("Train Index: ", train_index, "\n")
    print("Test Index: ", test_index)
    X_train, X_test, y_train, y_test = X[train_index], X[test_index], y[train_index], y[test_index]
    sm = SMOTE()
    X_train_oversampled, y_train_oversampled = sm.fit_sample(X_train, y_train)
    model.fit(X_train_oversampled, y_train_oversampled.ravel())
    scores.append(model.score(X_test, y_test.ravel()))
Run Code Online (Sandbox Code Playgroud)