python - 带权重的 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 传递,但是我该如何处理权重?
解决方案
我认为不可能直接指定二维形状的概率数组。所以散漫应该没问题。但是,要从平面索引中获取相应的 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)
推荐阅读
- ios - 使用 fastlane scan 进行并行测试时指定测试设备的数量
- ios - Swift Firebase 动态链接:shortURL 不起作用
- svg - 如何在 Markdown 文件中修剪 svg 图像
- ios - 相机“重拍”和“使用照片”按钮不起作用
- owl - 将对象属性域/范围转移到另一个本体中的类似类
- javascript - 停止将 '' 编码为 Javascript 中的引号
- ios - 如何使 UICollectionView 看起来像滚动的 Instagram 故事预览
- java - Tomcat - 从命令行覆盖 catalina.properties
- c# - 如何根据 EF 中子表中的列对项目进行排序
- php - Laravel 与 Docker 问题连接 MySQL