在numpy数组中沿轴的和

Tar*_*mar 11 python numpy multidimensional-array

我想了解这个ndarray.sum(axis =)是如何工作的.我知道axis = 0用于列,axis = 1用于行.但是在3维(3轴)的情况下,难以解释下面的结果.

arr = np.arange(0,30).reshape(2,3,5)

arr
Out[1]: 
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14]],

       [[15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]]])

arr.sum(axis=0)
Out[2]: 
array([[15, 17, 19, 21, 23],
       [25, 27, 29, 31, 33],
       [35, 37, 39, 41, 43]])


arr.sum(axis=1)
Out[8]: 
array([[15, 18, 21, 24, 27],
       [60, 63, 66, 69, 72]])

arr.sum(axis=2)
Out[3]: 
array([[ 10,  35,  60],
       [ 85, 110, 135]])
Run Code Online (Sandbox Code Playgroud)

在这个3轴形状阵列(2,3,5)的例子中,有3行5列.但是,如果我整个看这个数组,似乎只有两行(都有3个数组元素).

任何人都可以解释这个总和如何在3轴或更多轴(维度)的数组上工作.

MSe*_*ert 6

如果要保留可以指定的尺寸keepdims:

>>> arr = np.arange(0,30).reshape(2,3,5)
>>> arr.sum(axis=0, keepdims=True)
array([[[15, 17, 19, 21, 23],
        [25, 27, 29, 31, 33],
        [35, 37, 39, 41, 43]]])
Run Code Online (Sandbox Code Playgroud)

否则,您从中求和的轴将从形状中移除.跟踪这个的简单方法是使用该numpy.ndarray.shape属性:

>>> arr.shape
(2, 3, 5)

>>> arr.sum(axis=0).shape
(3, 5)  # the first entry (index = axis = 0) dimension was removed 

>>> arr.sum(axis=1).shape
(2, 5)  # the second entry (index = axis = 1) was removed
Run Code Online (Sandbox Code Playgroud)

如果需要,还可以沿多个轴求和(按指定轴的数量减少维数):

>>> arr.sum(axis=(0, 1))
array([75, 81, 87, 93, 99])
>>> arr.sum(axis=(0, 1)).shape
(5, )  # first and second entry is removed
Run Code Online (Sandbox Code Playgroud)


Psi*_*dom 5

这是另一种解释方式。您可以将多维数组视为张量,T[i][j][k],而 i、j、k 分别表示轴0,1,2

T.sum(axis = 0)数学上相当于:

在此输入图像描述

类似地,T.sum(axis = 1)

在此输入图像描述

和,T.sum(axis = 2)

在此输入图像描述

换句话说,轴将被求和,例如,axis = 0第一个索引将被求和。如果写在for循环中:

result[j][k] = sum(T[i][j][k] for i in range(T.shape[0])) for all j,k
Run Code Online (Sandbox Code Playgroud)

为了axis = 1

result[i][k] = sum(T[i][j][k] for j in range(T.shape[1])) for all i,k
Run Code Online (Sandbox Code Playgroud)

ETC。