Deriving PCA (ML #12)
You have 200 features, 60 observations, and a model that would not converge. Reducing dimensions is the obvious move, and PCA is the default — but the default is usually wrong for your problem, because PCA optimizes something unrelated to what you want.
It maximizes variance preserved. Not predictive power. Not class separation. Not sparsity. Variance. Those coincide often enough to make it useful and diverge often enough to make it dangerous, and you cannot tell which case you are in unless you know what the derivation actually claims.
This chapter derives PCA from reconstruction error — not from “variance is good” — and in the process shows the objective is a quadratic form whose stationary points are eigenvectors, and that the eigen-solution is provably the best possible rank-\(k\) approximation.
Start from reconstruction error
Center the data: \(\tilde{x}_i = x_i - \bar{x}\), so \(\sum_i \tilde{x}_i = 0\) and every subsequent result holds relative to the mean. Project onto a single unit direction \(u\) with \(\|u\| = 1\):
\[ \text{projection} = (\tilde{x}_i^\top u)\,u \]
The information kept is \((\tilde{x}_i^\top u)^2\), so the error for point \(i\) is
\[ \lVert \tilde{x}_i \rVert^2 - (\tilde{x}_i^\top u)^2 \]
Sum over all points and define the covariance matrix \(\Sigma = \frac1n\sum_i \tilde{x}_i\tilde{x}_i^\top\). Note \(\sum_i (\tilde{x}_i^\top u)^2 = u^\top\left(\sum_i \tilde{x}_i\tilde{x}_i^\top\right)u = n\,u^\top\Sigma u\). So total reconstruction error after projecting onto \(u\) is
\[ \text{SSE}(u) = \sum_i \lVert\tilde{x}_i\rVert^2 - n\,u^\top\Sigma u \]
The first term does not depend on \(u\). Minimizing error is therefore identical to maximizing \(u^\top\Sigma u\). This is the derivation in full: PCA is not “keep the most variance”, it is “minimize reconstruction error”, and variance preservation is what that reduces to. Anyone who tells you PCA maximizes variance without mentioning the error objective has skipped the interesting half.
Solving it: a Lagrange multiplier
Now maximize \(u^\top\Sigma u\) subject to \(\|u\| = 1\). The constraint must be enforced explicitly, since without it the optimum is unbounded — scale \(u\) up and the objective grows without limit. Form the Lagrangian
\[ \mathcal{L}(u, \lambda) = u^\top\Sigma u - \lambda\left(u^\top u - 1\right) \]
Differentiate with respect to \(u\) and set to zero. Since \(\Sigma\) is symmetric, \(\frac{\partial}{\partial u}u^\top\Sigma u = 2\Sigma u\):
\[ 2\Sigma u - 2\lambda u = 0 \;\Longrightarrow\; \Sigma u = \lambda u \]
That is the eigenvector equation. The stationary points of the reconstruction objective are exactly the eigenvectors of the covariance matrix, and the multiplier \(\lambda\) is the eigenvalue — which is precisely the variance along that direction, since \(u^\top\Sigma u = \lambda u^\top u = \lambda\).
So: eigendecompose \(\Sigma = U\Lambda U^\top\) with eigenvalues \(\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d \ge 0\). Sort descending. The first principal component is \(u_1\), and by construction it minimizes reconstruction error more than any other unit direction. Recurse for \(k\) components.
Why the largest eigenvalue wins. At a stationary point, the objective value equals \(\lambda\), so maximizing the objective means maximizing the eigenvalue. The eigendecomposition orders them. That’s the entire selection rule — no additional argument needed.
import numpy as np
def pca_via_eigendecomposition(X, k):
n, d = X.shape
Xc = X - X.mean(0) # centering is mandatory
Sigma = Xc.T @ Xc / n # sample covariance
vals, vecs = np.linalg.eigh(Sigma) # ascending
order = np.argsort(vals)[::-1][:k] # descending, top k
U = vecs[:, order] # principal directions
return U, vals[order], Xc @ U # scores/projections
Note np.linalg.eigh — covariance matrices are symmetric, so the specialized symmetric eigensolver is both faster and more accurate than a general one.
The optimality guarantee
A natural worry: PCA is greedy, taking the best 1-D direction then the best 2-D subspace containing it. Is the greedy choice actually optimal for rank \(k\)? Yes, and there is a theorem for it.
The Eckart–Young–Mirsky theorem states that the minimum achievable error for any rank-\(k\) linear approximation of a matrix \(A\) equals the sum of the squares of its \(k\) largest singular values, achieved by the leading singular/principal directions. For centered data this means:
\[ \min_{U:\,\text{rank}(U)=k} \sum_i \lVert \tilde{x}_i - UU^\top \tilde{x}_i \rVert^2 = \sum_{j > k} \lambda_j \]
Two things fall out. First, PCA is globally optimal among all rank-\(k\) linear projections — the greedy construction is not a heuristic, it attains the bound. Second, the optimal error is simply the sum of the discarded eigenvalues, which gives you a diagnostic without doing any work: if you keep components covering 95% of variance, the residual reconstruction error is exactly the remaining 5%.
This is the formal version of the intuition that variance and error are two views of one quantity, and it is why “95% of variance” is a meaningful and checkable criterion.
def pca_via_svd(X, k):
n, d = X.shape
Xc = X - X.mean(0)
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
# singular values s_j relate to eigenvalues by lambda_j = s_j^2 / n
scores = U[:, :k] * s[:k]
return Vt[:k].T, s[:k] ** 2 / n, scores
# both routes agree on the subspace and the eigenvalues
X = np.random.default_rng(0).normal(size=(200, 5))
X[:, 1] += 0.9 * X[:, 0] # inject structure
U1, l1, z1 = pca_via_eigendecomposition(X, 3)
U2, l2, z2 = pca_via_svd(X, 3)
print(np.round(l1, 6))
print(np.round(l2, 6)) # identical eigenvalues
print(np.abs(np.abs(np.diag(U1.T @ U2)) - 1).max() < 1e-8) # same subspace
Both decompositions return the same eigenvalues and the same subspace — the sign of an eigenvector is arbitrary, hence the abs in the alignment check.
Why SVD is the numerically right choice
The two routes agree mathematically. Numerically they do not, and the reason is conditioning. Forming \(\Sigma = X^\top X/n\) squares the condition number:
\[ \text{cond}(X^\top X) = \text{cond}(X)^2 \]
Squared is not a mild degradation. If \(X\) has condition number \(10^6\), then \(\Sigma\) has \(10^{12}\) — beyond double precision’s ~\(10^{16}\) limit in combination with any small true eigenvalue, the small ones are destroyed by rounding error. PCA’s whole job is to find the smallest directions accurately, so destroying them is a targeted failure.
The SVD route never forms \(X^\top X\). It factorizes \(X\) directly, so it is stable for ill-conditioned data. Standard practice in libraries for that reason, and it costs nothing to use.
Reconstruction
With \(U_k\) holding the top-\(k\) directions, scores and reconstruction are two projections:
\[ \text{scores: } z_i = U_k^\top \tilde{x}_i \qquad \text{reconstruction: } \hat{x}_i = U_k U_k^\top \tilde{x}_i \]
Worth noting the geometry: reconstruction is the orthogonal projection onto a subspace, so \(\lVert \tilde{x}_i - \hat{x}_i \rVert\) is exactly the component orthogonal to the retained directions. PCA keeps the directions that are not orthogonal to each other — they are eigenvectors of a symmetric matrix and so must be mutually orthogonal — and discards everything else.
How many components? The cumulative explained-variance ratio is the standard tool:
U, vals, scores = pca_via_svd(X, X.shape[1])
cumulative = np.cumsum(vals) / vals.sum()
k95 = int(np.searchsorted(cumulative, 0.95) + 1)
print(k95, "components for 95% of variance")
The geometry of a projection
Everything above says “minimize error, maximize variance”. Here is what one projection actually does to a point:
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\draw[->, thick] (-1.2,0) -- (5.6,0) node[right, font=\rmfamily\scriptsize] {$x_1$};
\draw[->, thick] (0,-1.4) -- (0,3.6) node[above, font=\rmfamily\scriptsize] {$x_2$};
\draw[->, thick, orange!85!black] (0,0) -- (4.6,3.0) node[above right, font=\rmfamily\scriptsize, text=orange!70!black] {$u_1$};
\coordinate (P) at (3.4,2.1);
\fill[orange!85!black] (P) circle (2.6pt) node[above right, font=\rmfamily\scriptsize, text=orange!70!black] {$x$};
\draw[dashed, gray] (P) -- (1.78,0);
\fill[orange!85!black] (1.78,0) circle (2pt) node[below, font=\rmfamily\scriptsize, text=orange!70!black] {$(\tilde{x}^\top u)u$};
\draw[->, thick, blue!70!black] (P) to[bend left=25] node[above, font=\rmfamily\scriptsize, text=blue!60!black] {$\lVert\tilde{x}\rVert$};
\draw[->, thick, red!70!black] (P) to[bend right=25] node[below, font=\rmfamily\scriptsize, text=red!60!black] {$\lVert\tilde{x} - z u\rVert$};
\fill[gray, opacity=.35] (0,0) -- (4.6,3.0) -- (4.6,0) -- cycle;
\node[font=\rmfamily\scriptsize, align=center, text=black!65] at (2.4,-1.0) {kept: along $u_1$\quad discarded: orthogonal to $u_1$};
\end{tikzpicture}
The retained component is the projection \((\tilde{x}^\top u)u\) along \(u_1\); the discarded component is the segment orthogonal to it. The projection preserves distances along \(u_1\) exactly and collapses everything perpendicular to zero. So the objective \(\max u^\top\Sigma u\) is asking: in which direction is the data most spread out? And the eigenvalue is the answer, measured in squared units of that direction.
Which PCA to use, and against what
The three settings worth knowing, since “run PCA” is ambiguous:
| method | optimizes | supervised? | use when |
|---|---|---|---|
| PCA / SVD of \(\tilde{X}\) | total variance | no | compression, decorrelation, denoising, preprocessing for distance-based models |
| Kernel PCA | variance after an implicit non-linear map | no | structure that PCA’s hyperplanes cannot capture (rings, spirals) |
| LDA | between-class scatter \(\sum_c n_c\lVert\mu_c - \mu\rVert^2\) | yes | at most \(K-1\) components, and you have labels — the right choice for classification |
LDA is worth noticing here because it is structurally the same computation as PCA with a different scatter matrix: PCA maximizes within-total scatter along \(u\), LDA maximizes between-class scatter, and both reduce to solving an eigenvector problem. Swapping \(\Sigma\) for \(S_B\) (the between-class scatter, which Chapter 10’s shared-covariance Gaussian NB already contains in its log-posterior) turns PCA into a supervised projection. If your goal is classification rather than compression, LDA is usually the better tool — and unlike PCA it can never produce more than \(K-1\) components for \(K\) classes, which keeps the projection small.
Whitening
ZCA/normalization rescales each component to unit variance, which decorrelates and isotropizes:
\[ z^{\text{white}}_i = \Lambda^{-1/2}U^\top \tilde{x}_i, \qquad \text{where } \Lambda^{-1/2} = \text{diag}\!\left(\lambda_1^{-1/2}, \dots, \lambda_d^{-1/2}\right) \]
The covariance of the whitened scores is then \(\Lambda^{-1/2}U^\top\Sigma U\Lambda^{-1/2} = \Lambda^{-1/2}\Lambda\Lambda^{-1/2} = I\) — identity, exactly. This matters for algorithms that assume spherical inputs (Chapter 5’s k-NN, Chapter 9’s RBF-SVM): after whitening, every direction contributes equally to distance, so a large-variance noise direction stops dominating.
Two cautions. Whitening amplifies noise along low-variance directions — dividing by a tiny \(\sqrt{\lambda}\) inflates what is mostly numerical error or measurement noise, so regularized variants use \(\lambda \to \lambda + \epsilon\). And it destroys any interpretability: after whitening, components are no longer “original units of feature \(j\)”.
def whiten(X, k, eps=1e-6):
U, vals, scores = pca_via_svd(X, k)
return scores / np.sqrt(vals + eps)
Zw = whiten(X, 3)
print(np.round(np.cov(Zw.T), 4)) # ~identity on the diagonal
What PCA does not do
The limitation to carry away: PCA maximizes variance, not usefulness. Concretely, it fails in three common ways.
Variance can be noise. If measurement error in one feature has larger scale than your signal features, the top components will align with the error. PCA will happily hand you the noisiest directions because they explain the most spread.
Class separation can be orthogonal to variance. The direction that best discriminates two classes may have low total variance — a narrow, well-separated pair of clusters along an axis with small spread. PCA discards it, because discarding it barely reduces reconstruction error. With strong class imbalance or tight clusters on a low-variance axis, LDA (Chapter 10’s shared-covariance Gaussian NB, which is the same algebra with a between-class scatter matrix) optimizes the right quantity instead.
It is unsupervised, so it cannot use labels at all. Any supervised signal is thrown away by construction. On tabular prediction problems, supervised alternatives — selecting features by importance, or fitting a supervised low-dimensional embedding — frequently beat PCA.
PCA vs feature selection, the frequent confusion: PCA produces new features that are linear combinations of the originals — you cannot point at one and say “this is hours-of-sleep”. Feature selection keeps original features and stays interpretable. On small-\(d\) tabular data, selection is often the better first move; PCA earns its keep when \(d \gg n\).
Pitfalls
- Forgetting to center. PCA on uncentered data finds the direction of the mean, not of the variation. The library centers for you, but hand-rolled PCA that skips it is subtly wrong.
- Using it to combat the curse of dimensionality. PCA truncates, but k-NN on the truncated space is still k-NN; the cure is a metric or a model that doesn’t rely on raw distance (Chapters 5, 9).
- Reading components as features. A component is a mixture; “PC1 = 0.6·income − 0.5·age” is not an interpretable driver. Use permutation importance on the original features instead.
- Whitening low-variance directions. Dividing by a near-zero \(\lambda\) amplifies noise. Regularize with \(\epsilon\).
- Interpreting explained variance as accuracy. 99% of variance retained says nothing about whether your model will work. It is a reconstruction statement, and only that (Eckart–Young).
- Expecting supervised performance. PCA cannot see labels. When discrimination is the goal, use LDA or a supervised method.
Derive PCA from reconstruction error: show that minimizing \(\sum_i\lVert\tilde{x}_i\rVert^2 - n u^\top\Sigma u\) over unit \(u\) leads to the eigenvector equation, and say what the Lagrange multiplier \(\lambda\) represents. State the Eckart–Young result and explain why it means PCA is globally optimal rather than greedy. Why is the SVD route numerically preferable even though both are mathematically identical? Your PCA keeps 99% of variance and your classifier got worse — give two reasons the derivation predicts.
ASolution
The \(\sum\lVert\tilde{x}_i\rVert^2\) term is data-only, so minimizing error is maximizing \(u^\top\Sigma u\); with the constraint \(\lVert u\rVert = 1\) enforced via \(\mathcal{L} = u^\top\Sigma u - \lambda(u^\top u - 1)\), stationarity gives \(2\Sigma u - 2\lambda u = 0\), i.e. \(\Sigma u = \lambda u\); and the objective value at that point is \(\lambda\), so \(\lambda\) is the variance along \(u\) — the multiplier is the captured variance, which is why eigenvalue order selects components. Eckart–Young–Mirsky says the minimum error over all rank-\(k\) approximations equals the sum of the \(k\) largest singular values, attained by the leading directions; since PCA attains that bound, the greedy sequential construction is provably optimal, and the leftover error is exactly \(\sum_{j>k}\lambda_j\). SVD is preferred because the eigendecomposition route forms \(\Sigma = X^\top X/n\), and \(\text{cond}(X^\top X) = \text{cond}(X)^2\) — squaring the condition number destroys precisely the small eigenvalues PCA exists to resolve, whereas SVD factorizes \(X\) directly and never forms the Gram matrix. For a worse classifier at 99% variance retained: (1) the retained directions may be dominated by high-variance noise rather than signal — large-scale measurement error maximizes spread, so the top components can be noise directions while the low-variance but discriminative direction is discarded; (2) PCA is unsupervised, and the direction that separates classes may be nearly orthogonal to the top variance directions (tight clusters on a low-spread axis give small reconstruction error to discard), so the component carrying the label signal is the one removed. Explained variance is a reconstruction guarantee only and says nothing about predictive value.
Next: Deriving the Bias-Variance Decomposition (ML #13) — the exact identity behind every generalization claim in this course.