[英]numpy 3D array vectorized access with arrays of indices
I have a 3D numpy array A representing a batch of images: A.shape -> (batch_size, height, width)我有一个 3D numpy 数组 A 代表一批图像:A.shape -> (batch_size, height, width)
I want to access this array using two other arrays Hs,Ws, of size batch_size.我想使用大小为batch_size 的另外两个数组Hs、Ws 访问该数组。 They contain the x index and y index of each image that I want to access.它们包含我要访问的每个图像的 x 索引和 y 索引。
Example 2 images of size 3x3:示例 2 大小为 3x3 的图像:
A.shape(2,3,3) A.shape(2,3,3)
A = [[[1,2,3],[5,6,7],[8,9,10]], [[10,20,30],[50,60,70],[80,90,100]]] A = [[[1,2,3],[5,6,7],[8,9,10]],[[10,20,30],[50,60,70],[80,90,100 ]]]
Hs = [0,2] Hs = [0,2]
Ws = [1,2] Ws = [1,2]
I want to acces A so that I get:我想访问 A 以便我得到:
A[:, Hs,Ws] = [2,100] A[:, Hs,Ws] = [2,100]
Doing it like this (A[:, Hs,Ws]) unfortunately results in a 2x2 array (batch_size x batch_size)不幸的是,这样做 (A[:, Hs,Ws]) 会导致 2x2 数组 (batch_size x batch_size)
Executed with a for loop this would look like this:用 for 循环执行,这看起来像这样:
Result = np.zeros(batch_size)
for b in range(0,batch_size):
Result[b] = A[b,Hs[b],Ws[b]]
Is it possible to do this without a for loop by accessing A directly in a vectorized manner?通过以矢量化方式直接访问 A 是否可以在没有 for 循环的情况下执行此操作?
Do you mean this:你的意思是:
In [6]: A = np.array(A); Hs=np.array(Hs); Ws=np.array(Ws)
In [7]: A.shape
Out[7]: (2, 3, 3)
In [8]: A[np.arange(2), Hs, Ws]
Out[8]: array([ 2, 100])
When using indexing arrays, they 'broadcast' against each other.使用索引数组时,它们会相互“广播”。 Here with (2,),(2,),(2,) the broadcasting is eash.这里使用 (2,),(2,),(2,) 广播很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.