近期做数据处理的时候准备尝试下根据标签分布构建自定义采样概率来缓解data imbalance问题。
举个例子,比如有一个标签类别
年龄 = {幼年, 青年, 中年, 老年},某场景下标签分布为 {100, 4000, 8000, 2000},构建一种自定义采样概率 {0.528, 0.155, 0.122, 0.195},如何依据这种自定义概率分布进行多次采样呢?
random.choices(population, weights=None, *, cum_weights=None, k=1)
- population: Seq(*) 采样元素集群
- weights: Seq(int/float) 采样权重分布
注意: 这里weights可以是整形或浮点型,自带归一化后处理。
比如 weights=[100,200,300] 等价于 [100/(100+200+300), …] - cum_weights: Seq(int/float)累计采样权重分布
比如 cum_weights = [0.2, 0.4, 0.6, 0.8, 1.0] 等价于 weights = [0.2, 0.2, 0.2, 0.2 ,0.2] - k: int # 采样次数
import random # 标签 label_list = ['幼年', '青年', '中年', '老年'] # 自定义概率分布 porb_dist = [0.528, 0.155, 0.122, 0.195] # 采样次数 sample_num = 10 sample_list = random.choices(label_list, weights=porb_dist, k=sample_num)
采样10次结果
[‘幼年’, ‘老年’, ‘青年’, ‘老年’, ‘中年’, ‘幼年’, ‘青年’, ‘幼年’, ‘幼年’, ‘青年’]
这样可以很方便的依照自己定义的概率分布进行多次采用,简单实用



