Application: Principal Component Analysis
Principal component analysis (PCA) finds the directions along which a cloud of data points varies the most. In linear algebra terms it is nothing more than the spectral decomposition of the covariance matrix, and it is one of the most used tools in data science.
The setup
Suppose we have data points in , stored as the rows of an matrix . PCA works in three steps:
The columns of are the principal components (directions) and is the variance of the data along . The scores are the coordinates of each point in the new orthonormal basis.
Why the eigenvectors?
The variance of the data projected onto a unit vector is
a quadratic form. Over all unit vectors, is largest at the top eigenvector of , where it equals (the Rayleigh quotient fact). Among directions orthogonal to the maximum is at , and so on. is symmetric and positive semidefinite, so the spectral theorem guarantees real, nonnegative eigenvalues and orthogonal components.
The explained variance ratio of component is . Since the trace is preserved, equals the total variance (the sum of the column variances).
By hand with NumPy
Made-up data: height and weight-like measurements that are strongly correlated, plus a third feature that is mostly noise.
import numpy as np
rng = np.random.default_rng(42)
n = 200
t = rng.normal(0, 1, n)
X = np.column_stack([170 + 8 * t + rng.normal(0, 2, n),
65 + 6 * t + rng.normal(0, 2, n),
rng.normal(0, 1, n)])
Xc = X - X.mean(axis=0)
C = Xc.T @ Xc / (n - 1)
lam, Q = np.linalg.eigh(C)
order = np.argsort(lam)[::-1] # eigh gives ascending order; PCA wants descending
lam, Q = lam[order], Q[:, order]
print("eigenvalues (variances):", np.round(lam, 3))
print("explained ratio:", np.round(lam / lam.sum(), 4))
print("total variance check:", round(float(lam.sum()), 3), "=", round(float(np.trace(C)), 3))
print("PC1 direction:", np.round(Q[:, 0], 4))
scores = Xc @ Q
print("score covariance is diagonal:", np.allclose(np.cov(scores.T), np.diag(lam)))eigenvalues (variances): [79.04 4.019 1.022]
explained ratio: [0.94 0.0478 0.0122]
total variance check: 84.082 = 84.082
PC1 direction: [-0.7991 -0.6012 0.0022]
score covariance is diagonal: True
The first component explains about 94% of the variance and points (up to sign) along : mostly "size", a mix of the first two features. The noise feature contributes almost nothing to it. In the new coordinates the features are uncorrelated: the covariance of the scores is diagonal.
The same thing with scikit-learn
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(42)
n = 200
t = rng.normal(0, 1, n)
X = np.column_stack([170 + 8 * t + rng.normal(0, 2, n),
65 + 6 * t + rng.normal(0, 2, n),
rng.normal(0, 1, n)])
pca = PCA(n_components=3).fit(X)
print("sklearn variances:", np.round(pca.explained_variance_, 3))
print("sklearn ratio :", np.round(pca.explained_variance_ratio_, 4))
Xc = X - X.mean(axis=0)
lam, Q = np.linalg.eigh(Xc.T @ Xc / (n - 1))
Q = Q[:, ::-1]
same = [bool(np.isclose(abs(float(pca.components_[i] @ Q[:, i])), 1.0)) for i in range(3)]
print("same directions up to sign:", same)
Z = pca.transform(X)[:, :2] # keep 2 of 3 dimensions
X_back = pca.inverse_transform(np.column_stack([Z, np.zeros(n)]))
print("mean squared reconstruction error:", round(float(np.mean((X - X_back) ** 2)), 4))sklearn variances: [79.04 4.019 1.022]
sklearn ratio : [0.94 0.0478 0.0122]
same directions up to sign: [True, True, True]
mean squared reconstruction error: 0.339
scikit-learn does not form the covariance matrix: it computes the SVD of the centred data, . Then , so the right singular vectors are the principal components and . The SVD route is more accurate because it avoids squaring the condition number, exactly as with least squares.
Dropping the last component loses only its variance: the mean squared error per entry is about , here .
Note: Eigenvectors are only defined up to sign, so two correct PCA implementations may report and . Compare directions with , never entry by entry.
Tip: Standardize features measured in different units (StandardScaler) before PCA. Otherwise the feature with the biggest numbers wins regardless of how informative it is: PCA on the covariance of unscaled data is not scale-invariant.
In software
- Dimensionality reduction. Compress hundreds of features to the few components that hold most of the variance before clustering or regression (PCA in ML).
- Visualization. Projecting high-dimensional data (or word embeddings) onto the top two components gives a quick 2D scatter plot.
- Faces and images. "Eigenfaces" are the principal components of a set of face images.
- Graphics and games. The principal axes of a point cloud give a tight oriented bounding box and the best-fit plane (the normal is the smallest-variance component).
- Finance. PCA of interest-rate curves finds the "level, slope, curvature" factors.
Exercises
Exercise 1: Two points
Data points and . What is the first principal component and its variance?
Answer
with variance 4 (sample covariance, ); the second variance is 0.
Solution
The mean is ; centred points are . . Its eigenvalues are 4 (on ) and 0 (on ).
Exercise 2: Explained variance
A covariance matrix has eigenvalues 6, 3, 1. How many components keep at least 85% of the variance?
Answer
Two (90%).
Solution
Total 10. One component keeps 60%, two keep .
Exercise 3: Uncorrelated already
Data with covariance matrix . What are the principal components?
Answer
The coordinate axes: with variance 5, then with variance 2.
Solution
A diagonal matrix's eigenvectors are the standard basis vectors and its eigenvalues are its diagonal entries; sort them in descending order.
Exercise 4: PCA from scratch (code)
For the points , , , , compute the covariance matrix and principal components.
Answer
; (variance ), (variance ).
Solution
The mean is 0. ; divide by .
import numpy as np
X = np.array([[2, 0], [0, 1], [-2, 0], [0, -1]], dtype=float)
C = np.cov(X.T)
lam, Q = np.linalg.eigh(C)
print(np.round(C, 4).tolist(), np.round(lam[::-1], 4), np.abs(Q[:, ::-1]).tolist())[[2.6667, 0.0], [0.0, 0.6667]] [2.6667 0.6667] [[1.0, 0.0], [0.0, 1.0]]
Test yourself
The first principal component is…
- the column of with the largest mean
- the eigenvector of the covariance matrix with the largest eigenvalue
- the eigenvector with the smallest eigenvalue
- the first row of
Why might your PCA give where scikit-learn gives ?
- One of them has a bug
- Eigenvectors are only determined up to sign
- scikit-learn does not centre the data
- Because the data was not standardized
If the eigenvalues of the covariance are 9, 0.9 and 0.1, the first component explains…
- 9%
- 50%
- 90%
- 99%