簡體   English   中英

numpy rollaxis - 它究竟是如何工作的?

[英]numpy rollaxis - how exactly does it work?

所以我正在嘗試numpy,我在rollaxis方法中遇到了一個奇怪的(?)行為。

In [81]: a = np.ones((4, 3, 2))

In [82]: a.shape
Out[82]: (4, 3, 2)

In [83]: x = np.rollaxis(a, 2)

In [84]: x.shape
Out[84]: (2, 4, 3)

In [85]: np.rollaxis(x, -2).shape
Out[85]: (4, 2, 3)

-2不應該反轉rolrolis? 我要做的是應用一個只能在2坐標第一時應用的矩陣。 但后來我想把我的陣列恢復原狀。 我發現的唯一的工作是應用np.rollaxis(x, 2)兩次,或應用np.rollaxis(x, 0, start=3) 我只是通過猜測發現了這些,我不知道它們為什么會起作用。 他們似乎也模糊了我真正想做的事情。 有人可以解釋一下我應該“扭轉”滾動的方式,或者我做錯了什么?

(有這樣的pythonic方法嗎?)

方法rollaxis

def rollaxis(a, axis, start=0):

start “位置”重新分配所選axis

按照你的例子:

a = np.ones((4, 3, 2))
x = np.rollaxis(a, 2)
# x.shape = (2, 4, 3)

關於形狀: rollaxis會將數字2 (最后一個axis=2 )帶到第一個位置,因為start=0

通過使用

x2 = np.rollaxis(x, -2)
# x2.shape = (4,2,3)

rollaxis將帶來數字4,這是第二個最后一個軸, axis=-2 ,並在第一個位置重新分配,因為start=0 這解釋了你的結果(4,2,3) ,而不是(4,3,2)

遵循相同的邏輯,這解釋了為什么兩次應用rollaxis(a,2)會使陣列形狀回到初始狀態。 np.rollaxis(x, 0, start=3)也有效,因為第一個軸到達最后一個軸,換句話說,(2,4,3)中的數字2到達最后一個位置(4,3,2) )。

np.rollaxis(tensor,axis,start)將軸參數指定的軸移動到位於start的軸之前的位置,沒有異常。

假設軸是(1,2,3,4,5,6),如果軸指向3,並且開始指向5,那么在滾動之后,3將在5之前。因為3在我的示例位於維度元組的位置2,軸= 2。 此外,由於5位於位置4,因此start = 4。

像這樣:

>>> a.shape

(1, 2, 3, 4, 5, 6)

>>> np.rollaxis(a, 2, 4).shape

(1, 2, 4, 3, 5, 6)

正如您所看到的,3現在正好在5之前。注意:3不會移動到位置4,而是移動到最初位於第4位的值之前的位置(在這種情況下結果是位置3)。

負數指定位置就像它們對列表一樣。 換句話說,axis = -1指定最后一個位置。 在上面的例子中,在-1位置有一個6,在-2位置有一個5。 軸和起點都可以是負數。

您可以使用上面的負數做同樣的事情:

>>> a.shape

(1, 2, 3, 4, 5, 6)

>>> np.rollaxis(a, -4, -2).shape

(1, 2, 4, 3, 5, 6)

如果未指定start,則默認為0,這是第一個位置。 這意味着如果未指定start,則指定的軸將始終移動到開頭,該開頭位於最初位於位置0的1之前。

如果這令人困惑,還有另一種解釋可能會更有意義: 為什么numpy rollaxis如此令人困惑?

基本思想是它圍繞nd陣列的軸移動 它取axis參數提到的axis並將其置於start參數提到的位置 ; 當發生這種情況時,以下位置的剩余軸直到結束將向右移動。 如果忽略start參數,它會將提到的軸移動到第一個位置(即它將移動為第0個軸)

讓我們用一個例子來理解它:

In [21]: arr = np.ones((3,4,5,6))

In [22]: arr.shape
Out[22]: (3, 4, 5, 6)
# here 0th axis is 3, 1st axis is 4, 2nd axis is 5, 3rd axis is 6

# moving `3`rd axis as `1`st axis
In [27]: np.rollaxis(arr, 3, 1).shape

# see how `6` which was the third axis has been moved to location `1`
Out[27]: (3, 6, 4, 5)

在移動軸(或按NumPy調用它的方式滾動 )時,該位置中已存在的軸為進入的軸騰出空間,並且隨后的軸向右側移動。

如果忽略start參數,則axis參數中的axis將移動到前面(即到第0位置)。

In [29]: a.shape
Out[29]: (3, 4, 5, 6)

# ignoring the `start` moves the axis to the very front position.
In [30]: np.rollaxis(arr, 3).shape
Out[30]: (6, 3, 4, 5)

np.moveaxis比較

In [38]: arr.shape
Out[38]: (3, 4, 5, 6)

In [39]: np.rollaxis(arr, 0, -1).shape
Out[39]: (4, 5, 3, 6)

In [40]: np.moveaxis(arr, 0, -1).shape
Out[40]: (4, 5, 6, 3)

觀察在上面的例子中如何np.moveaxis確實循環移位而np.rollaxis只是僅延伸朝向右側。


PS:另請注意,此rollaxis操作返回NumPy 1.10.0開始的輸入數組視圖

當軸== start和axis == start-1時,它將具有相同的結果

>>>a=np.ones([1, 2, 3, 4, 5, 6])
(1, 2, 3, 4, 5, 6)
>>> np.rollaxis(a, axis=2, start=2).shape
(1, 2, 3, 4, 5, 6)
>>> np.rollaxis(a, axis=2, start=3).shape
(1, 2, 3, 4, 5, 6)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM