4

问题:在实现 SMOTE(一种过采样)时,我的数据框正在转换为 numpy 数组)。

Test_train_split

from sklearn.model_selection import train_test_split
X_train, X_test, y_train_full, y_test_full = train_test_split(X, y, test_size=0.20, random_state=66)
[IN]type(X_train)
[OUT]pandas.core.frame.DataFrame

在 SMOTE 之后,X_train 的数据类型从 pandas 数据帧变为 numpy 数组

from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state = 42)
X_train, y_train = sm.fit_sample(X_train, y_train)
[IN]type(X_train)
[OUT]numpy.ndarray

预期输出 我想在 SMOTE 之后保留 X_train 和 X_test 的数据帧结构。怎么做?

4

2 回答 2

11

我找到了一个更简单的答案:

from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state = 42)
X_train_oversampled, y_train_oversampled = sm.fit_sample(X_train, y_train)
X_train = pd.DataFrame(X_train_oversampled, columns=X_train.columns)

这有助于在 SMOTE 之后保留数据帧结构

于 2020-02-27T12:06:48.217 回答
3

这个功能可以帮助你。df在您的情况下是 X_train 和 X_test 并且output是 y 的列名作为字符串。SEED如果要设置,则为随机整数random_state

您可以在拆分后或拆分数据集之前使用它,具体取决于您的选择。

def smote_sampler(df, output, SEED=33):
     X = df.drop([output], axis=1)
     y = df[output]
     col_names = pd.concat([X, y], axis=1).columns.tolist()
     smt = SMOTE(random_state=SEED)
     X_smote, y_smote = smt.fit_sample(X, y)
     smote_array = np.concatenate([X_smote, y_smote.reshape(-1, 1)], axis=1)
     df_ = pd.DataFrame(smote_array, columns=col_names)
     smote_cols = df_.columns.tolist()
     org_int_cols = df.dtypes.index[df.dtypes == 'int64'].tolist()
     org_float_cols = df.dtypes.index[df.dtypes == 'float64'].tolist()
     try:
         for col in smote_cols:
             if col in org_float_cols:
                 df_[col] = df_[col].astype('float64')
             elif col in org_int_cols:
                 df_[col] = df_[col].astype('int64')
     except:
         raise ValueError
     return df_
于 2020-02-27T12:02:36.957 回答