np.sum()
时,总是对 axis
参数的运用不是很清楚,所以特意做了个小实验了解了一番。
首先从源码的说明文档处可以看出,axis
就是求和的“轴”,即沿着axis
方向进行求和。
axis : None or int or tuple of ints, optional
Axis or axes along which a sum is performed. The default,
axis=None, will sum all of the elements of the input array. If
axis is negative it counts from the last to the first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, a sum is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before.
对下面的这个三维数组来说,它的shape为(2,3,2)
import numpy as np
a=np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]])
print(a.shape)
>>>(2, 3, 2)
我们分别从axis=0, 1, 2方向对该三维数组求和,并打印出它们的shape:
原始数组[[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]]
的shape为(2,3,2),分别对应三维坐标中每一【行、列、层】里面的元素个数。
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]
[[ 8 10]
[12 14]
[16 18]]
② 当axis=1时,去掉中间的那层[]
,按【列】的方向进行求和:同一【列】的元素相加,然后【列】这一维就没有了。
(2,3,2)——>(2,2)
[[ 9 12]
[27 30]]
③ 当axis=2时,去掉最内的[]
,按【行】的方向进行求和:同一【行】的相加,然后【行】这一维就没有了;由于【列】、【层】前面的维度消失了,所以都往前挪一维。
(2,3,2)——>(3,2)—前挪—>(2,3)
[[ 3 7 11]
[15 19 23]]
事实上,这个axis的数值叫做数值的trailing dimension(后缘维度),即从末尾开始算起的第几个维度。
axis
也可以是二维的,以axis=(0,1)
为例,即沿最外两层【层】【列】都进行相加。显然这种情况下相加的结果是一维的,即只剩一个一维向量了。并且可以看到,axis=(0,1)
和axis=(0,1)
的结果是相同的