【Numpy】不再迷茫!np.mean() axis参数通俗解释。

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。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小丫么小阿豪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值