1. 程式人生 > >numpy中多維陣列的軸(axis)

numpy中多維陣列的軸(axis)

多維陣列的軸(axis=)是和該陣列的size(或者shape)的元素是相對應的;


>>> np.random.seed(123)
>>> X = np.random.randint(0, 5, [3, 2, 2])
>>> print(X)


[[[5 2]
  [4 2]]


 [[1 3]
  [2 3]]


 [[1 1]
  [0 1]]]


>>> X.sum(axis=0)
array([[7, 6],
       [6, 6]])


>>> X.sum(axis=1)
array([[9, 4],
       [3, 6],
       [1, 2]])


>>> X.sum(axis=2)
array([[7, 6],
       [4, 5],
       [2, 1]])


如果將三維陣列的每一個二維看做一個平面(plane,X[0, :, :], X[1, :, :], X[2, :, :]),三維陣列即是這些二維平面層疊(stacked)出來的結果。則(axis=0)表示全部平面上的對應位置,(axis=1),每一個平面的每一列,(axis=2),每一個平面的每一行。


考察多維陣列的dot運算


numpy.dot(a, b, out=None)


For 2-D arrays it is equivalent to matrix multiplication,


兩個二維陣列的dot運算遵循矩陣乘法(其實一個二維一個一維也是矩陣乘法(Ax))


and for 1-D arrays to inner product of vectors (without complex conjugation).


兩個一維陣列的dot運算執行的是內積運算(對應位相乘相加)


For N dimensions it is a sum product over the last axis of a and the second-to-last of b。


dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) 
a的最後一軸與b的倒數第二軸,(而 np.tensordot 可靈活地指定相互作用的兩個矩陣的任意軸) 
這不正是著名的 Am×n⋅Bn×p,A 的每一行乘以 B的每一列;


>>> X.dot([1, 1])
array([[7, 6],
       [4, 5],
       [2, 1]])
# X的最後一軸是每一個二維的行方向


此時如果我們想通過矩陣與向量(一維)內積的方式實現(np.sum(X, axis=0)的結果)需使用np.tensordots(X, [1, 1, 1], axes=([0], [0])),具體的用法見 np.tensordots文件。


>>> np.tensordots(X, [1, 1, 1], axes=([0], [0]))


array([[7, 6],
       [6, 6]])


我們再來看看如何實現多維陣列求平均的動作(每一個二維平面對應位的平均):


>>> X = np.random.randint(0, 5, [3, 2, 2])
>>> X
array([[[3, 4],
        [2, 2]],


       [[3, 4],
        [2, 3]],


       [[2, 1],
        [1, 3]]])


>>> np.tensordot(X, [1/3, 1/3, 1/3], axes=([0], [0]))
array([[ 2.66666667,  3.        ],
       [ 1.66666667,  2.66666667]])