Week 05 · Eigenvalues, covariance, and PCA
Derive the principal axes of a small dataset and measure how much variance a one-dimensional projection retains.
Subject contents · Week 4 · Week 6
Derive the principal axes of a small dataset and measure how much variance a one-dimensional projection retains.
Find a useful view of a cloud of points
Suppose you measure two features that often increase together. Plotting the first feature alone throws away all changes in the second. Rotating the axes first lets one coordinate capture what the two features do together. Principal component analysis (PCA) chooses that rotation from the data.
Here you will build the covariance matrix, find its two principal directions, and decide what a one-coordinate representation loses. PCA ranks directions by variance. If you are building a predictor, a direction with low variance can still be important for the target, so retained variance is a reconstruction measure rather than a guarantee of predictive quality.
The idea
Centering subtracts each feature’s mean. If the centered data matrix X has n rows, the empirical covariance matrix used here is C = XᵀX/n. The diagonal contains the feature variances. An off-diagonal entry is positive when the two centered features tend to have the same sign. Some libraries divide by n − 1 when estimating a population covariance. That changes the eigenvalues by a common factor and leaves the principal directions unchanged.
If C v = λv, then v is an eigenvector and λ is its eigenvalue. Along a unit direction v, the projected variance is vᵀCv. The first principal component is the unit direction that maximizes that quantity. For a symmetric covariance matrix, the maximizing direction is an eigenvector for the largest eigenvalue. To get the second component, maximize the same quantity over directions perpendicular to the first.
The sign of an eigenvector is arbitrary. Flipping the axis also flips all its coordinates, so reconstructing the points gives the same answer.
Turn the picture into a variance calculation
Write centered row i as xᵢ and choose a unit column vector v, meaning vᵀv = 1. Its projected coordinate is tᵢ = xᵢ · v. These coordinates have mean zero because the rows of X were centered. Their variance is the mean of their squares.
Var(t) = Σᵢ (xᵢ · v)² / n = vᵀ(XᵀX/n)v = vᵀCv.
The transpose symbol ᵀ turns a column into a row or vice versa. The unit-length condition keeps the comparison fair. Doubling v would otherwise quadruple the variance without changing the direction.
Why does the leading eigenvector win? Write v as a weighted sum of two perpendicular unit eigenvectors, v = a v₁ + b v₂, where a² + b² = 1. Then vᵀCv = λ₁a² + λ₂b². If λ₁ ≥ λ₂, this weighted average cannot exceed λ₁. Choosing v₁ achieves it. When the largest eigenvalues tie, more than one direction attains the same variance.
Work it out
Use the four points (3, 3), (−3, −3), (1, −1), and (−1, 1). Their mean is zero. Each feature has mean square (9 + 9 + 1 + 1)/4 = 5. The cross-product mean is (9 + 9 − 1 − 1)/4 = 4.
The covariance matrix has 5 on the diagonal and 4 off it. Multiplying it by (1, 1) gives 9(1, 1). Multiplying by (1, −1) gives 1(1, −1). The first direction retains 9/(9 + 1) = 90% of the variance. Projecting onto it collapses the two shorter points to the origin, so the discarded 10% still represents information.
The diagonal axes capture 90% and 10% of the empirical variance.
Run the Python lab
import numpy as np
points = np.array([[3., 3.], [-3., -3.], [1., -1.], [-1., 1.]])
X = points - points.mean(axis=0)
cov = X.T @ X / len(X)
values, axes = np.linalg.eigh(cov)
first = axes[:, -1]
scores = X @ first
reconstructed = np.outer(scores, first)
print("covariance:", cov.tolist())
print("variances, largest first:", np.round(values[::-1], 6).tolist())
print(f"variance retained: {values[-1] / values.sum():.0%}")
print(f"mean squared distance lost: {np.mean(np.sum((X - reconstructed)**2, axis=1)):.1f}")
np.testing.assert_allclose(values, [1, 9])
assert np.isclose(np.mean(scores**2), 9)
Expected output
covariance: [[5.0, 4.0], [4.0, 5.0]]
variances, largest first: [9.0, 1.0]
variance retained: 90%
mean squared distance lost: 1.0
Read the scores and reconstruct the points
np.linalg.eigh(cov) is for a real symmetric matrix. It returns eigenvalues in ascending order, so the final eigenvector column is the first principal direction. The code calls that column first. Then X @ first produces one score per row. Multiply each score by the same axis to reconstruct a two-feature approximation in centered coordinates. For data with nonzero feature means, add the means back to reconstruct in the original coordinates.
The lab reports a reconstruction loss of 1.0 as the mean of the squared distances per point. In this example that is exactly the variance discarded along the second direction. If you are evaluating PCA in a prediction pipeline, fit the means and directions on the training data and reuse them on held-out rows.
Try it yourself
- Add (10, −5) to every point and repeat PCA with centering. Do the principal directions move?
- Change the units of the first feature by multiplying it by 100. Why might the first axis change?
Check your work. Centering removes the common translation. Rescaling changes the covariance matrix. Use standardized features when equal relative variation is the comparison you intend.