首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python中的加权随机样本

python中的加权随机样本
EN

Stack Overflow用户
提问于 2012-10-24 18:56:34
回答 6查看 14.7K关注 0票数 9

我正在寻找函数weighted_sample的合理定义,它不会只为给定的权重列表返回一个随机索引(可能是这样的

def weighted_choice(weights, random=random):
    """ Given a list of weights [w_0, w_1, ..., w_n-1],
        return an index i in range(n) with probability proportional to w_i. """
    rnd = random.random() * sum(weights)
    for i, w in enumerate(weights):
        if w<0:
            raise ValueError("Negative weight encountered.")
        rnd -= w
        if rnd < 0:
            return i
    raise ValueError("Sum of weights is not positive")

给出一个具有恒定权重的分类分布),而是其中的k的随机样本,没有替换,就像random.samplerandom.choice相比一样。

就像weighted_choice可以被写成

lambda weights: random.choice([val for val, cnt in enumerate(weights)
    for i in range(cnt)])

weighted_sample可以写成

lambda weights, k: random.sample([val for val, cnt in enumerate(weights)
    for i in range(cnt)], k)

但我想要一个不需要我将权重分解成一个(可能很大的)列表的解决方案。

编辑:如果有任何很好的算法可以给我返回一个直方图/频率列表(格式与参数weights相同),而不是一系列索引,那也是非常有用的。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13047806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档