【问题标题】:How to save synthetic dataset in CSV file using SMOTE如何使用 SMOTE 将合成数据集保存在 CSV 文件中
【发布时间】:2020-02-27 11:31:58
【问题描述】:

我正在使用信用卡数据通过 SMOTE 进行过采样。我正在使用 geeksforgeeks.org (Link) 中编写的代码

运行以下代码后,它会声明如下内容:

print("Before OverSampling, counts of label '1': {}".format(sum(y_train == 1))) 
print("Before OverSampling, counts of label '0': {} \n".format(sum(y_train == 0))) 

# import SMOTE module from imblearn library 
# pip install imblearn (if you don't have imblearn in your system) 
from imblearn.over_sampling import SMOTE 
sm = SMOTE(random_state = 2) 
X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel()) 

print('After OverSampling, the shape of train_X: {}'.format(X_train_res.shape)) 
print('After OverSampling, the shape of train_y: {} \n'.format(y_train_res.shape)) 

print("After OverSampling, counts of label '1': {}".format(sum(y_train_res == 1))) 
print("After OverSampling, counts of label '0': {}".format(sum(y_train_res == 0))) 

输出:

Before OverSampling, counts of label '1': 345
Before OverSampling, counts of label '0': 199019 

After OverSampling, the shape of train_X: (398038, 29)
After OverSampling, the shape of train_y: (398038,) 

After OverSampling, counts of label '1': 199019
After OverSampling, counts of label '0': 199019

因为我是这个领域的新手。我不明白如何以 CSV 格式显示这些数据。如果有人在这个问题上帮助我,我将非常高兴。

或者,如果有任何参考资料,我可以使用 SMOTE 从数据集生成合成数据并将更新的数据集保存在 CSV 文件中,请提及。

类似于下图:

提前致谢。

【问题讨论】:

    标签: python machine-learning dataset smote


    【解决方案1】:

    从您的代码中我可以看到,您的 X_train_res 和其他人是 Python Numpy 数组。你可以这样做:

    import numpy as np
    import pandas as pd
    
    y_train_res = y_train_res.reshape(-1, 1) # reshaping y_train to (398038,1)
    data_res = np.concatenate((X_train_res, y_train_res), axis = 1)
    data.savetxt('sample_smote.csv', data_res, delimiter=",")
    

    无法运行并检查它,但如果您遇到任何问题,请告诉我。

    注意:您将不得不做更多的事情来添加列标签。一旦您完成此操作并需要帮助,请告诉我。

    【讨论】:

    • 感谢您的帮助。假设我有一个 CSV 格式的不平衡数据集。在那个数据集中,我在不平衡类中进行过采样。现在我有合成数据,少数类数据等于多数类数据。现在我想在另一个 CSV 文件中显示这个平衡的数据集。
    • 我在我的问题中附上了一张图片。我想要这样的东西。
    • 已编辑答案,如有问题请通知我。
    • 为什么我得到 'DataFrame' 对象没有属性 'savetxt'?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2016-09-01
    • 1970-01-01
    • 2022-06-28
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多