我有一個 4 維陣列rand,我想使用 3 維陣列沿第 3 維索引idx。在下面的示例中,輸出應該是形狀[32,100,3]
import numpy as np
# values to be indexed
array = np.random.rand(32, 100, 4, 3)
# values to be indexed along the 3rd dimension of array
idx = np.random.randint(low=0, high=3, size=(32,100,1))
indexed_array = array[idx] # Output here should be [32, 100, 3]
我究竟做錯了什么?一個解決方案是遍歷每個維度,但有更好的選擇嗎?
uj5u.com熱心網友回復:
In [61]: array = np.random.rand(32, 100, 4, 3)
...:
...: # values to be indexed along the 3rd dimension of array
...: idx = np.random.randint(low=0, high=3, size=(32, 100, 1))
In [62]: array.shape
Out[62]: (32, 100, 4, 3)
In [63]: idx.shape
Out[63]: (32, 100, 1)
和:
In [64]: array[idx].shape
Out[64]: (32, 100, 1, 100, 4, 3)
我們將陣列idx應用于 的第一個維度array。
idx是第三維的索引,而不是第一維。要應用它,我們需要為前 2 個維度指定兼容的陣列(在broadcasting某種意義上):
In [66]: array[np.arange(32)[:, None,None], np.arange(100)[:,None], idx].shape
Out[66]: (32, 100, 1, 3)
In [67]:
In [67]: array[np.arange(32)[:, None], np.arange(100), idx[:,:,0]].shape
Out[67]: (32, 100, 3)
有一個新功能可以簡化這一點(對于某些人):
In [70]: np.take_along_axis(array, idx[:, :, :, None], axis=2).shape
Out[70]: (32, 100, 1, 3)
索引陣列時,元組和陣列(或串列)之間有一個重要區別。
arr[1,2,3] # index each of the 3 dimensions
arr[(1,2,3)] # equivalent
arr[[1,2,3]] # index just the first dimension with a list
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439817.html
下一篇:如何將真實坐標轉換為0-1網格?
