Sub topic 3
Standardization: centering and scaling to unit variance
This chapter assumes you know Python and NumPy array operations, the mean and standard deviation, and the basic idea of training and test sets. You should also have seen a scikit-learn estimator before. Here you will learn what standardization does, how to compute it by hand, and which mistakes come up most often.
What standardization does
Standardization (also called the z-score transform) rewrites each value in a column as its distance from the column mean, measured in standard deviations. The formula is:
z = (x - mean) / std
It has two steps:
- Centering: subtract the column mean, so the new column has mean 0.
- Scaling: divide by the column standard deviation, so the new column has standard deviation 1.
The shape of the distribution does not change. Standardization shifts and stretches the values. It does not make a skewed column normal, and it does not bound the values to a fixed range. A value of 2.5 means "2.5 standard deviations above the mean", and any real number is possible.
Computing it by hand with NumPy
The statistics are computed per column, so you pass axis=0 to NumPy.
import numpy as np
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
# Standardization: (x - mean) / std, computed per column
z = (X - X.mean(axis=0)) / X.std(axis=0)
print(z)
print(z.mean(axis=0))
print(z.std(axis=0))Both columns become the same values, about -1.22, 0, and 1.22. The first column was in single digits and the second in hundreds, but after standardization they are on the same scale. That is the point: a model no longer sees the second column as 200 times more important just because its numbers are larger.
The means printed at the end are 0 up to floating-point error, so you may see something like 1e-17 instead of an exact zero. The standard deviations are 1.
The same result with StandardScaler
scikit-learn wraps this formula in StandardScaler. It learns the column means and standard deviations when you call fit, and stores them in the attributes mean_ and scale_.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
scaler = StandardScaler()
X_std = scaler.fit_transform(X)
print(scaler.mean_)
print(scaler.scale_)
print(X_std)mean_ is [2. 400.] and scale_ is the standard deviation of each column. X_std matches the hand computation above.
Common errors
Expecting a fixed range
Standardized values are not limited to [-1, 1] or [0, 1]. If you need a bounded range, that is the job of min-max scaling, covered in the next chapter.
Expecting a normal distribution
Standardization keeps the shape. A right-skewed column is still right-skewed afterwards, only with mean 0 and unit variance. If you need a more Gaussian shape, use a power or quantile transform instead.
Computing statistics on all the data
The mean and standard deviation are learned from data, so which data you use matters. If you fit on the full dataset before splitting into train and test sets, information from the test set leaks into preprocessing. A later chapter covers this in detail. For now, remember that the statistics belong to the training data.
Outliers inflate the statistics
The mean and standard deviation are both sensitive to extreme values. One large outlier raises the standard deviation, which squeezes the ordinary values toward each other after scaling. A later chapter compares this effect across scalers.
Constant columns
If every value in a column is identical, the standard deviation is 0 and the formula would divide by zero. StandardScaler detects this case and sets the scale to 1 for that column, so the output is a column of zeros instead of nan. You can verify this by looking at scale_ after fitting.
Checking that standardization worked
A quick test after scaling is to confirm the column means are near 0 and the standard deviations are near 1. Use np.allclose rather than exact equality, because of floating-point error.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[10.0, 1.0],
[20.0, 3.0],
[30.0, 5.0],
[40.0, 7.0]])
X_std = StandardScaler().fit_transform(X)
print(np.allclose(X_std.mean(axis=0), 0.0))
print(np.allclose(X_std.std(axis=0), 1.0))Both lines print True. Remember that this check holds for the data the scaler was fitted on. A test set scaled with training statistics will generally not have exactly mean 0 and standard deviation 1, and that is correct behavior.
Exercise
A column has the values 4, 8, 12 and 16. Compute the standardized value of 16 by hand, using the population standard deviation. Why is the result not guaranteed to lie between 0 and 1?
Show answer
The mean is 10. The population variance is ((-6)^2 + (-2)^2 + 2^2 + 6^2) / 4 = 80 / 4 = 20, so the standard deviation is about 4.472. The z-score of 16 is (16 - 10) / 4.472, which is about 1.342. Standardization only sets the mean to 0 and the standard deviation to 1. It does not bound values, so results can be negative or larger than 1.
Exercise
You fit a StandardScaler on a column where every value is 7. What is the learned scale_, and what does transform return for that column?
Show answer
scale_ is 1, because scikit-learn replaces a zero standard deviation with 1 to avoid dividing by zero. The column is centered, so transform returns all zeros.