gpt4 book ai didi

python - 从 numpy 数组中进行概率选择

转载 作者:太空狗 更新时间:2023-10-30 02:32:17 24 4
gpt4 key购买 nike

Numpy 是否有任何内置函数可以从一维 numpy 数组中随机选择值,并为数组末尾的值赋予更高的权重?有没有比定义偏态分布并从中采样以获得数组索引更简单的方法?

最佳答案

可以给np.choice一个权重,如图:

a = np.random.random(100)    # an array to draw from
n = 10 # number of values to draw
i = np.arange(a.size) # an array of the index value for weighting
w = np.exp(i/10.) # higher weights for larger index values
w /= w.sum() # weight must be normalized

现在,访问您的值:

np.random.choice(a, size=n, p=w)

很明显,您可以随心所欲地更改权重数组,我从末端开始进行指数衰减,衰减长度 10;增加衰减长度以获得更广泛的选择:

对于np.exp(i/50.):

In [38]: np.random.choice(a, size=n, p=w)
Out[38]: array([37, 53, 45, 22, 88, 69, 56, 86, 96, 24])

对于np.exp(i):

In [41]: np.random.choice(a, size=n, p=w)
Out[41]: array([99, 99, 98, 99, 99, 99, 99, 97, 99, 98])

如果您只想获取每个值一次,请务必设置replace=False,否则您可以多次获取相同的值(尤其是当它具有很高的权重时,如上面的第二个例子)。看这个例子:

In [33]: np.random.choice(a, size=n, replace=False, p=w)
Out[33]: array([99, 84, 86, 91, 87, 81, 96, 89, 97, 95])

In [34]: np.random.choice(a, size=n, replace=True, p=w)
Out[34]: array([94, 98, 99, 98, 97, 99, 91, 96, 97, 93])

我原来的回答是:

如果分布的形式并不重要,您可以做类似指数泊松分布的事情:

idx = np.random.poisson(size=10)

你的样本:

a[-idx-1]

关于python - 从 numpy 数组中进行概率选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com