TExcelTAD
Home › Math for Machine Learning › PCA in Practice

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 D≫ND \gg N, 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 Xc∈RN×DX_c \in \mathbb{R}^{N \times D} with thin SVD Xc=UΣVTX_c = U\Sigma V^T:

S=1NXcTXc=V Σ2N VTS = \frac{1}{N}X_c^TX_c = V\,\frac{\Sigma^2}{N}\,V^T

so the principal directions are the columns of VV (rows of VTV^T), the variances are σi2/N\sigma_i^2/N, and the codes are Z=XcV=UΣZ = X_cV = U\Sigma. Never forming XcTXcX_c^TX_c avoids squaring the condition number, and the thin SVD costs O(NDmin⁡(N,D))O(ND\min(N, D)).

python · try it yourself
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.

python · try it yourself
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 D≫ND \gg N

  • Whitening divides each code by λm\sqrt{\lambda_m}, giving unit variance in every direction: Zw=XcV diag⁡(λ)−1/2Z_w = X_cV\,\operatorname{diag}(\lambda)^{-1/2}. Useful before algorithms that assume isotropic data, risky for tiny λm\lambda_m (noise gets amplified).
  • With more features than examples (genes, pixels), at most N−1N - 1 eigenvalues are nonzero. The thin SVD handles this automatically; the eigendecomposition of the D×DD \times D 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 StandardScaler before PCA in a Pipeline when features have different units.
  • IncrementalPCA processes 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 N=100N = 100 rows has singular values 20,10,220, 10, 2. What are the PCA variances and the explained ratio of PC1?

Answer

4,1,0.044, 1, 0.04; about 79.4%79.4\%.

Solution

σ2/N\sigma^2/N: 400/100400/100, 100/100100/100, 4/1004/100. Ratio 4/5.04≈0.7944/5.04 \approx 0.794.

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 N−1=29N - 1 = 29.

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
python · try it yourself
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 Xc=UΣVTX_c = U\Sigma V^T of centred data, the principal directions are…

  1. the columns of UU
  2. the columns of VV
  3. the singular values
  4. the rows of XcX_c

When should you standardize features before PCA?

  1. Never
  2. When features are measured in different units or scales
  3. Only for images
  4. Only when N<DN < D

After PCA, the codes of different components are…

  1. perfectly correlated
  2. uncorrelated
  3. identical
  4. always zero