有人可以幫我理解爲什麼有時候高級選擇不起作用,我能做些什麼才能使它起作用(第二種情況)?Numpy高級選擇不起作用
>>> import numpy as np
>>> b = np.random.rand(5, 14, 3, 2)
# advanced selection works as expected
>>> b[[0,1],[0,1]]
array([[[ 0.7575555 , 0.18989068],
[ 0.06816789, 0.95760398],
[ 0.88358107, 0.19558106]],
[[ 0.62122898, 0.95066355],
[ 0.62947885, 0.00297711],
[ 0.70292323, 0.2109297 ]]])
# doesn't work - why?
>>> b[[0,1],[0,1,2]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
# but this seems to work
>>> b[:,[0,1,2]]
array([[[[ 7.57555496e-01, 1.89890676e-01],
[ 6.81678915e-02, 9.57603975e-01],
[ 8.83581071e-01, 1.95581063e-01]],
[[ 2.24896112e-01, 4.77818599e-01],
[ 4.29313861e-02, 8.61578045e-02],
[ 4.80092364e-01, 3.66821618e-01]],
...
更新
分手的選擇似乎是解決這個問題,但我不能確定爲什麼這是必要的(或者,如果有一個更好的方式來做到這一點)。
>>> b.shape
(5, 14, 3, 2)
>>> b[[0,1]].shape
(2, 14, 3, 2)
# trying to separate indexing by dimension.
>>> b[[0,1]][:,[0,1,2]]
array([[[[ 0.7575555 , 0.18989068],
[ 0.06816789, 0.95760398],
[ 0.88358107, 0.19558106]],
[[ 0.22489611, 0.4778186 ],
[ 0.04293139, 0.0861578 ],
你覺得呢'B [[0,1],[0,1,2]]'應該做的事?如果你期望這樣做,那麼'b [[0,1],[0,1]]'最有可能沒有做你想做的事情,而你沒有注意到由於沒有噪聲錯誤信息。 – user2357112
那麼,對於初學者來說,它不應該導致錯誤。 – orange
該索引應從維度'0'選擇元素'0'和'1',並從維度'1'選擇'0','1'和'2'(對於其他後續維度選擇「片(無)」) 。 – orange