numpy python 选择_python – 从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]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值