在python中生成具有加权概率的随机数 [英] Generating random numbers with weighted probabilities in python

查看:565
本文介绍了在python中生成具有加权概率的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个正整数数组a,目标是根据它们在数组中的权重生成5个随机数.

Given a positive integer array a, the goal is to generate 5 random numbers based on the weight they have in the array.

例如:

a = [2,3,4,4,4,4,4,6,7,8,9]

在这种情况下,数字4出现了5次,在这种情况下,数字4应该有5/11出现的可能性.

In this case the number 4 has appeared 5 times, in this case the number 4 should have the probability of 5/11 to appear.

任何数字都不能重复.

推荐答案

给出a,一个正整数数组,您首先需要计算每个整数的频率.例如,使用bincount:

Given a, an array of positive integers, you'll first need to compute the frequency of each integer. For example, using bincount:

>>> a = [2,3,4,4,4,4,4,4,5,6,7,8,9,4,9,2,3,6,3,1]
>>> b = np.bincount(a)

b告诉您a中每个整数的频率.因此,相应的权重集为数组b/len(a).然后将np.random.choice与这些权重和replace=False结合使用,即可为您提供所需的信息:

b tells you the frequency of each integer in a. The corresponding set of weights is therefore the array b/len(a). Using np.random.choice with these weights and replace=False should then give you what you need:

>>> np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False)
array([5, 9, 4, 3, 8])
>>> np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False)
array([7, 4, 6, 9, 1])
>>> np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False)
array([3, 7, 4, 9, 6])

如果您不只使用正整数,或者正在使用大正整数,则@ user2357112在下面的注释中指出np.unique提供了另一种解决方案.在这里您要写:

If you're not working with only positive integers, or if you are working with large positive integers, @user2357112 points out in the comments below that np.unique provides another solution. Here you'd write:

>>> choices, counts = np.unique(a, return_counts=True)
>>> np.random.choice(choices, 5, p=counts/len(a), replace=False)
array([9, 8, 2, 4, 5])

这篇关于在python中生成具有加权概率的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆