TExcelTAD
Home › Math for Machine Learning › PCA: Maximum Variance

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 x1,…,xN∈RD\mathbf{x}_1, \ldots, \mathbf{x}_N \in \mathbb{R}^D, centred so that the mean is 0\mathbf{0}, with covariance

S=1N∑n=1NxnxnT=1NXTXS = \frac{1}{N}\sum_{n=1}^{N}\mathbf{x}_n\mathbf{x}_n^T = \frac{1}{N}X^TX

Project each point onto a unit vector b1\mathbf{b}_1: z1n=b1Txnz_{1n} = \mathbf{b}_1^T\mathbf{x}_n. The variance of the projections is

V1=1N∑n(b1Txn)2=b1TS b1V_1 = \frac{1}{N}\sum_{n}(\mathbf{b}_1^T\mathbf{x}_n)^2 = \mathbf{b}_1^TS\,\mathbf{b}_1

The first principal component

Maximize b1TSb1\mathbf{b}_1^TS\mathbf{b}_1 subject to ∥b1∥2=1\lVert \mathbf{b}_1 \rVert^2 = 1 (otherwise we could inflate the variance by scaling). With a Lagrange multiplier:

L=b1TSb1+λ1(1−b1Tb1),∂L∂b1=2b1TS−2λ1b1T=0  ⟹  Sb1=λ1b1\mathfrak{L} = \mathbf{b}_1^TS\mathbf{b}_1 + \lambda_1(1 - \mathbf{b}_1^T\mathbf{b}_1), \qquad \frac{\partial\mathfrak{L}}{\partial \mathbf{b}_1} = 2\mathbf{b}_1^TS - 2\lambda_1\mathbf{b}_1^T = \mathbf{0} \implies S\mathbf{b}_1 = \lambda_1\mathbf{b}_1

So b1\mathbf{b}_1 is an eigenvector of SS, and the variance along it is V1=b1TSb1=λ1V_1 = \mathbf{b}_1^TS\mathbf{b}_1 = \lambda_1. To maximize, take the eigenvector with the largest eigenvalue.

All the components

The mm-th component maximizes the remaining variance while being orthogonal to the previous ones. By induction it is the eigenvector of the mm-th largest eigenvalue. Since SS is symmetric, these eigenvectors are orthonormal (Eigendecomposition), and the variance captured by the first MM components is ∑m=1Mλm\sum_{m=1}^{M}\lambda_m out of the total tr⁡(S)=∑dλd\operatorname{tr}(S) = \sum_d\lambda_d.

python · try it yourself
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 (0.6,0,0.8)(0.6, 0, 0.8) (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:

python · try it yourself
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.PCA exposes components_ (the bm\mathbf{b}_m), explained_variance_ (the λm\lambda_m, with an N−1N - 1 divisor) and explained_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 6,3,0.8,0.26, 3, 0.8, 0.2. What fraction of variance do the first two components explain?

Answer

90%90\%.

Solution

(6+3)/(6+3+0.8+0.2)=9/10(6 + 3)/(6 + 3 + 0.8 + 0.2) = 9/10.

Exercise 2: Diagonal covariance

What are the principal components of data with covariance diag⁡(1,5,2)\operatorname{diag}(1, 5, 2)?

Answer

e2\mathbf{e}_2, e3\mathbf{e}_3, e1\mathbf{e}_1, in that order.

Solution

A diagonal matrix has the coordinate axes as eigenvectors; sorting the eigenvalues 5>2>15 > 2 > 1 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 1NXTX\frac{1}{N}X^TX for uncentred data with mean (10,0)(10, 0) and covariance diag⁡(1,4)\operatorname{diag}(1, 4). What does it point to?

Answer

Roughly (1,0)(1, 0), towards the mean, not the high-variance direction (0,1)(0, 1).

Solution

Without centring, 1NXTX=S+μμT\frac{1}{N}X^TX = S + \boldsymbol{\mu}\boldsymbol{\mu}^T, and the large mean dominates.

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

  1. the eigenvector of the covariance matrix with the largest eigenvalue
  2. the mean of the data
  3. the feature with the largest values
  4. the smallest eigenvector

The variance of the data projected onto principal component mm equals…

  1. 1
  2. λm\lambda_m
  3. λm\sqrt{\lambda_m}
  4. tr⁡(S)\operatorname{tr}(S)

Why is the constraint ∥b∥=1\lVert \mathbf{b} \rVert = 1 needed?

  1. To make the problem convex
  2. Otherwise the variance could be made arbitrarily large by scaling b\mathbf{b}
  3. Because eigenvectors must be integers
  4. It is not needed