数据分析学习之:如何均衡样本——使用 imblearn 库实现重采样(resampling),过采样(over-sampling) + 欠采样(under-sampling))

什么是样本不平衡

import pandas as pd
import numpy as np
import seaborn as sns

values = {"姓名":["A","B","C","D","E","F","G","H","I","J","K","L","G","H","I","J","K","L"],
         "年龄":[55,70,80,90,60,30,67,44,60,30,67,44,30,67,30,67,30,67],
          "头发颜色":["白","白","白","白","白","黑","白","黑","白","白","黑","白","白","黑","白","白","黑","黑"]}
table = pd.DataFrame(values)
table
姓名年龄头发颜色
0A55
1B70
2C80
3D90
4E60
5F30
6G67
7H44
8I60
9J30
10K67
11L44
12G30
13H67
14I30
15J67
16K30
17L67
table["头发颜色"] = pd.Categorical(table["头发颜色"]).codes
table
姓名年龄头发颜色
0A550
1B700
2C800
3D900
4E600
5F301
6G670
7H441
8I600
9J300
10K671
11L440
12G300
13H671
14I300
15J670
16K301
17L671
  • 从下面的统计图中可以看出,以头发颜色作为 label 进行分类的时候,样本是不均衡的
  • 因为 12个白头发,但是有 6 个黑头发
table["头发颜色"].plot(x=[0,1],kind="hist")

在这里插入图片描述

如何平衡数据集的样本——重采样

  • 我们的最终目标是保证数据集中各个 label 下的样本数量是几乎完全相等的
  • 要么我们就需要把样本多的组的样本按照随机的原则砍掉一部分来平衡,要么就把少样本的一组进行扩充

欠采样(也叫 undersampling)

  • 顾名思义,削减大的样本集

将大的样本集的数据全部筛选出来

df_white = table.loc[table["头发颜色"] == 0]  #选出头发为白色的人
df_black = table.loc[table["头发颜色"] == 1] #选出头发为黑色的人
df_white
姓名年龄头发颜色
0A550
1B700
2C800
3D900
4E600
6G670
8I600
9J300
11L440
12G300
14I300
15J670
df_black
姓名年龄头发颜色
5F301
7H441
10K671
13H671
16K301
17L671

通过随机采样操作采样固定个数的样本留下

df_white = df_white.sample(n=6,random_state=30)
df_white
姓名年龄头发颜色
0A550
8I600
12G300
11L440
1B700
3D900

和少样本的样本集拼合成最终的样本集

table_undersampling = pd.concat([df_black,df_white],axis=0,ignore_index=True)
table_undersampling
姓名年龄头发颜色
0F301
1H441
2K671
3H671
4K301
5L671
6A550
7I600
8G300
9L440
10B700
11D900

样本均衡了

table_undersampling["头发颜色"].plot(kind="hist")

在这里插入图片描述

过采样(over-sampling)

通过 imblearn 库扩充小的样本集

from imblearn.over_sampling import SMOTE
# Resample the minority class. You can change the strategy to 'auto' if you are not sure.

# 如果这里选 minority 只能保证两个 class 样本均衡
# 但是使用 auto 可以保证多个类样本均衡
sm = SMOTE(sampling_strategy='auto', random_state=7)


# Fit the model to generate the data.

oversampled_data,oversampled_label=sm.fit_resample(table.drop(['姓名','头发颜色'], axis=1), table['头发颜色'])
oversampled_table =pd.concat([oversampled_data, oversampled_label], axis=1)

样本均衡了

oversampled_table["头发颜色"].plot(kind="hist")

在这里插入图片描述



  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暖仔会飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值