import numpy as np
# create x
x = np.asarray([1,2,3,4], dtype=np.float64)
np.mean(x) # calculates the mean of the array x
x-np.mean(x) # this is euivalent to subtracting the mean of x from each value in x
x-=np.mean(x) # the -= means can be read as x = x- np.mean(x)
np.std(x) # this calcualtes the standard deviation of the array
x/=np.std(x) # the /= means can be read as x = x/np.std(x)
遵循下面代码中的注释
根据给定的语法,我得出结论,数组是多维的。因此,我将首先讨论x只是一个线性数组的情况:
np.mean(x)
将计算平均值,通过广播x-np.mean(x)
将从所有条目中减去x
的平均值。x -=np.mean(x,axis = 0)
相当于x = x-np.mean(x,axis = 0). Similar for
x/np.std(x)`。对于多维数组,同样的事情也会发生,但不是计算整个数组的平均值,而是计算第一个“轴”的平均值。轴是维度的
numpy
单词。所以如果你的x
是二维的,那么np.mean(x,axis =0) = [np.mean(x[:,0], np.mean(x[:,1])...]
。广播将再次确保,这是对所有元素。注意,这只适用于第一个维度,否则形状将不匹配广播。如果要规范化wrt另一个轴,则需要执行以下操作:
这就是所谓的^{} 。
SciPy有一个实用程序:
相关问题 更多 >
编程相关推荐