我正在处理用于分类的不平衡数据,并且之前尝试使用综合少数族裔过采样技术(SMOTE)对培训数据进行过采样。但是,这一次我认为我还需要使用“留出一组”(LOGO)交叉验证,因为我想在每个简历中留出一个主题。
我不确定我是否可以很好地解释它,但是据我的理解,要使用SMOTE进行k折CV,我们可以在每一折上循环进行SMOTE,如我在代码on another post中所看到的。以下是在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)}')
没有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()))
我应该如何在“退出一组退出” CV循环中实现SMOTE?我对如何为综合训练数据定义组列表感到困惑。

最佳答案

此处建议的方法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()))

关于python - 在进行“离开一个组出”交叉验证时如何应用过采样?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56964533/

10-12 18:02