鑒于以下情況:
polygons = np.array([
[[1, 0],
[1, 1],
[0, 0],
[0, 1]],
[[3, 2],
[2, 2],
[4, 4],
[2, 3]]])
sort_idx = np.array([
[2, 0, 1, 3],
[1, 0, 2, 3]])
polygons[sort_idx] #< The problematic part
預期的輸出是:
array([[[0, 0],
[1, 0],
[1, 1],
[0, 1]],
[[2, 2],
[3, 2],
[4, 4],
[2, 3]]])
我希望polygons[sort_idx]回傳 的“排序”行polygons,排序順序由 中的值給出sort_idx。
polygons[0][sorted_idx[0]](和等效的 for [1])給出正確的值,但運行polygons[sort_idx]會引發:
IndexError: index 2 is out of bounds for axis 0 with size 2
我估計這個問題與我不了解操作是如何廣播的有關,但我真的不知道要搜索什么或如何表達這個問題。我看到類似的問題建議使用np.take()or polygons[sort_idx,...],但都引發了相同的錯誤。我錯過了什么?
uj5u.com熱心網友回復:
使用np.take_along_axis:
np.take_along_axis(polygons, sort_idx[..., None], 1)
Out[]:
array([[[0, 0],
[1, 0],
[1, 1],
[0, 1]],
[[2, 2],
[3, 2],
[4, 4],
[2, 3]]])
uj5u.com熱心網友回復:
take_along_axis應該“簡化”我們必須做(并且仍然可以做)的索引:
In [233]: polygons[np.arange(2)[:,None], sort_idx]
Out[233]:
array([[[0, 0],
[1, 0],
[1, 1],
[0, 1]],
[[2, 2],
[3, 2],
[4, 4],
[2, 3]]])
第一個維度索引是(2,1),然后是第二個(2,4),它們一起廣播選擇前2個維度中的(2,4)(最后一個維度不變)。
的值sort_idx適用于第 2 軸,尺寸為 4 的軸。 polygons[sort_idx]將它們應用于第一個尺寸為 2 的維度,因此會出現錯誤。
對第一個維度使用 slice 會回傳太多值,即一個塊。我們想要更像對角線的東西:
In [235]: polygons[:, sort_idx,:].shape
Out[235]: (2, 2, 4, 2)
所以,是的,這是一個broadcasting問題。當使用多個索引陣列時,我們要考慮它們如何broadcast相互對抗。適用與運營商相同的規則。
In [236]: np.array([10,100])[:,None]* sort_idx
Out[236]:
array([[ 20, 0, 10, 30],
[100, 0, 200, 300]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464607.html
