[英]Efficiently sample vectors from numpy ndarray
I have a multidimensional numpy array X
of shape
: (B, dim, H, W)
I would like to randomly sample k
dim
-dimensional vectors out of X
. 我有一个多维阵列numpy的X
的shape
: (B, dim, H, W)
我想随机抽样k
dim
维向量出X
。
I can get the sample indices from a msk
of shape (B, 1, H, W)
: 我可以从形状为(B, 1, H, W)
的msk
获取样本索引:
sIdx = random.sample((msk.flat>=0).nonzero()[0], k)
Equivalent sampling code using numpy is: 使用numpy的等效采样代码为:
sIdx = np.random.choice((msk.flat>=0).nonzero()[0], replace=False, size=(k,))
But how can I efficiently slice X
according to the "flat" sampled indices sIdx
? 但是,如何根据“平坦的”采样索引sIdx
有效地切片X
?
That is, is there an efficient way to combine the random sampling of msk
with the slicing of X
? 也就是说,是否存在将msk
的随机采样与X
的切片相结合的有效方法?
Get the respective indices for the rest of those three axes with np.unravel_index
from the flattened indices and simply index into X
along those axes for the final output, like so - 从展平的索引中使用np.unravel_index
获取这三个轴的其余部分的相应索引,然后简单地沿着这些轴将X
索引为最终输出,就像这样-
I,J,K = np.unravel_index(sIdx, (B, H, W))
out = X[I,:,J,K]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.