Sub topic 9
Implementing PCA from scratch with NumPy
This chapter assumes you know basic NumPy, the covariance matrix, and the idea of eigenvectors. You should also be comfortable with a feature matrix where rows are samples and columns are features. Here you put those pieces together into a working PCA.
The recipe
PCA from scratch is five steps. Each step maps to one line or two of NumPy.
- Subtract the column means so every feature has mean zero.
- Build the covariance matrix of the centered data.
- Compute its eigenvalues and eigenvectors.
- Sort them from largest eigenvalue to smallest.
- Multiply the centered data by the first k eigenvectors.
The code
The data below has three features. The first two are correlated and have large variance. The third is small noise, so two components should capture almost everything.
import numpy as np
rng = np.random.default_rng(0)
mixing = np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
X = rng.normal(size=(200, 3)) @ mixing
Xc = X - X.mean(axis=0)
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
scores = Xc @ eigvecs[:, :2]
ratio = eigvals / eigvals.sum()
print(scores.shape)
print(ratio)The output shape is (200, 2): 200 samples, each described by two scores. The ratio array sums to 1. Its first two entries should add up to nearly 1, because the third direction carries little variance.
What each line does
np.cov(Xc, rowvar=False) treats columns as features. Without rowvar=False, NumPy treats rows as variables and returns a 200 by 200 matrix, which is a common mistake. The result here is a 3 by 3 matrix.
np.linalg.eigh is the right solver because a covariance matrix is symmetric. It is faster and more stable than np.linalg.eig. It also guarantees real eigenvalues and orthonormal eigenvectors. The eigenvectors are the columns of eigvecs, not the rows.
eigh returns eigenvalues in ascending order, so the argsort(...)[::-1] step reverses them. Apply the same order to both the eigenvalues and the eigenvector columns. If you sort only one of them, the pairs no longer match.
Each eigenvalue is the variance of the data along its eigenvector. That is why eigvals / eigvals.sum() gives the fraction of total variance each component explains.
Reconstruction
Scores can be mapped back to the original space. Multiply by the transposed eigenvectors and add the mean back:
components = eigvecs[:, :2].T
reconstructed = scores @ components + X.mean(axis=0)
error = np.mean((X - reconstructed) ** 2)
print(error)The error is small but not zero, because the discarded third direction is lost. With all three components the error would be zero, apart from rounding.
Common errors
- Forgetting to center. If you skip the subtraction, the first component partly points at the mean instead of the direction of greatest spread.
- Wrong axis in
np.cov. Check thatcov.shapeequals the number of features in both dimensions. - Using rows of
eigvecs. The components are columns. Useeigvecs[:, :k]or its transpose consistently. - Comparing signs. An eigenvector and its negative are equally valid. Your scores may be flipped relative to scikit-learn's, and that is not a bug.
Exercise
You call np.cov(Xc) on a 200 by 3 matrix without rowvar=False. What shape does the result have, and why is it wrong for PCA?
Show answer
The result is 200 by 200. By default NumPy treats each row as a variable, so it computes covariance between samples instead of between features. PCA needs the 3 by 3 feature covariance matrix, so pass rowvar=False.