在 SMOTE 之后保留 pandas 数据帧结构,在 python 中过采样

Retain pandas dataframe structure after SMOTE, oversampling in python

问题:在实施 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 的数据帧结构。怎么做?

这个功能或许能帮到你。 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_

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

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 之后保留数据帧结构