np.mean()注释截取
"""
axis : None or int or tuple of ints, optional
Axis or axes along which the means are computed. The default is to
compute the mean of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a mean is performed over multiple axes,
instead of a single axis or all the axes as before.
>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0)
array([2., 3.])
>>> np.mean(a, axis=1)
array([1.5, 3.5])
"""
看完还是有点懵? 没关系,继续往下看
通俗解释
这个axis其实就是你要求mean的轴。我建议从array的shape来理解。
例子:
b = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
[[9, 10], [11, 12]]])
np.mean(b, axis=0)
"""
Out:
array([[5., 6.],
[7., 8.]])
"""
np.mean(b, axis=1)
"""
Out:
array([[ 2., 3.],
[ 6., 7.],
[10., 11.]])
"""
np.mean(b, axis=2)
"""
array([[ 1.5, 3.5],
[ 5.5, 7.5],
[ 9.5, 11.5]])
"""
一点点来解释:
- b的shape: (3, 2, 2)
- axis=0, 1, 2分别表示对3, 2, 2表示的轴来求mean
- 由此不难理解,为什么得到的矩阵中元素的数量分别为: 4, 6, 6。如果axis=0, 表示以3的那个轴来求mean,那么剩下的元素是2*2 = 4。其他同理
- 那么怎么理解输出矩阵中每个位置的值呢?对哪个轴求mean就可以想象为哪个轴设为变量。例如,axis = 1时输出矩阵中第一个元素其实是对b[0][x][0]来求的mean。也就是(1+3)/2。其他同理。
axis输入为tuple的情况
np.mean(b, axis=(1, 2))
"""
Out:
array([ 2.5, 6.5, 10.5])
"""
这其实和上面的情况刚好相反。此时就是把剩下的那个轴当作变量,对其他两个轴构成的元素来求mean。输出矩阵的形状就是剩下的轴。
对上面的情况,剩下了axis=0,输出其实就是b[x][0-1][0-1] (x取0 1 2),后面两个维度就是里面所有元素的mean。