zoukankan      html  css  js  c++  java
  • Python 按分类权重(区间)随机获取分类样本

    按分类权重(区间)随机获取分类样本

    By:授客 QQ1033553122

    开发环境

    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)
    

      

     

     

    运行结果

     

     

     

     

    注意

    为啥可以用python的randowm函数来实现这个需求?那是因为python的random函数是平均分布函数,产生的随机数是等可能的。如下,可以把[0,1)区间看作一条线,生成的随机数可以看作是线条上一个个点,这样,就可以根据这个点所在位置,把这个点划分到某个区间(本例中划分了几个区间[0, 0.1),[0.1,0.25),[0.25,0.4),[0.4, 0.65),[0.65,1)),映射样本的概率范围

    0       0.25      0.5              1

    |--------|--------|----------------|

     

    从运行结果来看,不难看出,这种计算方式存在一定的偏差,比较适合大数据

  • 相关阅读:
    Java抽象类、接口能否有构造方法
    Java堆溢出、栈溢出示例
    typora常用快捷键
    什么是业务逻辑
    解决idea登录github出现的invalid authentication data 404 not found
    SQL常用聚合函数
    oracle存储过程/函数调试
    解决IDEA全局搜索Ctrl+Shift+F失效问题
    如何在win10系统中使用Linux命令
    Java复现NullPointerException异常
  • 原文地址:https://www.cnblogs.com/shouke/p/13986965.html
Copyright © 2011-2022 走看看