多维数组随机选择在纽比

2024-04-27 22:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张桌子,我需要用随机选择对于概率计算, 例如(摘自docs):

>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
      dtype='|S11')

如果我用的是3D数组而不是aa_milne_arr,它不允许我继续。我需要为3个数组生成概率不同的随机事件,但它们内部的元素也是一样。例如

^{pr2}$

我希望arr0(0.5),arr1(0.1)和arr3(0.4)中的元素都有相同的概率,因此我可以看到arr0中任何元素的概率都是0.5

有什么优雅的方法吗?在


Tags: 元素docsnprandom数组概率aaarr
2条回答

p的值除以数组的长度,然后按相同的长度重复。在

然后用新的概率从串联数组中选择

arr = [arr0, arr1, arr3]
lens = [len(a) for a in arr]
p = [.5, .1, .4]
new_arr = np.concatenate(arr)
new_p = np.repeat(np.divide(p, lens), lens)

np.random.choice(new_arr, p=new_p)

这是我带来的。 它采用概率向量或矩阵,其中权重按列组织。权重将规格化为和1。在

import numpy as np

def choice_vect(source,weights):
    # Draw N choices, each picked among K options
    # source: K x N ndarray
    # weights: K x N ndarray or K vector of probabilities
    weights = np.atleast_2d(weights)
    source = np.atleast_2d(source)
    N = source.shape[1]
    if weights.shape[0] == 1:
        weights = np.tile(weights.transpose(),(1,N))
    cum_weights = weights.cumsum(axis=0) / np.sum(weights,axis=0)
    unif_draws = np.random.rand(1,N)
    choices = (unif_draws < cum_weights)
    bool_indices = choices > np.vstack( (np.zeros((1,N),dtype='bool'),choices ))[0:-1,:]
    return source[bool_indices]

它避免使用循环,并且类似于的矢量化版本随机选择. 在

你可以这样使用它:

^{pr2}$

相关问题 更多 >