numpy的axis的理解和檢驗


原文:https://www.cnblogs.com/ppes/p/9461246.html 

一、官網的定義:

https://docs.scipy.org/doc/numpy/user/quickstart.html

In NumPy dimensions are called axes.

For example, the coordinates of a point in 3D space [1, 2, 1] has one axis. That axis has 3 elements in it, so we say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3.

[[ 1., 0., 0.],
 [ 0., 1., 2.]]

其實,可以這么理解。維度(dimension) D和數組A,D[axis]和A[i] 。是不是大概懂了,axis對應第幾維度,與數組的下標的作用差不多。但是axis有點區別的。既然axis是下標那么就有范圍:

[-維度,維度),如上例子axis的取值范圍 [-2,2),記住不包括2。

維度與axis的對應關系:axis是從最外層的 [] 數起來的,如上的例子,axis=0:第二維,axis=1:第一維。

二、驗證:

1 # 產生24個[0,50)的隨機整數,維度為3
2 x = np.random.RandomState(5).randint(50, size=[2, 3, 4])
3 print(x.ndim, x.shape, x.size)
4 print("x:\n", x)

選一個能夠使用到axis的函數:這里選用numpy.amax()(選出最大的元素),https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html#numpy.amax

為了方便理解,先從最內層開始

1 print("x[0][0]:\n", x[0][0])
2 print("axis=2: \n", np.amax(x, 2))

 

print("x[0]:\n", x[0])
print("axis=1: \n", np.amax(x, 1))

 

1 print("x:\n", x)
2 print("axis=0: \n", np.amax(x, 0))

很顯然,從axis=2,axis=1都挺好理解,但是axis=0就有點困惑了,而且這個僅僅是三維而已,那么四維、五維呢。

但是其實仔細觀察axis=2的第一個數字54是怎么來的呢?是從x[0][0][0]—x[0][0][4]比較而得。因此一共有3*4個。

同理axis=1時,比較的就是:x[0][0][0]—x[0][3][0]共3*5個

同理axis=2時,比較的是:x[0][0][0]—x[2][0][0],共4*5個

現在,是不是就對不同的axis的輸出的形狀或者說排列有一定的了解了?而且是不是體會到axis的作用了?我可是煩死那么多方括號了!!

 三、總結

最直觀的:函數所選的axis的值,就表明 x[][][] 的第幾個方塊號,從0開始,代表第一個[ ],即x[ ] [ ] [ ]

不足或者錯誤之處,歡迎指正!

 1 import numpy as np
 2 
 3 # 產生60個[0,60)的隨機整數,維度為3
 4 x = np.random.RandomState(5).randint(60, size=[3, 4, 5])
 5 print(x.ndim, x.shape, x.size)
 6 print("x:\n", x)
 7 print("x[0][0]:\n", x[0][0])
 8 print("axis=2: \n", np.amax(x, 2))
 9 
10 print("x[0]:\n", x[0])
11 print("axis=1: \n", np.amax(x, 1))
12 
13 print("x:\n", x)
14 print("axis=0: \n", np.amax(x, 0))
15 print("\n", np.amin(x, 0))
16 for i in range(4):
17     print(x[0][i][1])
全部代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM