Sub topic 3
Centering and standardizing your features
This chapter assumes you know mean, variance and correlation, can multiply matrices, and can work with a feature matrix X that has samples as rows and features as columns. You also need basic NumPy.
PCA looks for directions of maximum variance. Because of that, the scale and location of your columns change the answer. This chapter covers the two preprocessing steps that control this: centering and standardizing.
Why centering is required
Centering subtracts each column's mean, so every feature has mean zero. The covariance matrix is defined around the mean, and the principal components are directions through the center of the data cloud. If you skip centering, the first component tends to point from the origin toward the data's mean instead of along its spread.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(200, 2)) @ np.array([[2.0, 0.0], [0.0, 0.5]]) + [50.0, 80.0]
def first_axis(M):
vals, vecs = np.linalg.eigh(M.T @ M / (len(M) - 1))
return vecs[:, np.argmax(vals)]
print("uncentered:", first_axis(X))
print("centered: ", first_axis(X - X.mean(axis=0)))The uncentered axis points toward the mean (50, 80). The centered axis follows the real spread, which is along the first feature. Sign may differ, since an eigenvector and its negative are equivalent.
Why scale matters
Variance is measured in the units of each feature. A feature in grams has a far larger variance than the same quantity in kilograms. Without scaling, the feature with the largest numeric range dominates the first component, whatever its real importance.
Standardizing (z-scoring) fixes this. Each column is centered and divided by its standard deviation:
z = (x − mean) / std
Every feature then has mean 0 and variance 1. The covariance matrix of standardized data is the correlation matrix of the original data. So PCA on standardized data is PCA on correlations.
import numpy as np
rng = np.random.default_rng(2)
height_cm = rng.normal(170, 10, 300)
income = rng.normal(50_000, 15_000, 300) + 500 * (height_cm - 170)
X = np.column_stack([height_cm, income])
def explained(M):
vals = np.linalg.eigvalsh(np.cov(M, rowvar=False))[::-1]
return vals / vals.sum()
Xc = X - X.mean(axis=0)
Xz = Xc / X.std(axis=0, ddof=1)
print("centered only:", explained(Xc))
print("standardized: ", explained(Xz))
print(np.allclose(np.cov(Xz, rowvar=False), np.corrcoef(X, rowvar=False)))With centering only, income takes nearly all the variance, simply because its numbers are large. After standardizing, the split reflects how strongly the two features are correlated. The last line prints True, which confirms the covariance-correlation link.
When not to standardize
Standardizing is the safe default for mixed units. Skip it when the scale carries meaning. Pixel intensities in an image all share one unit, and a pixel with high variance really does carry more signal. Standardizing would boost noisy, near-constant pixels to the same weight as informative ones.
| Situation | Preprocessing |
|---|---|
| Features in different units | Center and standardize |
| Same units, variance is meaningful | Center only |
| Constant column (variance 0) | Remove it first |
Common errors
- Fitting the scaler on all the data. Compute means and standard deviations on the training set only, then apply them to test data. A pipeline does this for you.
- Dividing by zero. A constant column has standard deviation 0. Drop it before scaling.
- Mixing
ddof. NumPy'sstddivides by n by default, whilenp.covdivides by n − 1. The difference is small but breaks exact comparisons. The example above setsddof=1. - Scaling binary or one-hot columns without thought. It makes rare categories look large. Decide deliberately.
Exercise
A dataset has two features: weight in grams (variance about 4,000,000) and height in meters (variance about 0.04). You run PCA after centering only. Which feature will dominate the first component, and what single step fixes this?
Show answer
Weight will dominate, because its variance is far larger purely due to its units. Standardizing both columns (subtract the mean, divide by the standard deviation) gives each variance 1, so the components then reflect correlation structure instead of units.