绘制numpy的随机元素 [英] draw random element in numpy
问题描述
我有概率元素的数组,假设 [0.1,0.2,0.5,0.2]
。该阵列总结为1.0。
使用普通的Python或numpy的,我想提请比例元素及其概率:第一个元素大约10%的时间,第二个20%,第三个50%等。画应该返回绘制的元素的索引。
我想出了这一点:
高清画(probs):
cumsum = numpy.cumsum(probs /总和(probs))#总和高达1.0,以防万一
返回LEN(numpy.where(numpy.random.rand()&GT = cumsum)[0])
它的工作原理,但它太令人费解,必须有一个更好的办法。谢谢你。
导入numpy的是NP
高清random_pick(选择,probs):
'''
>>> A = ['打','出']
>>> B = [3,0.7]
>>> random_pick(A,B)
'''
截止= np.cumsum(probs)
IDX = cutoffs.searchsorted(np.random.uniform(0,截断值[-1]))
返回选择[IDX]
它是如何工作:
在[22]:进口numpy的为NP
在[23]:probs = [0.1,0.2,0.5,0.2]
计算的累计总和:
在[24]:截止= np.cumsum(probs)
在[25]:截止
出[25]:阵列([0.1,0.3,0.8,1])
计算在半开区间均匀分布的随机数 [0,临界值[-1])
:
在[26]:np.random.uniform(0,临界值[-1])
出[26]:0.9723114393023948
使用<一个href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html#numpy-searchsorted\">searchsorted找到其中,随机数将被插入截止
索引:
在[27]:cutoffs.searchsorted(0.9723114393023948)
出[27]:3
返回选择[IDX]
,其中 IDX
是索引。
I have an array of element probabilities, let's say [0.1, 0.2, 0.5, 0.2]
. The array sums up to 1.0.
Using plain Python or numpy, I want to draw elements proportional to their probability: the first element about 10% of the time, second 20%, third 50% etc. The "draw" should return index of the element drawn.
I came up with this:
def draw(probs):
cumsum = numpy.cumsum(probs / sum(probs)) # sum up to 1.0, just in case
return len(numpy.where(numpy.random.rand() >= cumsum)[0])
It works, but it's too convoluted, there must be a better way. Thanks.
import numpy as np
def random_pick(choices, probs):
'''
>>> a = ['Hit', 'Out']
>>> b = [.3, .7]
>>> random_pick(a,b)
'''
cutoffs = np.cumsum(probs)
idx = cutoffs.searchsorted(np.random.uniform(0, cutoffs[-1]))
return choices[idx]
How it works:
In [22]: import numpy as np
In [23]: probs = [0.1, 0.2, 0.5, 0.2]
Compute the cumulative sum:
In [24]: cutoffs = np.cumsum(probs)
In [25]: cutoffs
Out[25]: array([ 0.1, 0.3, 0.8, 1. ])
Compute a uniformly distributed random number in the half-open interval [0, cutoffs[-1])
:
In [26]: np.random.uniform(0, cutoffs[-1])
Out[26]: 0.9723114393023948
Use searchsorted to find the index where the random number would be inserted into cutoffs
:
In [27]: cutoffs.searchsorted(0.9723114393023948)
Out[27]: 3
Return choices[idx]
, where idx
is that index.
这篇关于绘制numpy的随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!