Sub topic 5
Principal components: directions of maximum variance
This chapter assumes you know how to build a covariance matrix and center data, and that you know what an eigenvector is. It also assumes you can read basic NumPy. The earlier chapters on centering and eigenvectors cover those ideas. Here we use them to define principal components and show why they come out of an eigendecomposition.
The idea in one sentence
A principal component is a unit-length direction in feature space. When you project the centered data onto it, the projected values have the largest variance of any direction. The second component is the direction of largest remaining variance that is perpendicular to the first. The third is perpendicular to both, and so on.
Suppose your data matrix Xc has n rows (samples) and p columns (features), and each column has mean zero. A direction is a vector w with ‖w‖ = 1. Projecting every sample onto w gives n numbers, Xc @ w. The variance of those numbers is the quantity PCA maximizes.
Why the objective is a quadratic form
Let C be the sample covariance matrix:
C = Xcᵀ Xc / (n − 1)
The variance of the projection onto w is:
Var(Xc w) = wᵀ C w
This is a quadratic form. It expands to Σᵢⱼ wᵢ wⱼ Cᵢⱼ. The diagonal entries of C weight the variance of each feature. The off-diagonal entries reward directions that follow correlated features. That is why correlated features produce a strongly preferred direction.
PCA solves this problem:
maximize wᵀ C w subject to wᵀ w = 1
The constraint matters. Without it you could scale w up and the variance would grow without bound.
Deriving the answer with a Lagrange multiplier
Write the Lagrangian with multiplier λ:
L(w, λ) = wᵀ C w − λ (wᵀ w − 1)
Set the gradient with respect to w to zero. Because C is symmetric, the gradient is 2 C w − 2 λ w = 0, so:
C w = λ w
Any maximizer must be an eigenvector of C. Now multiply on the left by wᵀ and use wᵀ w = 1:
wᵀ C w = λ
The variance along an eigenvector equals its eigenvalue. To make the variance as large as possible, pick the eigenvector with the largest eigenvalue. That is the first principal component.
For later components, add the constraint that w is orthogonal to the earlier ones. A symmetric matrix has orthogonal eigenvectors for distinct eigenvalues, so the solution is the next eigenvector in order of decreasing eigenvalue.
What you get from the decomposition
Because C is real and symmetric, the spectral theorem gives:
C = W Λ Wᵀ
Whas the eigenvectors as columns. They are orthonormal, soWᵀ W = I.Λis diagonal, with eigenvaluesλ₁ ≥ λ₂ ≥ … ≥ λₚ ≥ 0.- Every eigenvalue is nonnegative, because
Cis positive semidefinite (wᵀ C wis a variance and cannot be negative).
The new coordinates of the data are the scores, T = Xc W. Their covariance is:
Tᵀ T / (n − 1) = Wᵀ C W = Λ
So the scores are uncorrelated, and the variance of score column k is λₖ. This is the sense in which PCA replaces correlated features with uncorrelated ones. The total variance is unchanged, because trace(C) = Σ λₖ. PCA only redistributes it, piling as much as possible into the first few components.
Verifying it numerically
The following script builds correlated data, computes the components, and checks the claims above. It checks that the variance along the first component equals the top eigenvalue and that no random direction beats it. It also checks that the components are orthonormal and that the score covariance is diagonal.
import numpy as np
rng = np.random.default_rng(0)
mixing = np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
X = rng.normal(size=(200, 3)) @ mixing
Xc = X - X.mean(axis=0)
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
def variance_along(w):
return np.var(Xc @ w, ddof=1)
w1 = eigvecs[:, 0]
print("variance along w1:", variance_along(w1))
print("largest eigenvalue:", eigvals[0])
dirs = rng.normal(size=(1000, 3))
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
best_random = max(variance_along(d) for d in dirs)
print("best of 1000 random directions:", best_random)
print("w1 wins:", best_random <= eigvals[0] + 1e-9)
print("W^T W:")
print(np.round(eigvecs.T @ eigvecs, 10))
scores = Xc @ eigvecs
print("covariance of scores:")
print(np.round(np.cov(scores, rowvar=False), 6))Expect the first two printed values to match. Expect w1 wins to print True. Expect W^T W to be the identity and the score covariance to be diagonal with the eigenvalues on its diagonal.
Use np.linalg.eigh here, not np.linalg.eig. It is written for symmetric matrices, returns real values, and guarantees orthonormal eigenvectors. It returns eigenvalues in ascending order, which is why the script re-sorts them.
The geometry: rotating the axes
The matrix W is orthogonal, so Xc W rotates (and possibly reflects) the data without stretching it. PCA is a change of basis to axes aligned with the data's spread. In two dimensions with a tilted elliptical cloud, the first component points along the long axis of the ellipse. The second points along the short axis. The eigenvalues are the variances along those axes, so the ellipse's semi-axis lengths scale with √λ.
Dropping the last components then amounts to flattening the cloud onto its widest subspace. The next chapters in this tutorial measure how much that flattening costs.
Uniqueness, signs and ties
Several details of principal components are not fixed by the math.
- Sign ambiguity. If
wis an eigenvector, so is−w. Libraries pick a sign by convention or by an implementation detail, and the choice can change between versions or machines. Never compare loadings between runs without checking signs. - Repeated eigenvalues. If
λₖ = λₖ₊₁, any orthonormal basis of the shared eigenspace is valid. The data has no preferred direction inside that plane, as with a circular cloud. The individual components are then arbitrary, though the subspace they span is not. - Near-ties. If two eigenvalues are close, small changes in the data can rotate their components a lot. Components with nearly equal variance are unstable, even when the span of the pair is stable.
- Zero eigenvalues. If features are exactly linearly dependent, or
n ≤ p, some eigenvalues are zero. Their eigenvectors point in directions where the data has no spread at all. Withnsamples, the centered data has rank at mostn − 1. - Numerical noise. Tiny negative eigenvalues such as
-1e-17can appear from rounding. Treat them as zero.
Common mistakes
- Forgetting to center. The formula
C = Xcᵀ Xc / (n − 1)only measures variance about the mean if the columns have mean zero. If you skip centering, the first component can simply point toward the data's mean offset from the origin. - Using
eighoutput in the wrong order. The columns ofeigvecsare the eigenvectors, not the rows. The first principal component iseigvecs[:, 0]after sorting, noteigvecs[0]. - Confusing the rows and columns of the data.
np.covtreats rows as variables by default. For a samples-by-features matrix, passrowvar=False. - Reading components as causes. A component is a weighted mix of features chosen to maximize variance. It need not correspond to any real process.
- Assuming high variance means high importance. PCA is unsupervised. A low-variance direction may be exactly what separates your classes. See the limitations chapter.
Summary of the working model
| Quantity | Meaning | How to get it |
|---|---|---|
| Principal component `wₖ` | Unit direction of the k-th largest variance | Column k of the sorted eigenvector matrix of `C` |
| Eigenvalue `λₖ` | Variance of the data along `wₖ` | Sorted eigenvalue of `C` |
| Score column `k` | Coordinates of each sample along `wₖ` | `Xc @ wₖ` |
| Total variance | Sum of all feature variances | `trace(C) = Σ λₖ` |
Exercise
A centered dataset has covariance matrix C = [[4, 0], [0, 1]]. What is the first principal component, and what is the variance of the data projected onto the direction (1, 1)/√2?
Show answer
C is diagonal, so its eigenvectors are the coordinate axes. The largest eigenvalue is 4, so the first principal component is (1, 0) (or (−1, 0)). For w = (1, 1)/√2, wᵀ C w = (4 + 1)/2 = 2.5. This is less than 4, as it must be, because no direction can have more variance than the top eigenvalue.
Exercise
You run PCA twice on the same data with different library versions. The eigenvalues match, but the first component is (0.8, 0.6) in one run and (−0.8, −0.6) in the other. Is something wrong?
Show answer
No. If w is an eigenvector then −w is too, and both give the same variance. The sign is arbitrary. The scores for that component flip sign between the runs, and the subspace they span is identical.
Exercise
The covariance matrix of centered data is the 2 × 2 identity matrix. What are the principal components?
Show answer
Both eigenvalues are 1, so the eigenvalue is repeated and every unit direction has variance 1. Any orthonormal pair of vectors is a valid set of principal components. The data has no preferred direction, so the components are not unique.