icney 2022-03-01 08:57 采纳率: 100%
浏览 56
已结题

【Python】过采样与下采样同时进行的代码应该是这样吗?

问题遇到的现象和发生背景

请问如下代码是同时进行了过采样和下采样吗?另外,具体sampling_strategy应该怎么去用呢?

原始数据的value_counts():

0 13634
1 6305

问题相关代码
#SMOTE上采样:原少数类*1.5=9458个
from imblearn.combine import SMOTEENN
smo = SMOTEENN(sampling_strategy={1: 9458 },random_state=24)
tra1_x1, tra1_y1 = smo.fit_resample(train1.drop(['Pred','Date'], axis=1), train1['Pred'])  

#下采样:原少数类*0.5*3.5=11034个
from imblearn.combine import SMOTETomek
rus = SMOTETomek(sampling_strategy={0: 11034 },random_state=24)
tra1_x1, tra1_y1 = rus.fit_resample(train1.drop(['Pred','Date'], axis=1), train1['Pred'])
print(tra1_x1.shape)
print((tra1_y1==1).sum()/len(tra1_y1))
运行结果及报错内容
ValueError: With over-sampling methods, the number of samples in a class should be greater or equal to the original number of samples. Originally, there is 13634 samples and 11034 samples are asked.

谢谢大家!

  • 写回答

1条回答 默认 最新

  • icney 2022-03-01 09:34
    关注

    !好像上面是两种不同的方法;我换了一种方式,先过采样,再下采样也解决了问题,代码如下:

    from imblearn.over_sampling import SMOTE
    smote = SMOTE(sampling_strategy={1: 9458 },random_state=2021)
    tra1_x1, tra1_y1 = smote.fit_resample(train1.drop(['Pred','Date'], axis=1), train1['Pred'])  
    print(tra1_x1.shape) 
    print((tra1_y1==1).sum()/len(tra1_y1))
    
    from imblearn.under_sampling import RandomUnderSampler
    cc = RandomUnderSampler(sampling_strategy={0:11034 },random_state=2021)
    tra1_x2, tra1_y2 = cc.fit_resample(tra1_x1, tra1_y1)  
    print(tra1_x2.shape) 
    print((tra1_y2==1).sum()/len(tra1_y2))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月9日
  • 已采纳回答 3月1日
  • 创建了问题 3月1日

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示