Sub topic 11
PCA Through the Singular Value Decomposition
This chapter assumes you can compute a covariance matrix and its eigenvectors, as in the earlier chapters on PCA from scratch. You should also be comfortable with matrix transposes and the idea of an orthonormal basis. Here you will see that PCA can be computed from the centered data matrix directly, without ever forming the covariance matrix.
The singular value decomposition in one paragraph
Any real matrix Xc with n rows and d columns can be factored as
Xc = U S Vt
Uhas orthonormal columns and shapen × r. Its columns are the left singular vectors, one entry per sample.Sis a diagonal matrix of singular valuess1 ≥ s2 ≥ ... ≥ 0. NumPy returns it as a 1-D array.Vthas orthonormal rows and shaper × d. Its rows are the right singular vectors, one entry per feature.r = min(n, d)for the "economy" form, which you get withfull_matrices=False.
For PCA, Xc is the data matrix after subtracting each column's mean. The SVD of an uncentered matrix does not give principal components.
Why the SVD gives the same answer as the covariance matrix
Start from the sample covariance matrix of centered data:
C = Xc^T Xc / (n - 1)
Substitute the SVD. Because U^T U = I, the U factors cancel:
Xc^T Xc = V S U^T U S V^T = V S² V^T
So C = V (S² / (n - 1)) V^T. This is an eigendecomposition of C, which gives three facts:
- The columns of
V(the rows ofVt) are the eigenvectors ofC. They are the principal axes. - The eigenvalues of
C, the variances along those axes, ares_i² / (n - 1). - The scores
Xc VequalU S, becauseXc V = U S V^T V = U S.
The third fact means the scores come straight out of the decomposition. Each column of U is a unit-length score vector, and multiplying by s_i restores its scale.
Checking the equivalence numerically
This script uses the same synthetic data as the earlier chapters. It computes PCA both ways and compares the results.
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
n = X.shape[0]
Xc = X - X.mean(axis=0)
# Route 1: covariance matrix and eigh
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
# Route 2: SVD of the centered data
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
svd_vals = S**2 / (n - 1)
print(np.allclose(svd_vals, eigvals))
print(np.allclose(np.abs(Vt), np.abs(eigvecs.T)))
print(np.allclose(U * S, Xc @ Vt.T))All three lines print True. The comparison of axes uses np.abs because of the sign ambiguity described below.
Sign ambiguity
If v is a valid principal axis, so is -v. Flipping the sign of a column of V and the matching column of U leaves U S Vt unchanged. Different LAPACK builds, library versions or solvers can therefore return axes with opposite signs.
Treat signs as arbitrary. Do not compare components between runs or libraries without aligning signs first. Do not tell a story such as "positive means more of feature 3" without looking at the loadings in the same run. If you need stable signs, apply a fixed rule, such as making the largest-magnitude entry of each axis positive. scikit-learn applies a deterministic rule of this kind (svd_flip), but it is a convention, not a property of the data.
A related edge case is repeated singular values. When two singular values are equal, any rotation within their shared plane is also valid, so the individual axes are not unique. Only the subspace they span is meaningful.
Truncation and the best low-rank approximation
Keeping the first k components means keeping the first k singular triplets:
Xk = U[:, :k] S[:k] Vt[:k]
The Eckart–Young theorem says Xk is the closest rank-k matrix to Xc in squared (Frobenius) error. The error has a closed form. It is the sum of the squared singular values you dropped:
||Xc - Xk||² = s_{k+1}² + ... + s_r²
Dividing by the number of entries, n * d, gives the mean squared reconstruction error you measured in the earlier chapter.
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]])
mean = X.mean(axis=0)
Xc = X - mean
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
k = 2
Xk = (U[:, :k] * S[:k]) @ Vt[:k] + mean
mse = np.mean((X - Xk) ** 2)
predicted = np.sum(S[k:] ** 2) / X.size
print(mse, predicted)
print(np.isclose(mse, predicted))You can therefore read the reconstruction error for every possible k directly off the singular values, without reconstructing anything. The explained variance ratio follows the same pattern: s_i² / sum(s²).
When there are more features than samples
Suppose you have n = 20 samples and d = 500 features, as with gene expression or image pixels. The covariance matrix is 500 × 500. It costs a lot of memory and its eigendecomposition is slow, yet it carries at most 19 dimensions of information. The SVD of the 20 × 500 data matrix avoids this cost.
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(20, 500))
Xc = X - X.mean(axis=0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
print(U.shape, S.shape, Vt.shape)
print(np.sum(S > 1e-10))The shapes are (20, 20), (20,) and (20, 500). Only 19 singular values are nonzero. Centering removes one degree of freedom, so the rank of Xc is at most n - 1. The 20th singular value is numerically zero, and asking for more than min(n, d) - 1 meaningful components makes no sense.
Numerical stability
Forming Xc^T Xc squares the condition number. A singular value of 1e-8 relative to the largest becomes an eigenvalue of 1e-16, which is at the limit of double-precision floating point. Small variances then come out noisy or slightly negative, and the matching axes are inaccurate. Running the SVD on Xc avoids the squaring and resolves small directions much better.
This matters most when features differ in scale, when data is nearly collinear, or when you plan to keep or invert small components, as in whitening. For the leading components of a well-scaled dataset, both routes agree to many digits.
What scikit-learn does
sklearn.decomposition.PCA centers the data, then computes an SVD or an equivalent decomposition. It does not scale features. The fitted attributes map directly onto the SVD:
| Attribute | SVD quantity |
|---|---|
| `components_` | first `k` rows of `Vt` |
| `singular_values_` | first `k` entries of `S` |
| `explained_variance_` | `S**2 / (n - 1)` |
| `mean_` | column means used for centering |
import numpy as np
from sklearn.decomposition import PCA
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]])
n = X.shape[0]
Xc = X - X.mean(axis=0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
pca = PCA(n_components=3).fit(X)
print(np.allclose(pca.singular_values_, S))
print(np.allclose(np.abs(pca.components_), np.abs(Vt)))
print(np.allclose(pca.explained_variance_, S**2 / (n - 1)))Choosing a solver
The svd_solver parameter selects the algorithm.
| Solver | Use it when |
|---|---|
| `"full"` | The data is small or medium and you want an exact answer. It runs a complete LAPACK SVD. |
| `"arpack"` | You want a few exact leading components from a large matrix. It is an iterative truncated SVD. |
| `"randomized"` | The matrix is large and `k` is much smaller than `min(n, d)`. It is fast and approximate. |
| `"covariance_eigh"` | `n` is much larger than `d`. It eigendecomposes the small `d × d` covariance matrix. It is only available in recent scikit-learn versions. |
| `"auto"` | You want the library to pick one by data shape and `k`. |
The default "auto" is a sensible starting point. With "randomized", components beyond the first few can be slightly off, and results depend on random_state.
Common mistakes
- Skipping centering. SVD on raw data finds directions of maximum second moment around the origin. The first component then mostly points toward the data mean. Center the data first, or use
PCA, which does it for you. - Confusing
VtwithV. NumPy returnsVt. Components are its rows, so project withXc @ Vt[:k].T, notXc @ Vt[:k]. - Using
Sas variances.Sholds standard-deviation-like quantities scaled bysqrt(n - 1). Square it and divide byn - 1to get variances. - Calling the full SVD on huge data.
full_matrices=Truebuilds ann × nmatrixU. Forn = 100000that is tens of gigabytes. Always passfull_matrices=False. - Reading meaning into signs. See the sign ambiguity section.
Exercise
You have a centered matrix Xc with n = 500 samples and d = 10 features, and its SVD gives singular values S. (a) What is the variance explained by the second component? (b) After keeping k = 3 components, what is the mean squared reconstruction error per entry? (c) Which matrix times which gives the 3-column score matrix?
Show answer
(a) S[1]2 / (n - 1) = S[1]2 / 499, using the zero-based index for the second singular value. As a fraction of the total, it is S[1]2 / np.sum(S2). (b) np.sum(S[3:]*2) / (n d), which is the sum of the dropped squared singular values divided by 500 10 = 5000. (c) Scores = Xc @ Vt[:3].T, which equals U[:, :3] S[:3]. Both forms give the same numbers.