Sub topic 5
Principal components: directions of maximum variance
This chapter assumes you know basic Python and NumPy, mean, variance and correlation, matrix multiplication, and the idea of a basis. It also assumes your data is a feature matrix with rows as samples and columns as features. You have already seen the covariance matrix and the eigenvectors of a symmetric matrix. Here they combine into the definition of a principal component.
The question PCA asks
Take a centered data matrix Xc with n samples and d features. Pick a unit vector w with d entries. Projecting every sample onto w gives one number per sample, Xc @ w. The variance of those numbers depends on which direction you picked.
PCA asks for the unit vector w that makes this variance as large as possible. That direction is the first principal component.
Why the covariance matrix appears
Let C be the covariance matrix of the centered data. The variance of the projection onto w is:
Var(Xc @ w) = w.T @ C @ wSo the task becomes: maximize w.T @ C @ w subject to w.T @ w = 1. The solution is an eigenvector of C. The variance along that direction equals its eigenvalue. The largest variance comes from the eigenvector with the largest eigenvalue.
The second component is the best direction that is also orthogonal to the first. Because C is symmetric, its eigenvectors are already orthogonal, so the third, fourth and later components follow by taking eigenvectors in order of decreasing eigenvalue.
A small worked example
The code below builds correlated 2D data and finds its components. It checks that the variance of the projection onto each component equals the matching eigenvalue.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(500, 2)) @ np.array([[2.0, 1.0],
[0.0, 0.5]])
Xc = X - X.mean(axis=0)
C = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(C)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
print("eigenvalues:", eigvals)
print("first component:", eigvecs[:, 0])
for k in range(2):
proj = Xc @ eigvecs[:, k]
print(k, proj.var(ddof=1), eigvals[k])
print("dot product:", eigvecs[:, 0] @ eigvecs[:, 1])The printed variances match the eigenvalues. The dot product is zero up to rounding, so the two components are orthogonal.
Properties to remember
- Components are unit vectors, so their length carries no information. Only their direction matters.
- Components are orthogonal to each other. They form a new basis for the feature space.
- The scores, which are the coordinates of each sample in the new basis, are uncorrelated. Their covariance matrix is diagonal, with the eigenvalues on the diagonal.
- The sum of all eigenvalues equals the total variance, which is the trace of
C. Rotating the axes redistributes variance but does not change the total.
Common errors
- Forgetting to center. If you skip centering, the first direction often points toward the data mean instead of along the main spread.
- Reading rows instead of columns.
np.linalg.eighreturns eigenvectors as columns. Useeigvecs[:, k], noteigvecs[k]. - Assuming sorted output.
eighreturns eigenvalues in ascending order. Sort them in descending order before taking the top components. - Trusting the sign. If
wis a component, so is-w. Different libraries or versions can return opposite signs, and both are correct.
Exercise
A centered dataset has a covariance matrix with eigenvalues 6, 3 and 1. What is the variance of the data projected onto the second principal component, what is the total variance, and what fraction of it does the first component carry?
Show answer
The variance along the second component equals its eigenvalue, 3. The total variance is the sum of the eigenvalues, 6 + 3 + 1 = 10. The first component carries 6 / 10 = 0.6, or 60% of the total variance.
Exercise
Your code computes eigvals, eigvecs = np.linalg.eigh(C) and uses eigvecs[:, 0] as the first principal component. Why is this wrong, and how do you fix it?
Show answer
eigh returns eigenvalues in ascending order, so column 0 belongs to the smallest eigenvalue. That is the direction of least variance. Fix it by sorting with order = np.argsort(eigvals)[::-1] and reordering both eigvals and eigvecs[:, order], or by taking the last column.