PCA in Practice
The theory says "eigenvectors of the covariance matrix". In practice PCA is computed with an SVD, and it needs a few decisions: whether to standardize features, how to handle , how to whiten, and how to keep the signs of components stable. This lesson writes a small, complete PCA and checks it against the theory.
PCA through the SVD
For centred data with thin SVD :
so the principal directions are the columns of (rows of ), the variances are , and the codes are . Never forming avoids squaring the condition number, and the thin SVD costs .
import numpy as np
def pca(X, M):
mu = X.mean(axis=0)
Xc = X - mu
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
signs = np.sign(Vt[np.arange(len(Vt)), np.argmax(np.abs(Vt), axis=1)]) # deterministic signs
Vt = Vt * signs[:, None]
var = s**2 / len(X)
return mu, Vt[:M], var
rng = np.random.default_rng(0)
X = rng.multivariate_normal([5, -2, 0], [[4, 2, 0.5], [2, 3, 0.3], [0.5, 0.3, 0.5]], size=1000)
mu, comps, var = pca(X, 2)
lam = np.linalg.eigvalsh(np.cov(X.T, bias=True))[::-1]
print("variances from SVD:", np.round(var, 4))
print("eigenvalues of S: ", np.round(lam, 4))
Z = (X - mu) @ comps.T
print("codes shape:", Z.shape, " codes uncorrelated:", np.allclose(np.cov(Z.T, bias=True), np.diag(var[:2])))variances from SVD: [5.5236 1.3451 0.4479]
eigenvalues of S: [5.5236 1.3451 0.4479]
codes shape: (1000, 2) codes uncorrelated: True
The codes are uncorrelated, with variances equal to the top eigenvalues: PCA rotates the data so that the covariance becomes diagonal.
Standardize first?
PCA maximizes variance, so it is sensitive to units. A feature in grams has a million times the variance of the same feature in tonnes. When features have different units, standardize each to unit variance first, which is PCA on the correlation matrix.
import numpy as np
rng = np.random.default_rng(1)
height_m = rng.normal(1.7, 0.1, 500)
weight_g = 70000 + 400000 * (height_m - 1.7) + rng.normal(0, 8000, 500)
X = np.column_stack([height_m, weight_g])
for name, M in (("raw", X), ("standardized", (X - X.mean(0)) / X.std(0))):
Mc = M - M.mean(0)
_, s, Vt = np.linalg.svd(Mc, full_matrices=False)
print(f"{name:12s}: PC1 = {np.round(np.abs(Vt[0]), 4)}, explained ratio {s[0]**2 / np.sum(s**2):.4f}")raw : PC1 = [0. 1.], explained ratio 1.0000
standardized: PC1 = [0.7071 0.7071], explained ratio 0.9872
On raw units, the first component is just "weight in grams", because grams dominate the variance. After standardizing, both features contribute equally, revealing their correlation.
Whitening and
- Whitening divides each code by , giving unit variance in every direction: . Useful before algorithms that assume isotropic data, risky for tiny (noise gets amplified).
- With more features than examples (genes, pixels), at most eigenvalues are nonzero. The thin SVD handles this automatically; the eigendecomposition of the matrix would be wasteful.
In software
sklearn.decomposition.PCA(n_components, whiten=...)uses an SVD (randomized for large data) and fixes signs with a similar rule.- Put
StandardScalerbeforePCAin aPipelinewhen features have different units. IncrementalPCAprocesses data in batches when it does not fit in memory.
Go further: PCA in Practice: Scaling, Components and Pipelines covers the modelling decisions: whether to scale, how many components to keep and how to put PCA in a pipeline.
Exercises
Exercise 1: From singular values to variances
Centred data with rows has singular values . What are the PCA variances and the explained ratio of PC1?
Answer
; about .
Solution
: , , . Ratio .
Exercise 2: Rank with few samples
You run PCA on 30 images of 10,000 pixels each. At most how many components have nonzero variance?
Answer
Solution
Centring makes the 30 rows sum to zero, so the centred matrix has rank at most .
Exercise 3: Whitening (code)
Whiten correlated 2-D data with PCA and check that the result has identity covariance.
Answer
The whitened covariance is the identity matrix.
Solution
import numpy as np
rng = np.random.default_rng(3)
X = rng.multivariate_normal([0, 0], [[3.0, 1.5], [1.5, 2.0]], size=2000)
Xc = X - X.mean(0)
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
Zw = Xc @ Vt.T / (s / np.sqrt(len(X)))
print(np.round(np.cov(Zw.T, bias=True), 6) + 0)[[1. 0.]
[0. 1.]]
Test yourself
In the SVD of centred data, the principal directions are…
- the columns of
- the columns of
- the singular values
- the rows of
When should you standardize features before PCA?
- Never
- When features are measured in different units or scales
- Only for images
- Only when
After PCA, the codes of different components are…
- perfectly correlated
- uncorrelated
- identical
- always zero