I saw in tutorial (there were no further explanation) that we can process data to zero mean with x -= np.mean(x, axis=0)
and normalize data with x /= np.std(x, axis=0)
. Can anyone elaborate on these two pieces on code, only thing I got from documentations is that np.mean
calculates arithmetic mean calculates mean along specific axis and np.std
does so for standard deviation.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Follow the comments in the code below
This is also called
zscore
.SciPy has a utility for it:
Key here are the assignment operators. They actually performs some operations on the original variable. a += c is actually equal to a=a+c.
So indeed a (in your case x) has to be defined beforehand.
Each method takes an array/iterable (x) as input and outputs a value (or array if a multidimensional array was input), which is thus applied in your assignment operations.
The axis parameter means that you apply the mean or std operation over the rows. Hence, you take values for each row in a given column and perform the mean or std. Axis=1 would take values of each column for a given row.
What you do with both operations is that first you remove the mean so that your column mean is now centered around 0. Then, when you divide by std, you happen to reduce the spread of the data around this zero, and now it should roughly be in a [-1, +1] interval around 0.
So now, each of your column values is centered around zero and standardized.
There are other scaling techniques, such as removing the minimal or maximal value and dividing by the range of values.
From the given syntax you have I conclude, that your array is multidimensional. Hence I will first discuss the case where your x is just a linear array:
np.mean(x)
will compute the mean, by broadcastingx-np.mean(x)
the mean ofx
will be subtracted form all the entries.x -=np.mean(x,axis = 0)
is equivalent tox = x-np.mean(x,axis = 0). Similar for
x/np.std(x)`.In the case of multidimensional arrays the same thing happens, but instead of computing the mean over the entire array, you just compute the mean over the first "axis". Axis is the
numpy
word for dimension. So if yourx
is two dimensional, thennp.mean(x,axis =0) = [np.mean(x[:,0], np.mean(x[:,1])...]
. Broadcasting again will ensure, that this is done to all elements.Note, that this only works with the first dimension, otherwise the shapes will not match for broadcasting. If you want to normalize wrt another axis you need to do something like: