Sub topic 3
Centering and standardizing your features
PCA finds directions of large variance, so the numbers you give it decide which directions it finds. This chapter covers the two preprocessing steps that control this: centering and standardizing. It assumes you know mean, variance and correlation, can multiply matrices, and can read a feature matrix with samples as rows and features as columns. You should also have read the previous chapter on the covariance matrix.
Centering: subtract the mean
Centering means subtracting each column's mean from that column, so every feature averages to zero. In NumPy, that is Xc = X - X.mean(axis=0).
The covariance matrix is defined in terms of deviations from the mean. If you skip centering and compute X.T @ X / n, you get the matrix of second moments about the origin. That matrix mixes the spread of the data with the location of the data. When the cloud sits far from the origin, the largest "variance" is the direction from the origin to the cloud's center, and the first component points there instead of along the data's real spread.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 2)) @ np.array([[1.0, 0.0],
[0.0, 0.3]]) + np.array([10.0, 10.0])
def top_axis(M):
vals, vecs = np.linalg.eigh(M)
return np.abs(vecs[:, -1]) # eigh sorts ascending; abs removes sign ambiguity
second_moment = X.T @ X / len(X)
cov = np.cov(X, rowvar=False)
print("uncentered:", top_axis(second_moment))
print("centered: ", top_axis(cov))The data spread mostly along the first axis, with a standard deviation of 1 against 0.3. The uncentered result comes out close to [0.71, 0.71], which is the direction toward the point (10, 10). The centered result comes out close to [1, 0], the real axis of spread.
Centering has a second job at projection time. The scores are Xc @ components.T, which measure displacement from the mean. To reconstruct, you add the mean back, as you saw in the projection chapter.
Standardizing: divide by the standard deviation
Standardizing (also called z-scoring) centers each feature and then divides it by its standard deviation. Every feature ends up with mean 0 and variance 1.
Variance depends on units. A distance recorded in millimeters has a variance one million times larger than the same distance recorded in kilometers. PCA only sees the numbers, so a feature measured on a large scale dominates the first component regardless of how informative it is.
The wine dataset in scikit-learn shows this. One of its 13 features, proline, has values in the hundreds or thousands. The others are mostly between 0 and 30.
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, _ = load_wine(return_X_y=True)
raw = PCA().fit(X)
std = PCA().fit(StandardScaler().fit_transform(X))
print("raw first ratios: ", raw.explained_variance_ratio_[:3].round(3))
print("scaled first ratios:", std.explained_variance_ratio_[:3].round(3))
print("raw PC1 weight on proline:", abs(raw.components_[0, -1]).round(3))On raw data the first component explains about 99.8% of the variance, and its weight on proline is almost 1. That component is essentially the proline column. After standardizing, the first component explains about 36%, and the variance is spread over several components, which reflects the real structure of the data.
Standardized PCA is PCA on the correlation matrix
After standardizing, the covariance matrix of the data is the correlation matrix. Its diagonal is all ones, so the eigenvalues sum to the number of features p. The following check confirms the relationship. StandardScaler divides by n, while np.cov divides by n - 1, so the two differ by a factor of (n - 1) / n.
import numpy as np
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
X, _ = load_wine(return_X_y=True)
n, p = X.shape
Z = StandardScaler().fit_transform(X)
corr = np.corrcoef(X, rowvar=False)
print(np.allclose(np.cov(Z, rowvar=False) * (n - 1) / n, corr))
print(np.linalg.eigvalsh(corr).sum()) # equals p = 13, up to roundingThis gives a quick sanity check: if you run PCA on standardized data and the eigenvalues do not sum to p, something is off. It also gives a rule of thumb. A component with an eigenvalue below 1 explains less variance than a single original standardized feature.
Choosing between centering only and standardizing
| Situation | What to do | Reason |
|---|---|---|
| Features in different units (years, dollars, grams) | Standardize | Otherwise the largest numeric scale wins |
| Features in the same unit and the scale carries meaning (pixel intensities, gene counts on one scale) | Center only | Dividing by the standard deviation would inflate noisy, low-variance features |
| One feature has outliers | Clip or use a robust scaler such as `RobustScaler` | Mean and standard deviation are pulled by extreme values |
| Feature is constant | Drop it | Its variance is zero and it carries no information |
| Sparse matrix | Use `StandardScaler(with_mean=False)` and `TruncatedSVD` | Centering makes a sparse matrix dense |
Pixel data is the standard case for centering only. In the digits dataset all 64 features are intensities on the same 0 to 16 scale. Some border pixels are almost always 0 and vary very little. Standardizing would stretch those nearly empty pixels to unit variance and give noise the same weight as strokes. The code example in the "choosing components" chapter standardizes the digits anyway to keep the example simple. Treat that as a modeling choice you can revisit.
Standardizing is a statement about what you care about. It says that a one-standard-deviation move in any feature counts equally. If that is not true of your problem, think before applying it by default.
What scikit-learn does for you
PCA in scikit-learn centers the data internally. It stores the column means in pca.mean_ and subtracts them in transform. It does not scale. If you want standardization, you add it yourself.
This leads to a common mistake: centering by hand and then passing the result to PCA. That is harmless but redundant. The opposite mistake is assuming PCA standardizes. It does not, as the wine example shows.
StandardScaler has two behaviors worth knowing:
- It uses the population standard deviation (
ddof=0). Pandas'.std()usesddof=1. The difference is small for largenbut shows up when you compare results across libraries. - For a constant column, it sets the scale to 1 instead of dividing by zero. The column becomes all zeros and no error is raised, so a dead feature can pass through silently.
Fit the scaler on training data only
The mean and standard deviation are parameters learned from data, just like the components. If you fit the scaler on the full dataset before splitting, information from the test set leaks into training. Fit on the training set, then apply those same parameters to everything else.
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, _ = load_wine(return_X_y=True)
X_train, X_test = train_test_split(X, test_size=0.3, random_state=0)
scaler = StandardScaler().fit(X_train)
print(scaler.transform(X_train).mean(axis=0).round(3)) # all zeros
print(scaler.transform(X_test).mean(axis=0).round(3)) # close to zero, not exact
pipe = make_pipeline(StandardScaler(), PCA(n_components=2)).fit(X_train)
test_scores = pipe.transform(X_test)
print(test_scores.shape)The test means are close to zero but not exactly zero. That is correct. A new sample should be judged against the training population, not against itself. If you standardize the test set with its own statistics, you shift each feature by a different amount than the model saw, and the scores are no longer comparable. A pipeline avoids this mistake, because fit learns the scaler and the PCA together and transform reuses both.
Common errors
- Standardizing after PCA. The order is scale first, then project. Scaling the scores changes nothing useful, because the components are already uncorrelated.
- Standardizing one-hot columns. A rare category gets a huge standardized value in the rows where it appears. Decide deliberately whether that is what you want.
- Comparing explained variance across preprocessing choices. A ratio of 0.998 on raw data and 0.36 on scaled data are not comparable. They describe different matrices.
- Reading loadings without remembering the scaling. On standardized data, a loading refers to standard-deviation units of the original feature. On raw data it refers to the original unit.
Exercise
A dataset has two features: annual income in dollars (values around 50,000, standard deviation 15,000) and age in years (values around 40, standard deviation 10). You run PCA on the centered but unscaled data. Which feature will dominate the first component, and what single change would make the two features contribute on equal terms?
Show answer
Income dominates, because its variance (about 225,000,000) is over a million times larger than the variance of age (about 100), so the first component points almost entirely along income. Standardizing both features (dividing each centered column by its standard deviation) gives each a variance of 1, so PCA then works on the correlation matrix and neither feature wins because of its units.
Exercise
You standardize a dataset with StandardScaler, then compute np.cov(Z, rowvar=False) and find the diagonal entries are slightly above 1 (for example 1.002) instead of exactly 1. Why, and is it a bug?
Show answer
It is not a bug. StandardScaler divides by the population standard deviation (ddof=0), while np.cov divides by n - 1 by default. The diagonal equals n / (n - 1), which is slightly above 1. Multiplying the covariance by (n - 1) / n, or passing ddof=0 to np.cov, gives exactly 1.