按分类权重(区间)随机获取分类样本
按分类权重(区间)随机获取分类样本
By:授客 QQ:1033553122
开发环境
win 10
python 3.6.5
需求
活动抽奖,参与抽奖产品有iphone, 华为,小米,魅族,vivo,三星手机,要求为这些不同品牌的手机设置被抽奖的概率(基准概率,非绝对概率,即允许存在一定偏差),iphone为0,华为0.35,小米为0.25, 魅族0.1,vivo和三星为0.15
代码实现
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "shouke" import random def get_sample_by_rate(sample_rate_list): if sum([item[1] for item in sample_rate_list]) != 1: raise ValueError("样本比例配置错误,样本占比之和必须为1!") random_normalized_num = random.random() # random() -> x in the interval [0, 1). accumulated_probability = 0.0 for sample, probabilitie in sample_rate_list: accumulated_probability += probabilitie if random_normalized_num < accumulated_probability: return sample award_dict = {"iphone":0, "华为":0.35, "小米":0.25, "魅族":0.1, "vivo":0.15, "三星":0.15} # 初始化 output_dict = {} # 存放取样次数 for sample, rate in award_dict.items(): output_dict[sample] = 0 award_list = sorted(award_dict.items(), key=lambda arg:arg[1], reverse=False) n = 1000 # 取样总次数 for i in range(n): award = get_sample_by_rate(award_list) output_dict[award] += 1 percentage_dict = {key: output_dict[key]/n for key in output_dict} # 存放样本数占比 print(output_dict) print(percentage_dict)