numpy.sum(a, axis=None, dtype=None, out=None, keepdims=, initial=)[source])用于计算array元素的和.
python中常用的numpy进行数学计算,其中array的求和运算分为两种,一种是调用numpy.array
自身的sum()
方法,另一种是利用numpy的内建函数numpy.sum()
使用。(tips:python从0开始计数axis=0对应第一个维度)
#example
import numpy as np
x = np.random.rand(2,3,4) #生成三维随array
print("This is a 2*3rows 4cols array
",x)
'''
>>> This is a 2*3rows 4cols array
[[[ 0.88264952 0.12446208 0.82166137 0.31747846]
[ 0.51436626 0.03051283 0.46987831 0.64086531]
[ 0.14819094 0.6395191 0.21753309 0.61340538]]
[[ 0.0878878 0.5317064 0.65523138 0.704961 ]
[ 0.51081521 0.88710145 0.92958269 0.89587262]
[ 0.60233393 0.26146419 0.26584161 0.0823285 ]]]
'''
print('instance method:',x.sum())
print('numpy function:',np.sum(x))
'''
>>> 'instance method:', 11.835649415181807
>>> 'numpy function:', 11.835649415181807
'''
#对特定的轴求和
print('First axis sum',x.sum(axis=0))
'''
>>> 'First axis sum', #第一维是轴0,对前后两页array加和得到3*4的array输出
array([[ 0.97053732, 0.65616848, 1.47689275, 1.02243946],
[ 1.02518147, 0.91761428, 1.399461 , 1.53673793],
[ 0.75052486, 0.90098329, 0.4833747 , 0.69573388]])
'''
print('Second axis sum',x.sum(axis=1))
'''
>>> 'Second axis sum', #第二维是轴1,将每列的三行进行sum(对行求sum),得到2*4的输出
array([[ 1.54520672, 0.79449401, 1.50907277, 1.57174914],
[ 1.20103694, 1.68027204, 1.85065568, 1.68316212]])
'''
print('Third axis sum',x.sum(axis=2))
'''
>>> 'Third axis sum', #第三维是轴2,有4个数,将每行四个数加和(对列求sum),得到2*3输出
array([[ 2.14625142, 1.65562271, 1.6186485 ],
[ 1.97978658, 3.22337197, 1.21196823]])
'''
#对多个轴求和
print('axis1,2 sum:',x.sum(axis=(1,2)))
'''
>>> 'axis1,2 sum: #对第二维(axis=1)和第三维(axis=2)求和,归在第一维(axis=0)上
array([ 5.42052263, 6.41512678])
'''
ref:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html
https://blog.csdn.net/Leekingsen/article/details/76242244
https://blog.csdn.net/addmana/article/details/78472608