PCA: Maximum Variance
High-dimensional data usually varies along far fewer directions than it has coordinates. Principal component analysis (PCA) finds those directions. This lesson derives PCA as "find the direction along which the projected data varies the most", which turns into an eigenvalue problem for the covariance matrix.
Setup
Data , centred so that the mean is , with covariance
Project each point onto a unit vector : . The variance of the projections is
The first principal component
Maximize subject to (otherwise we could inflate the variance by scaling). With a Lagrange multiplier:
So is an eigenvector of , and the variance along it is . To maximize, take the eigenvector with the largest eigenvalue.
All the components
The -th component maximizes the remaining variance while being orthogonal to the previous ones. By induction it is the eigenvector of the -th largest eigenvalue. Since is symmetric, these eigenvectors are orthonormal (Eigendecomposition), and the variance captured by the first components is out of the total .
import numpy as np
rng = np.random.default_rng(0)
# 3-D data that really lives near a tilted plane
Z = rng.normal(size=(500, 2)) * [3.0, 1.0]
B = np.array([[0.6, 0.0], [0.0, 1.0], [0.8, 0.0]]) # orthonormal columns
X = Z @ B.T + 0.1 * rng.normal(size=(500, 3))
Xc = X - X.mean(axis=0)
S = Xc.T @ Xc / len(Xc)
lam, Q = np.linalg.eigh(S)
lam, Q = lam[::-1], Q[:, ::-1] # sort descending
print("eigenvalues (variances along PCs):", np.round(lam, 4))
print("explained variance ratio:", np.round(lam / lam.sum(), 4))
print("first PC:", np.round(Q[:, 0] * np.sign(Q[0, 0]), 3))
z1 = Xc @ Q[:, 0]
print("variance of projections onto PC1:", round(z1.var(), 4), "= lambda_1")eigenvalues (variances along PCs): [8.7142 0.9351 0.0089]
explained variance ratio: [9.023e-01 9.680e-02 9.000e-04]
first PC: [0.6 0.003 0.8 ]
variance of projections onto PC1: 8.7142 = lambda_1
The first direction recovers (up to sign), the axis with standard deviation 3; the third eigenvalue is just the small noise.
Brute force agrees
For 2-D data we can try every direction and see that the variance curve peaks at the top eigenvector:
import numpy as np
rng = np.random.default_rng(1)
X = rng.multivariate_normal([0, 0], [[3.0, 1.2], [1.2, 1.0]], size=2000)
Xc = X - X.mean(axis=0); S = Xc.T @ Xc / len(Xc)
angles = np.linspace(0, np.pi, 1801)
var = [np.array([np.cos(a), np.sin(a)]) @ S @ np.array([np.cos(a), np.sin(a)]) for a in angles]
a_best = angles[int(np.argmax(var))]
lam, Q = np.linalg.eigh(S)
print("best angle by search:", round(np.degrees(a_best), 2), "degrees, variance", round(max(var), 4))
print("top eigenvector angle:", round(np.degrees(np.arctan2(Q[1, -1], Q[0, -1])) % 180, 2), "degrees, eigenvalue", round(lam[-1], 4))best angle by search: 25.8 degrees, variance 3.5658
top eigenvector angle: 25.81 degrees, eigenvalue 3.5658
In software
sklearn.decomposition.PCAexposescomponents_(the ),explained_variance_(the , with an divisor) andexplained_variance_ratio_(PCA in scikit-learn).- PCA is used to visualize embeddings in 2-D, to compress features before a classifier and to decorrelate data (whitening).
- The same computation is usually done with the SVD of the centred data (PCA in Practice).
Exercises
Exercise 1: Variance explained
A covariance matrix has eigenvalues . What fraction of variance do the first two components explain?
Answer
.
Solution
.
Exercise 2: Diagonal covariance
What are the principal components of data with covariance ?
Answer
, , , in that order.
Solution
A diagonal matrix has the coordinate axes as eigenvectors; sorting the eigenvalues gives the order. The features are already uncorrelated, and PCA just ranks them by variance.
Exercise 3: Why centre? (code)
Compute the top eigenvector of for uncentred data with mean and covariance . What does it point to?
Answer
Roughly , towards the mean, not the high-variance direction .
Solution
Without centring, , and the large mean dominates.
import numpy as np
rng = np.random.default_rng(2)
X = rng.normal(size=(5000, 2)) * [1.0, 2.0] + [10.0, 0.0]
for name, M in (("uncentred", X), ("centred", X - X.mean(axis=0))):
lam, Q = np.linalg.eigh(M.T @ M / len(M))
print(name, np.round(np.abs(Q[:, -1]), 3))uncentred [1. 0.004]
centred [0.002 1. ]
Test yourself
The first principal component is…
- the eigenvector of the covariance matrix with the largest eigenvalue
- the mean of the data
- the feature with the largest values
- the smallest eigenvector
The variance of the data projected onto principal component equals…
- 1
Why is the constraint needed?
- To make the problem convex
- Otherwise the variance could be made arbitrarily large by scaling
- Because eigenvectors must be integers
- It is not needed