首页 > 解决方案 > 带权重的 numpy 随机选择的 2D 版本

问题描述

这与之前的帖子有关:Numpy random selection 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 传递,但是我该如何处理权重?

标签: pythonnumpyrandom

解决方案


我认为不可能直接指定二维形状的概率数组。所以散漫应该没问题。但是,要从平面索引中获取相应的 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_ 沿右手轴堆叠并给出相同的结果

np.column_stack(indices)

推荐阅读