赞
踩
参考:https://blog.csdn.net/m0_37561765/article/details/78187700
首先官网里有写:
numpy.mean(a, axis=None, dtype=None, out=None, keepdims= )
Compute the arithmetic mean along the specified axis.
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.
这里就说明axis值为整数或者元组(类似于(0,1,2))这种。
对于二维的矩阵,axis只有0,1两个参数,其中axis=0为按列求平均,axis=1为按行求平均,不给出axis不是默认axis为0,而是把所有元素加起来求平均.
在这里引用博客里最多的一句话,axis等于几,就理解成对那一维值进行压缩,如一个3×2的矩阵,axis=0,则输出为1*2的向量,对列进行操作。同理对4维tensor如[128,28,28,3] 设置axis=(0,1,2)输出为[1,1,1,3]沿着最后一个维度取平均。
- import numpy as np
- X = np.array([[1, 2], [3, 4], [5, 6]])
- print np.mean(X, axis=0, keepdims=True)
- print np.mean(X, axis=1, keepdims=True)
- print np.mean(X)
运行结果如下
- [[ 3. 4.]]
-
- [[ 1.5]
- [ 3.5]
- [ 5.5]]
-
- 3.5
方差同理:
- import numpy as np
- X = np.array([[1, 2], [3, 4], [5, 6]])
- print np.var(X, axis=0, keepdims=True)
- print np.var(X, axis=1, keepdims=True)
- print np.var(X)
-
- 运行结果如下:
-
- [[ 2.66666667 2.66666667]]
- [[ 0.25]
- [ 0.25]
- [ 0.25]]
- 2.91666666667
应该注意的是方差的特殊性,对行和列求的的方差进行平均不等于整体数据的方差,用np.var要搞清楚所求的到底是什么?
- import numpy as np
- X = np.array([[1, 4], [3, 8], [5, 9]])
- print np.var(X, axis=0, keepdims=True)
- print np.var(X, axis=1, keepdims=True)
- print np.var(X)
- print np.mean(np.var(X, axis=0))
- print np.mean(np.var(X, axis=1))
-
- 运行结果如下:
-
- [[ 2.66666667 4.66666667]]
- [[ 2.25]
- [ 6.25]
- [ 4. ]]
- 7.66666666667
- 3.66666666667
- 4.16666666667
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。