Sub topic 11
PCA through the singular value decomposition
This chapter assumes you know how to compute a covariance matrix, that you can read the eigenvector version of PCA, and that you are comfortable with NumPy matrix products. You have already seen PCA built from np.cov and eigh. Here you will get the same result from the singular value decomposition (SVD), which is the method most libraries use.
Why use the SVD
The covariance route has a cost. Forming X.T @ X squares the condition number of the data, so small singular values lose precision. The SVD works on the centered data matrix directly and avoids that step.
The SVD factors any matrix into three pieces. For a centered matrix Xc with n rows and p columns:
Xc = U S Vt
Uholds the left singular vectors, one column per sample direction.Sis a vector of singular values, sorted from largest to smallest.Vtholds the right singular vectors as rows.
The rows of Vt are the principal axes. They are the same directions you got from the covariance eigenvectors, up to a sign flip.
The link to the covariance matrix
Substitute the factorization into the covariance matrix:
Xc.T @ Xc / (n - 1) = V S² Vt / (n - 1)
This is an eigendecomposition of the covariance matrix. The eigenvectors are the columns of V, and the eigenvalues are S**2 / (n - 1). So the two methods agree.
Computing PCA with the SVD
This code uses the same data as the from-scratch chapter and builds everything from the SVD.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3)) @ np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
Xc = X - X.mean(axis=0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
eigvals = S**2 / (Xc.shape[0] - 1)
components = Vt[:2]
scores = Xc @ components.T
reconstructed = scores @ components + X.mean(axis=0)
error = np.mean((X - reconstructed) ** 2)
print(eigvals)
print(error)Walk through the steps:
full_matrices=Falsereturns the economy-size SVD.Uhas shape(200, 3)instead of(200, 200), which saves memory.S**2 / (n - 1)converts singular values to variances. They match the eigenvalues fromeigh.Vt[:2]selects the top two principal axes. Each row is one axis.Xc @ components.Tprojects the data onto those axes to give the scores.scores @ componentsmaps the scores back to the original space. Adding the mean undoes the centering.
The scores also equal U[:, :2] * S[:2], so you can get them without a second matrix product.
Gotchas
- Sign ambiguity. An axis and its negative are equally valid. Two libraries can return components with opposite signs, so compare results up to sign.
- Row versus column. NumPy returns
Vt, notV. Principal axes are the rows ofVt. - Centering is required. An SVD of uncentered data gives directions that include the mean offset, and the first component mostly points at the data's center.
- Variance scaling. Divide by
n - 1, notn, if you want to matchnp.covand scikit-learn.
When the SVD route is better
| Situation | Better choice |
|---|---|
| Few features, many samples | Either works. Covariance is small and fast. |
| Many features, few samples | SVD. A `p × p` covariance matrix is large and wasteful. |
| Ill-conditioned data | SVD, for numerical accuracy. |
| Only the top few components | Truncated or randomized SVD. |
Exercise
You compute U, S, Vt = np.linalg.svd(Xc, full_matrices=False) for a centered matrix with 500 samples. How do you get the variance explained by each component, and where are the principal axes?
Show answer
The variance of each component is S**2 / (500 - 1). The principal axes are the rows of Vt.
Exercise
Why can two correct PCA implementations return components with opposite signs?
Show answer
A principal axis is defined only as a line. Both a vector and its negative point along that line and give the same variance, so the sign depends on the algorithm's internal choices.