Sub topic 3
Standardization: centering and scaling to unit variance
This chapter covers the z-score transform, which scikit-learn implements as StandardScaler. It assumes you know basic NumPy array operations, mean and standard deviation, the idea of training and test sets, and how a scikit-learn estimator is called. The fit/transform workflow and leakage get their own chapters. Here the focus is what the transform does to your data and why it behaves the way it does.
The idea in one sentence
Standardization re-expresses each numeric column as the number of standard deviations each value lies from that column's mean.
For a single column with mean μ and standard deviation σ, the transformed value of x is:
z = (x − μ) / σ
The formula does two separate things:
- Centering subtracts the mean. The new column has mean 0.
- Scaling divides by the standard deviation. The new column has standard deviation 1.
After both steps, the column is measured in "standard deviation units". A value of 0 means "exactly average". A value of 2 means "two standard deviations above average". A value of −1.5 means "one and a half standard deviations below average".
Computing it by hand
The statistics are computed per column, so the formula is applied once for every feature. In NumPy, axis=0 means "down the rows, one result per column".
import numpy as np
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
mean = X.mean(axis=0)
std = X.std(axis=0)
z = (X - mean) / std
print("mean:", mean)
print("std: ", std)
print(z)
print("column means:", z.mean(axis=0))
print("column stds: ", z.std(axis=0))The means are [2. 400.] and the standard deviations are about [0.8165 163.299]. The result is:
[[-1.2247 -1.2247]
[ 0. 0. ]
[ 1.2247 1.2247]]Both columns started on very different scales: one ranges over 1 to 3, the other over 200 to 600. After standardization they are identical. Standardization removes the unit (and the offset) of each column. It keeps the relative positions of the values within the column.
The printed column means may show tiny numbers such as 1e-17 instead of exactly 0. That is floating-point rounding, not a bug. Compare with np.allclose rather than ==.
What standardization preserves and what it changes
Standardization is an affine transformation: z = a·x + b for constants a and b that depend on the column. This has useful consequences:
- Order is preserved. If one value was larger than another before, it is larger afterward.
- Shape is preserved. A skewed column stays skewed. A column with two clusters keeps two clusters. Standardization does not make data normally distributed, despite the common name "normalization to a standard normal". It only gives the data the mean and spread of a standard normal.
- Ratios of distances within a column are preserved. A gap that was twice as large as another stays twice as large.
- Correlations between columns are unchanged. Pearson correlation is invariant to shifting and positive rescaling of each variable.
- Values are not bounded. A z-score can be 0.3 or 7.9. There is no fixed range, unlike min-max scaling.
Why unit variance helps
Many models combine features in ways that depend on their numeric size. A Euclidean distance, a gradient step, or a penalty on coefficients all treat "a change of 1" in every column as equally important. If one column is measured in dollars (range of thousands) and another in years (range of tens), the dollar column dominates distances and the year column is nearly ignored.
After standardization, each column has the same spread, so a "typical difference" in any column contributes comparably. Three effects are worth naming:
- Distance-based models (k-nearest neighbors, k-means, RBF-kernel SVMs) compute distances across all columns at once. Standardizing prevents the largest-scale column from deciding the neighbors.
- Gradient-based models (logistic regression, neural networks) converge faster and more reliably when features have similar scale, because the loss surface is less stretched.
- Regularized models (ridge, lasso, elastic net, regularized logistic regression) apply one penalty strength to all coefficients. A feature with a small numeric range needs a large coefficient to matter, so it gets penalized more. Standardizing makes the penalty fair across features.
Centering also matters on its own. Principal component analysis, for example, assumes centered data, and a model without an intercept term depends on it too.
Using `StandardScaler`
StandardScaler implements the same formula, but splits it into two phases. fit learns the statistics from data and stores them on the object. transform applies the stored statistics to any data.
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("mean_: ", scaler.mean_)
print("scale_: ", scaler.scale_)
print("var_: ", scaler.var_)
print("n_seen: ", scaler.n_samples_seen_)
print(X_std)The learned attributes end with an underscore, which is the scikit-learn convention for values estimated during fit:
| Attribute | Meaning |
|---|---|
| `mean_` | Per-column mean μ |
| `scale_` | Per-column standard deviation σ, the divisor actually used |
| `var_` | Per-column variance σ² |
| `n_samples_seen_` | Number of rows used during fitting |
The output equals the manual result from the previous section. The reason to use the class instead of the one-line formula is that the learned mean_ and scale_ are saved. You can apply the same μ and σ later to new data, which is essential in the next chapters on leakage and pipelines.
The standard deviation uses ddof=0
StandardScaler divides by the population standard deviation, which divides the sum of squared deviations by n. This is ddof=0, the default for np.std. The sample standard deviation divides by n − 1 (ddof=1). The default in pandas Series.std() is ddof=1.
This difference is a frequent cause of "my manual result doesn't match scikit-learn" questions. For small n the numbers differ visibly. For large n they converge.
import numpy as np
from sklearn.preprocessing import StandardScaler
x = np.array([[1.0], [2.0], [3.0], [4.0]])
pop = (x - x.mean()) / x.std(ddof=0)
samp = (x - x.mean()) / x.std(ddof=1)
sk = StandardScaler().fit_transform(x)
print(np.allclose(pop, sk)) # True
print(np.allclose(samp, sk)) # FalseIf you need sample standard deviation for a specific reason, compute it yourself. For model preprocessing the choice rarely matters, as long as you use the same one consistently from training to prediction.
Centering and scaling separately
The constructor has two switches, with_mean and with_std, both True by default.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
center_only = StandardScaler(with_std=False).fit_transform(X)
scale_only = StandardScaler(with_mean=False).fit_transform(X)
print(center_only)
print(scale_only)with_std=Falseonly subtracts the mean. Columns keep their original spread.with_mean=Falseonly divides by the standard deviation. Columns keep their offset and stay non-negative if they were non-negative.
Turning off centering matters mostly for sparse matrices, where subtracting a non-zero mean would turn the many zeros into non-zeros and destroy the memory savings. That case is covered in the edge-cases chapter. For ordinary dense data, leave both switches on.
Behavior to know about
Constant columns
If a column has the same value in every row, its standard deviation is 0 and the formula would divide by zero. StandardScaler handles this by setting the divisor to 1 for such columns. The column becomes all zeros after centering, with no error and no NaN.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 5.0],
[2.0, 5.0],
[3.0, 5.0]])
scaler = StandardScaler().fit(X)
print(scaler.scale_)
print(scaler.transform(X))The second entry of scale_ is 1.0, and the second column of the output is all zeros. A manual (X - mean) / std would produce nan there, so this is one place the class is safer than the formula.
A subtler problem appears when a column is constant in training data but varies in new data. The new values are shifted by the training mean and divided by 1, so they can come out large. Check for such columns during data validation.
Missing values
StandardScaler ignores NaN when computing the mean and standard deviation, and leaves NaN in place in the output. It does not impute. If your model cannot accept missing values, handle them with an imputer before or after scaling, depending on your design.
Output is not bounded
Because nothing clips the result, a new observation far from the training mean produces a large z-score. This is the correct signal ("this is unusual"), but it also means that a feature with outliers can still have extreme values after scaling. The outlier chapter returns to this.
Scaling the target
Standardization is normally applied to input features, not to the label y. For regression with some models, scaling y can help optimization, but then predictions must be mapped back to the original units with inverse_transform (or TransformedTargetRegressor). Do not standardize class labels in classification.
Checking your work
A quick sanity test after scaling the training data is to confirm the properties directly:
import numpy as np
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
X = rng.normal(loc=[10, -500], scale=[2, 80], size=(1000, 2))
Z = StandardScaler().fit_transform(X)
print(np.allclose(Z.mean(axis=0), 0))
print(np.allclose(Z.std(axis=0), 1))Both lines print True for the data the scaler was fitted on. On a separate test set, the mean and standard deviation will be close to 0 and 1 but not exactly, and that is expected. The test set is scaled with the training statistics, not its own. If a test set came out at exactly mean 0 and standard deviation 1, it would mean the scaler was refitted on it, which is a mistake.
When standardization is a good fit
Standardization is the usual default when:
- The model is sensitive to feature scale (distance-based, gradient-based, or regularized).
- Features are roughly bell-shaped or at least do not have extreme outliers.
- You do not need values inside a fixed interval.
It is a weaker choice when features have heavy outliers (the mean and standard deviation are both pulled by extreme values), or when an algorithm requires bounded input. Those cases are compared with min-max scaling in later chapters.
Summary
- Standardization computes z = (x − μ) / σ per column, giving mean 0 and standard deviation 1.
- It preserves order, shape and correlations, and does not bound the values.
StandardScalerlearnsmean_andscale_infitand reuses them intransform. It uses the population standard deviation (ddof=0).- Constant columns get a divisor of 1, and
NaNvalues are ignored during fitting and kept in the output. - Only the data the scaler was fitted on has exactly mean 0 and standard deviation 1.
Exercise
A feature in the training data has mean 50 and population standard deviation 8. A new observation has value 66. (a) What is its z-score under StandardScaler? (b) A second feature is constant at 7 in the training data. What does StandardScaler store in scale_ for it, and what does it output for a new value of 9?
Show answer
(a) z = (66 − 50) / 8 = 2.0, so the observation is two standard deviations above the training mean. (b) The standard deviation is 0, so StandardScaler stores a scale of 1.0 for that column. The mean is 7, so a new value of 9 becomes (9 − 7) / 1 = 2.0. No error or NaN is produced.
Exercise
You compute standardization manually with np.std(ddof=1) and compare the result with StandardScaler on a column of four values. The numbers do not match. What is the cause, and which argument gives a match?
Show answer
StandardScaler divides by the population standard deviation (ddof=0), while ddof=1 gives the larger sample standard deviation, so the manual z-scores are smaller in magnitude. Using x.std(ddof=0), which is the NumPy default, makes the results match.