【问题标题】:2D version of numpy random choice with weighting带权重的 numpy 随机选择的 2D 版本
【发布时间】:2020-04-28 14:00:34
【问题描述】:

这与之前的帖子有关:Numpy random choice of tuples

我有一个 2D numpy 数组,并想使用 2D 概率数组从中进行选择。我能想到的唯一方法是展平,然后使用模数和余数将结果转换回二维索引

import numpy as np
# dummy data
x=np.arange(100).reshape(10,10)

# dummy probability array
p=np.zeros([10,10])
p[4:7,1:4]=1.0/9

xy=np.random.choice(x.flatten(),1,p=p.flatten())
index=[int(xy/10),(xy%10)[0]] # convert back to index
print(index)

这给了

[5, 2]

但是有没有一种更简洁的方法可以避免展平和取模?即我可以将坐标元组列表作为 x 传递,但是我该如何处理权重?

【问题讨论】:

  • 我觉得这个方法很好,你可以用unravel_index替换除法/取模

标签: python numpy random


【解决方案1】:

我认为不可能直接指定二维形状的概率数组。所以散漫应该没问题。但是,要从平面索引中获取相应的 2D 形状索引,您可以使用 np.unravel_index

index= np.unravel_index(xy.item(), x.shape)
# (4, 2)

对于多个索引,您可以只堆叠结果:

xy=np.random.choice(x.flatten(),3,p=p.flatten())

indices = np.unravel_index(xy, x.shape)
# (array([4, 4, 5], dtype=int64), array([1, 2, 3], dtype=int64))
np.c_[indices]
array([[4, 1],
       [4, 2],
       [5, 3]], dtype=int64)

np.c_stacks along the right hand axis 并给出与

相同的结果
np.column_stack(indices)

【讨论】:

    【解决方案2】:

    您可以使用numpy.random.randint 来生成索引,例如:

    # assumes p is a square array
    ij = np.random.randint(p.shape[0], size=p.ndim) # size p.ndim = 2 generates 2 coords
    
    # need to convert to tuple to index correctly
    p[tuple(i for i in ij))]
    >>> 0.0
    

    您还可以一次索引多个随机值:

    ij = np.random.randint(p.shape[0], size=(p.ndim, 5)) # get 5 values
    p[tuple(i for i in ij))]
    >>> array([0.        , 0.        , 0.        , 0.11111111, 0.        ])
    

    【讨论】:

    • 非常感谢,randint 的唯一问题是我认为它不允许我应用权重,还是我错了?
    • 不,我认为你是对的。 randint 没有概率参数,但 choice 有。很高兴知道!
    • 感谢您的输入,对非加权示例很有用。
    猜你喜欢
    • 2012-05-20
    • 2011-04-29
    • 2018-02-02
    • 2017-04-28
    • 2014-06-20
    • 2010-09-26
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    相关资源
    最近更新 更多