Eigenvectors, SVD and PCA¶
Every matrix, however messy, is secretly a rotation, a stretch along perpendicular axes, and another rotation. Finding those axes (eigenvectors for symmetric matrices, singular vectors for all matrices) tells you what a matrix really does, how much of it matters, and how to compress it. PCA is the same idea pointed at a cloud of data.
10,000 ft
Decompositions are how you look inside a matrix. The eigen-decomposition explains what happens when a map is applied over and over: why recurrent networks explode or vanish, why gradient descent diverges above a learning rate set by the loss surface's sharpest curvature (optimisation), and how PageRank ranks the web. The singular value decomposition (SVD) applies to every matrix and gives the provably best low-rank approximation, which underlies compression, LoRA-style fine-tuning (LoRA), latent semantic analysis, recommender systems and the spectral norm that bounds how much a layer can amplify its input. PCA, the oldest dimensionality-reduction method, is the SVD of centred data, and it is still the first thing to try when you want to see the shape of embeddings (dimensionality reduction).
2,000 ft
An eigenvector of a square matrix \(A\) is a direction that \(A\) only stretches: \(A\mathbf{v} = \lambda\mathbf{v}\), with stretch factor \(\lambda\) (the eigenvalue). A symmetric matrix has a full set of perpendicular eigenvectors, so in those coordinates it is just a diagonal stretch: \(A = Q\Lambda Q^\top\). For any matrix, square or not, the SVD writes \(A = U\Sigma V^\top\): rotate (by \(V^\top\)), stretch each axis by a singular value \(\sigma_i\ge 0\), rotate again (by \(U\)). Keep only the largest \(k\) singular values and you have the best rank-\(k\) approximation of \(A\) (Eckart–Young). PCA centres a data matrix and takes its SVD: the right singular vectors are the directions of greatest variance, and the squared singular values tell you how much variance each one explains.
Ground level¶
Eigenvectors: the directions a map does not turn¶
Most vectors change direction when you apply a matrix. A few special ones do not; they are only scaled. Take
Try \(\mathbf{v} = (1,1)\): \(A\mathbf{v} = (3,3) = 3\mathbf{v}\). Try \(\mathbf{v}=(1,-1)\): \(A\mathbf{v} = (1,-1) = 1\cdot\mathbf{v}\). So \(A\) stretches the diagonal direction by 3 and leaves the anti-diagonal alone. Every other vector is a mix of these two and gets bent toward the diagonal, because one component is tripled and the other is not.
Finding them. \(A\mathbf{v} = \lambda\mathbf{v}\) means \((A - \lambda I)\mathbf{v} = \mathbf{0}\) has a non-zero solution, so \(A-\lambda I\) must squash some direction to zero, so \(\det(A - \lambda I) = 0\). For our \(A\):
This characteristic polynomial has degree \(n\), so an \(n\times n\) matrix has \(n\) eigenvalues counted with multiplicity, possibly complex. Two useful checks: the eigenvalues sum to the trace (sum of the diagonal, here \(2+2 = 3+1\)) and multiply to the determinant (here \(4-1 = 3\times 1\)).
Set the widget below to \(\begin{pmatrix}2&1\\1&2\end{pmatrix}\) and find the two lines that stay put. Then try a rotation: no real direction survives, and the eigenvalues become complex. Try a shear \(\begin{pmatrix}1&1\\0&1\end{pmatrix}\): only one eigen-direction exists. Such a matrix is called defective: it cannot be diagonalised.
Diagonalisation, and what repeated application does¶
If an \(n\times n\) matrix has \(n\) independent eigenvectors, put them as columns of \(P\) and the eigenvalues on the diagonal of \(\Lambda\):
In eigen-coordinates the map is just "multiply coordinate \(i\) by \(\lambda_i\)", and \(k\) applications multiply it by \(\lambda_i^k\). Everything about long-run behaviour follows:
- The component along the eigenvector with the largest \(\lvert\lambda\rvert\) comes to dominate. Starting from \(\mathbf{x} = (1,0)\) with our \(A\), \(A^{10}\mathbf{x} = (29525, 29524)\): pointing along \((1,1)\) to four decimal places. This is power iteration, the simplest eigenvector algorithm, and essentially how PageRank was computed: the ranking is the dominant eigenvector of the web's link matrix.
- If all \(\lvert\lambda_i\rvert < 1\), \(A^k\mathbf{x}\to\mathbf{0}\); if any \(\lvert\lambda_i\rvert > 1\), it blows up. The largest \(\lvert\lambda\rvert\) is the spectral radius.
Why plain RNNs could not remember
A linear recurrent network updates \(\mathbf{h}_{t+1} = W\mathbf{h}_t\), so after 50 steps the state is \(W^{50}\mathbf{h}_0\), and the gradient flowing back 50 steps is multiplied by \((W^\top)^{50}\). With \(W\) a rotation scaled by 0.9, \(\lVert\mathbf{h}_{50}\rVert = 0.9^{50}\approx 0.005\); scaled by 1.1, it is \(1.1^{50}\approx 117\). Signals and gradients vanish or explode geometrically: the analysis of Pascanu, Mikolov and Bengio (2013). LSTMs, gating, residual connections and careful initialisation are all ways of keeping the relevant eigenvalues near 1 (RNNs and LSTMs).
Symmetric matrices: the spectral theorem¶
Symmetric matrices (\(A = A^\top\)) are the best-behaved of all, and they are everywhere in ML: covariance matrices, Hessians (second derivatives), kernel/Gram matrices \(XX^\top\). The spectral theorem says a real symmetric matrix has
- only real eigenvalues, and
- a full set of eigenvectors that can be chosen orthonormal,
so
Geometrically: a symmetric matrix stretches space along \(n\) perpendicular axes, with no shearing or rotation. Our \(A\) is \(3\,\mathbf{q}_1\mathbf{q}_1^\top + 1\,\mathbf{q}_2\mathbf{q}_2^\top\) with \(\mathbf{q}_1 = (1,1)/\sqrt2\), \(\mathbf{q}_2 = (1,-1)/\sqrt2\).
Quadratic forms and curvature. For symmetric \(A\), the function \(f(\mathbf{x}) = \mathbf{x}^\top A\mathbf{x}\) is, in eigen-coordinates \(\mathbf{y} = Q^\top\mathbf{x}\), simply \(\sum_i\lambda_iy_i^2\). If all \(\lambda_i>0\) (positive definite) it is a bowl; mixed signs give a saddle. Near a minimum, any smooth loss looks like \(\tfrac12(\mathbf{x}-\mathbf{x}^*)^\top H(\mathbf{x}-\mathbf{x}^*)\) where \(H\) is the Hessian, so the Hessian's eigenvalues are the curvatures along its principal axes. That has a sharp consequence for training:
Gradient descent is stable only when the learning rate is below 2/λ_max
On \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top H\mathbf{x}\), gradient descent is \(\mathbf{x}\leftarrow\mathbf{x} - \eta H\mathbf{x} = (I-\eta H)\mathbf{x}\). In eigen-coordinates each component is multiplied by \((1-\eta\lambda_i)\) every step. It shrinks only if \(\lvert 1-\eta\lambda_i\rvert<1\), i.e. \(0<\eta<2/\lambda_i\). So the sharpest direction (largest \(\lambda\)) caps the learning rate, while the flattest direction (smallest \(\lambda\)) sets how slowly you converge. Their ratio, the condition number \(\kappa = \lambda_{\max}/\lambda_{\min}\), measures how hard the problem is for plain gradient descent, which is the problem momentum and Adam attack (optimisers). Cohen et al. (2021) found that full-batch training of neural networks typically drives \(\lambda_{\max}\) of the Hessian up until it hovers right at \(2/\eta\), the "edge of stability".
The singular value decomposition¶
Eigenvectors need a square matrix and may not exist (rotations) or may not be perpendicular. The SVD has no such caveats: every real \(m\times n\) matrix factors as
where \(U\in\mathbb{R}^{m\times m}\) and \(V\in\mathbb{R}^{n\times n}\) are orthogonal, \(\Sigma\) is \(m\times n\) with non-negative singular values \(\sigma_1\ge\sigma_2\ge\dots\ge\sigma_r>0\) on its diagonal and zeros elsewhere, and \(r\) is the rank. The columns \(\mathbf{v}_i\) are the right singular vectors (input directions), the \(\mathbf{u}_i\) the left singular vectors (output directions), and \(A\mathbf{v}_i = \sigma_i\mathbf{u}_i\): each input axis is sent to an output axis, stretched by \(\sigma_i\).
The picture. \(A\) maps the unit sphere to an ellipsoid. The ellipsoid's semi-axes have lengths \(\sigma_i\) and point along \(\mathbf{u}_i\); the points of the sphere that land on them are the \(\mathbf{v}_i\).
Worked example. \(B = \begin{pmatrix}3&0\\4&5\end{pmatrix}\). Compute \(B^\top B = \begin{pmatrix}25&20\\20&25\end{pmatrix}\), whose eigenvalues are \(45\) and \(5\) with eigenvectors \((1,1)/\sqrt2\) and \((-1,1)/\sqrt2\). So \(\sigma_1 = \sqrt{45} = 3\sqrt5\approx 6.708\), \(\sigma_2 = \sqrt5\approx 2.236\), \(\mathbf{v}_1 = (1,1)/\sqrt2\), \(\mathbf{v}_2 = (-1,1)/\sqrt2\), and \(\mathbf{u}_i = B\mathbf{v}_i/\sigma_i\) gives \(\mathbf{u}_1 = (1,3)/\sqrt{10}\), \(\mathbf{u}_2 = (-3,1)/\sqrt{10}\). Checks: \(\sigma_1\sigma_2 = 15 = \lvert\det B\rvert\), and the condition number is \(\sigma_1/\sigma_2 = 3\). (NumPy returns the same vectors up to sign; see Build it.)
How the SVD relates to eigenvalues. \(A^\top A = V\Sigma^\top\Sigma V^\top\) and \(AA^\top = U\Sigma\Sigma^\top U^\top\). So the \(\mathbf{v}_i\) are eigenvectors of \(A^\top A\), the \(\mathbf{u}_i\) eigenvectors of \(AA^\top\), and \(\sigma_i^2\) are their shared non-zero eigenvalues. For a symmetric positive semi-definite matrix the SVD and the eigen-decomposition coincide.
What the singular values tell you.
- Spectral norm \(\lVert A\rVert_2 = \sigma_1\): the most \(A\) can stretch any vector. For a network layer it bounds how much a small input perturbation can be amplified. Spectral normalisation (Miyato et al., 2018) divides each weight matrix by an estimate of \(\sigma_1\) (found by one step of power iteration per training step) to stabilise GAN discriminators.
- Rank = number of non-zero \(\sigma_i\); numerical rank = number above a tolerance.
- Condition number \(\kappa = \sigma_1/\sigma_r\): how much relative error can be amplified when solving \(A\mathbf{x}=\mathbf{b}\) (numerical computing).
- Frobenius norm \(\lVert A\rVert_F = \sqrt{\sum_{ij}A_{ij}^2} = \sqrt{\sum_i\sigma_i^2}\): the total "energy", split among the directions.
- The spectrum's shape. Martin and Mahoney (2018) analyse the distribution of singular values of trained weight matrices with random-matrix theory and find heavy-tailed spectra, which they interpret as a form of implicit self-regularisation that emerges during training.
Low-rank approximation: Eckart–Young¶
Since \(A = \sum_i\sigma_i\mathbf{u}_i\mathbf{v}_i^\top\) with the terms sorted by size, the obvious compression is to keep the first \(k\):
The Eckart–Young theorem (Eckart and Young, 1936) says this is not just obvious but optimal: among all matrices of rank at most \(k\), \(A_k\) is closest to \(A\), with error
Storage drops from \(mn\) numbers to \(k(m+n+1)\).
Worked example. A \(64\times 64\) synthetic "image" built from three rank-1 patterns plus a little noise has singular values \(54.86, 22.83, 3.53, 0.75, 0.73, \dots\). The cliff after the third value is the structure; everything after is noise. Truncating:
| rank \(k\) | error \(\lVert A - A_k\rVert_F\) | numbers stored | of 4,096 |
|---|---|---|---|
| 1 | 23.30 | 129 | 3% |
| 2 | 4.66 | 258 | 6% |
| 3 | 3.05 | 387 | 9% |
| 10 | 2.46 | 1,290 | 31% |
The measured errors match the Eckart–Young prediction to every printed digit (Build it). Past rank 3 you are spending parameters to memorise noise, a small version of the bias–variance trade-off (bias, variance and regularisation).
Where low rank shows up in modern AI:
- LoRA learns a rank-\(r\) update \(BA\) to frozen weights (Hu et al., 2021). PiSSA (Meng et al., 2024) initialises those factors from the top singular vectors of the pretrained weight instead of from zero and noise.
- GaLore (Zhao et al., 2024) projects gradients onto their top singular directions to cut optimiser memory during full training.
- Recommender systems factor the users × items rating matrix into low-rank user and item vectors, the idea at the centre of the Netflix Prize (2006–2009).
- Randomised SVD (Halko, Martinsson and Tropp, 2009) computes the top-\(k\) singular vectors of huge matrices by multiplying by a few random vectors first, the trick inside scikit-learn's fast PCA.
PCA: the SVD of your data¶
You have \(n\) data points in \(\mathbb{R}^d\) as rows of \(X\in\mathbb{R}^{n\times d}\). Principal component analysis asks: which direction captures the most variance? Then the next, perpendicular to the first, and so on.
- Centre: subtract the mean of each column, \(X_c = X - \mathbf{1}\boldsymbol{\mu}^\top\). (Skip this and the first "component" mostly points at the mean.)
- Covariance: \(C = \frac{1}{n-1}X_c^\top X_c\in\mathbb{R}^{d\times d}\), symmetric positive semi-definite.
- Eigen-decompose: \(C = Q\Lambda Q^\top\). The eigenvectors \(\mathbf{q}_1,\mathbf{q}_2,\dots\) (sorted by eigenvalue) are the principal components; \(\lambda_i\) is the variance of the data along \(\mathbf{q}_i\); \(\lambda_i/\sum_j\lambda_j\) is the fraction of variance explained.
- Project: the reduced coordinates are \(Z = X_cQ_k\), with \(Q_k\) the first \(k\) eigenvectors. Reconstruct with \(\hat{X} = ZQ_k^\top + \mathbf{1}\boldsymbol{\mu}^\top\).
In practice you skip forming \(C\) and take the SVD of \(X_c\) directly: if \(X_c = U\Sigma V^\top\) then \(C = V\frac{\Sigma^2}{n-1}V^\top\), so the principal components are the columns of \(V\) and the variances are \(\sigma_i^2/(n-1)\). This is more accurate because forming \(X^\top X\) squares the condition number.
Worked example. 500 points drawn with standard deviation 3 along one axis and 0.5 along the other, rotated by 30° and shifted. True variances are 9 and 0.25. PCA recovers variances 8.767 and 0.234 (sampling noise), a first axis at 30.1°, and 97.4% of the variance in the first component. The covariance route and the SVD route give identical answers. Drag the points in the widget and watch the axes follow.
Things PCA does not do
- It finds linear directions only. Data on a curved surface (a "Swiss roll") needs non-linear methods such as t-SNE, UMAP or autoencoders (dimensionality reduction, autoencoders).
- It is scale-sensitive: a feature measured in rupees will dominate one measured in lakhs. Standardise features first unless their units are comparable.
- High variance is not the same as importance for a task. The direction separating two classes can have low variance.
- Components are only defined up to sign, and nearly equal eigenvalues make their directions unstable from sample to sample.
History¶
From rotating bodies to recommender systems
Eigenvalue problems arose in the 18th century in the mechanics of rotating bodies and vibrating strings (Euler, Lagrange). Cauchy proved in 1829 that symmetric matrices have real eigenvalues. Eugenio Beltrami (1873) and Camille Jordan (1874) independently discovered the singular value decomposition; David Hilbert's work on integral equations around 1904 gave us the word eigen ("own", "characteristic"). Karl Pearson introduced what we now call PCA in 1901 as finding the lines and planes of closest fit to a cloud of points, and Harold Hotelling developed it in 1933 under the name principal components. Carl Eckart and Gale Young proved the low-rank optimality theorem in 1936. Gene Golub and William Kahan's 1965 algorithm made the SVD practical on computers. Then applications multiplied: latent semantic analysis (Deerwester et al., 1990) took the SVD of term–document matrices; "eigenfaces" (Turk and Pentland, 1991) used PCA for face recognition; PageRank (Brin and Page, 1998) was a dominant eigenvector; and matrix factorisation was at the heart of the Netflix Prize (2006–2009).
First principles¶
Why symmetric matrices have perpendicular eigenvectors. Suppose \(A\mathbf{v} = \lambda\mathbf{v}\) and \(A\mathbf{w} = \mu\mathbf{w}\) with \(\lambda\ne\mu\). Using symmetry, \(\lambda(\mathbf{v}\cdot\mathbf{w}) = (A\mathbf{v})\cdot\mathbf{w} = \mathbf{v}\cdot(A\mathbf{w}) = \mu(\mathbf{v}\cdot\mathbf{w})\). Since \(\lambda\ne\mu\), \(\mathbf{v}\cdot\mathbf{w} = 0\). Symmetry, meaning "\(A\) is its own adjoint", is exactly what forces orthogonality.
Why eigenvectors are the answer to an optimisation problem. Ask: along which unit direction \(\mathbf{w}\) does a symmetric \(A\) give the largest value of \(\mathbf{w}^\top A\mathbf{w}\) (the Rayleigh quotient)? Write \(\mathbf{w}\) in eigen-coordinates, \(\mathbf{w} = \sum_i c_i\mathbf{q}_i\) with \(\sum_i c_i^2 = 1\). Then \(\mathbf{w}^\top A\mathbf{w} = \sum_i\lambda_ic_i^2\), a weighted average of eigenvalues with weights \(c_i^2\). It is maximised by putting all the weight on \(\lambda_{\max}\), i.e. \(\mathbf{w} = \mathbf{q}_1\). Restrict to directions perpendicular to \(\mathbf{q}_1\) and the maximum is \(\lambda_2\) at \(\mathbf{q}_2\), and so on. For \(A = C\), the covariance matrix, \(\mathbf{w}^\top C\mathbf{w}\) is exactly the variance of the data projected onto \(\mathbf{w}\). So the direction of maximum variance is the top eigenvector of the covariance. That is PCA, derived from nothing but "find the most spread-out direction".
Why maximum variance equals minimum reconstruction error. For a centred point \(\mathbf{x}\) and a unit direction \(\mathbf{w}\), Pythagoras gives \(\lVert\mathbf{x}\rVert^2 = (\mathbf{w}\cdot\mathbf{x})^2 + \lVert\mathbf{x} - (\mathbf{w}\cdot\mathbf{x})\mathbf{w}\rVert^2\). The left side is fixed by the data, so maximising the projected part (variance) is the same as minimising the residual part (reconstruction error). Pearson's "closest fit" and Hotelling's "maximum variance" are one problem.
Why the SVD always exists. \(A^\top A\) is symmetric and positive semi-definite (\(\mathbf{x}^\top A^\top A\mathbf{x} = \lVert A\mathbf{x}\rVert^2\ge0\)), so by the spectral theorem it has orthonormal eigenvectors \(\mathbf{v}_i\) with eigenvalues \(\sigma_i^2\ge0\). Define \(\mathbf{u}_i = A\mathbf{v}_i/\sigma_i\) for \(\sigma_i>0\). These are orthonormal too: \(\mathbf{u}_i\cdot\mathbf{u}_j = \mathbf{v}_i^\top A^\top A\mathbf{v}_j/(\sigma_i\sigma_j) = \sigma_j^2\,\mathbf{v}_i\cdot\mathbf{v}_j/(\sigma_i\sigma_j)\), which is 1 if \(i=j\) and 0 otherwise. Complete both sets to orthonormal bases and \(A\mathbf{v}_i = \sigma_i\mathbf{u}_i\) for every \(i\) is the SVD. So the SVD is the spectral theorem applied to \(A^\top A\).
The maths¶
Eigen-decomposition. \(A\mathbf{v} = \lambda\mathbf{v}\), \(\mathbf{v}\ne\mathbf{0}\). Eigenvalues are roots of \(p(\lambda) = \det(A-\lambda I)\). \(\sum_i\lambda_i = \operatorname{tr}A\), \(\prod_i\lambda_i = \det A\). If diagonalisable, \(A = P\Lambda P^{-1}\) and \(f(A) = Pf(\Lambda)P^{-1}\) for powers, exponentials and polynomials.
Spectral theorem. \(A = A^\top\in\mathbb{R}^{n\times n}\Rightarrow A = Q\Lambda Q^\top\) with \(Q\) orthogonal and \(\Lambda\) real diagonal. \(A\) is positive definite iff all \(\lambda_i>0\).
SVD. \(A\in\mathbb{R}^{m\times n}\): \(A = U\Sigma V^\top\), \(U\in\mathbb{R}^{m\times m}\), \(V\in\mathbb{R}^{n\times n}\) orthogonal, \(\Sigma\in\mathbb{R}^{m\times n}\) diagonal with \(\sigma_1\ge\dots\ge\sigma_{\min(m,n)}\ge0\). The "thin" SVD keeps \(U\in\mathbb{R}^{m\times r}\), \(\Sigma\in\mathbb{R}^{r\times r}\), \(V\in\mathbb{R}^{n\times r}\). \(\lVert A\rVert_2 = \sigma_1\), \(\lVert A\rVert_F^2 = \sum\sigma_i^2\), \(\kappa(A) = \sigma_1/\sigma_r\). Pseudo-inverse \(A^+ = V\Sigma^+U^\top\) (invert the non-zero \(\sigma_i\)), which gives the least-squares solution \(\mathbf{x} = A^+\mathbf{b}\).
Derivation: PCA via Lagrange multipliers
Maximise the projected variance \(\mathbf{w}^\top C\mathbf{w}\) subject to \(\mathbf{w}^\top\mathbf{w} = 1\). The Lagrangian is
Setting \(\nabla_{\mathbf{w}}\mathcal{L} = 2C\mathbf{w} - 2\lambda\mathbf{w} = \mathbf{0}\) gives \(C\mathbf{w} = \lambda\mathbf{w}\): every stationary point is an eigenvector. At such a point the objective is \(\mathbf{w}^\top C\mathbf{w} = \lambda\mathbf{w}^\top\mathbf{w} = \lambda\), so the maximum is the largest eigenvalue, attained at its eigenvector. For the \(k\)-dimensional version, maximise \(\operatorname{tr}(W^\top CW)\) over \(W\in\mathbb{R}^{d\times k}\) with \(W^\top W = I_k\); the maximum is \(\lambda_1+\dots+\lambda_k\), attained by the top-\(k\) eigenvectors (Ky Fan's theorem).
Eckart–Young (Frobenius norm), proof sketch
Let \(B\) have rank \(k\). Its null space has dimension \(n-k\), so it intersects the \((k+1)\)-dimensional span of \(\mathbf{v}_1,\dots,\mathbf{v}_{k+1}\) in at least a line; pick a unit \(\mathbf{z}\) there. Then \(\lVert(A-B)\mathbf{z}\rVert = \lVert A\mathbf{z}\rVert\ge\sigma_{k+1}\), because \(\mathbf{z}\) is a unit combination of the top \(k+1\) right singular vectors. So \(\lVert A-B\rVert_2\ge\sigma_{k+1} = \lVert A - A_k\rVert_2\), which is the spectral-norm version. The Frobenius version follows by applying the same argument to the \(i\)-th singular value of \(A-B\) (Weyl's inequality \(\sigma_{i+k}(A)\le\sigma_i(A-B)\)) and summing squares: \(\lVert A-B\rVert_F^2\ge\sum_{i>k}\sigma_i^2(A) = \lVert A-A_k\rVert_F^2\).
Build it¶
NumPy only: power iteration, PCA two ways, and a check of Eckart–Young.
import numpy as np
rng = np.random.default_rng(0)
# 1. Power iteration: repeated multiplication finds the dominant eigenvector
def power_iteration(A, steps=50):
v = rng.standard_normal(A.shape[1])
for _ in range(steps):
v = A @ v
v /= np.linalg.norm(v)
return v @ A @ v, v # Rayleigh quotient, eigenvector
A = np.array([[2.0, 1.0], [1.0, 2.0]])
lam, v = power_iteration(A)
print("power iteration:", round(lam, 6), v.round(4))
# 2. PCA from scratch on correlated 2-D data
n = 500
z = rng.standard_normal((n, 2)) * [3.0, 0.5] # long axis 3, short axis 0.5
t = np.radians(30)
R = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
X = z @ R.T + [5.0, -2.0] # rotate by 30 degrees, shift
Xc = X - X.mean(axis=0) # centre (essential)
C = Xc.T @ Xc / (n - 1) # covariance
evals, evecs = np.linalg.eigh(C) # ascending order
evals, evecs = evals[::-1], evecs[:, ::-1]
print("covariance eigenvalues:", evals.round(3), " explained:", (evals / evals.sum()).round(3))
print("first axis:", evecs[:, 0].round(3), " angle:", round(np.degrees(np.arctan2(evecs[1, 0], evecs[0, 0])) % 180, 1))
U, s, Vt = np.linalg.svd(Xc, full_matrices=False) # same thing via SVD of the data
print("via SVD :", (s**2 / (n - 1)).round(3), Vt[0].round(3))
# 3. Eckart-Young: truncated SVD is the best rank-k approximation
i, j = np.mgrid[0:64, 0:64] / 63
img = np.sin(6 * i) * np.cos(4 * j) + (i > 0.5) * 0.8 + 0.6 * np.outer(np.hanning(64), np.hanning(64))
img += 0.05 * rng.standard_normal(img.shape)
U, s, Vt = np.linalg.svd(img)
for k in [1, 2, 3, 5, 10]:
approx = (U[:, :k] * s[:k]) @ Vt[:k]
err = np.linalg.norm(img - approx)
print(f"rank {k:>2}: error {err:6.3f} predicted {np.sqrt((s[k:]**2).sum()):6.3f} "
f"params {k * (64 + 64 + 1):>4} of {64 * 64}")
Output:
power iteration: 3.0 [-0.7071 -0.7071]
covariance eigenvalues: [8.767 0.234] explained: [0.974 0.026]
first axis: [-0.865 -0.501] angle: 30.1
via SVD : [8.767 0.234] [-0.865 -0.501]
rank 1: error 23.298 predicted 23.298 params 129 of 4096
rank 2: error 4.664 predicted 4.664 params 258 of 4096
rank 3: error 3.049 predicted 3.049 params 387 of 4096
rank 5: error 2.866 predicted 2.866 params 645 of 4096
rank 10: error 2.456 predicted 2.456 params 1290 of 4096
Notice the sign: power iteration and the SVD both returned vectors pointing "backwards", \((-0.707, -0.707)\) and \((-0.865, -0.501)\). Eigenvectors and singular vectors are defined only up to sign, so never compare them across runs without aligning signs first.
Things to try
- Run power iteration on \(\begin{pmatrix}2&1\\1&2.01\end{pmatrix}\) versus \(\begin{pmatrix}1&0.99\\0.99&1\end{pmatrix}\) and count the steps to converge. The speed depends on \(\lvert\lambda_2/\lambda_1\rvert\).
- Load any image as a greyscale array (for instance with Pillow), take its SVD and plot the reconstruction at ranks 5, 20 and 50. Plot \(\sigma_i\) on a log scale and look for the "knee".
- Download a set of word or sentence embeddings, run PCA, and project onto the first two components. Do the clusters you expect appear? How much variance do two components explain in 384 or 768 dimensions?
- Verify numerically that gradient descent on \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top H\mathbf{x}\) with \(H = \operatorname{diag}(10, 1)\) converges for \(\eta = 0.19\) and diverges for \(\eta = 0.21\).
- Implement spectral normalisation: estimate \(\sigma_1\) of a random \(256\times 128\) matrix with 1, 5 and 20 power-iteration steps and compare with
np.linalg.norm(W, 2).
In practice¶
- Use
np.linalg.eigh(noteig) for symmetric matrices: it is faster, guarantees real output, and returns orthonormal eigenvectors in ascending order. - For PCA on large data use the SVD of the centred data, or
sklearn.decomposition.PCA(which uses randomised SVD for big inputs), neverinvor explicit \(X^\top X\) when accuracy matters. - Decide how many components to keep by explained variance (for example 90–95%), by a knee in the singular values, or by downstream validation performance. The last is the only one that measures what you care about.
- For visualising embeddings, PCA to about 50 dimensions followed by t-SNE or UMAP is a common recipe; read How to use t-SNE effectively before trusting any cluster picture.
Check yourself¶
Find the eigenvalues and eigenvectors of [[4, 1], [2, 3]].
\(\det\begin{pmatrix}4-\lambda&1\\2&3-\lambda\end{pmatrix} = \lambda^2 - 7\lambda + 10 = 0\), so \(\lambda = 5\) or \(2\) (trace 7, determinant 10 ✓). For \(\lambda=5\): \((A-5I)\mathbf{v} = \mathbf{0}\) gives \(-v_1 + v_2 = 0\), so \(\mathbf{v} = (1,1)\). For \(\lambda=2\): \(2v_1 + v_2 = 0\), so \(\mathbf{v} = (1,-2)\). Not perpendicular: the matrix is not symmetric.
What are the singular values of a 2×2 rotation matrix, and of the projection [[1, 0], [0, 0]]?
A rotation preserves lengths, so both singular values are 1 (although its eigenvalues are complex). The projection has singular values 1 and 0: rank 1.
A covariance matrix has eigenvalues 6, 3, 0.6, 0.3, 0.1. How many components keep at least 90% of the variance?
Total 10. Cumulative: 60%, 90%, 96%, … So 2 components keep exactly 90%.
Why must you centre the data before PCA?
PCA finds directions of maximum variance, which is spread around the mean. Without centring, \(X^\top X/(n-1)\) measures the second moment about the origin, and for data far from the origin the top "component" points roughly at the mean, telling you where the data is, not how it spreads.
The Hessian at a minimum has eigenvalues 100 and 0.01. What is the largest stable learning rate for gradient descent, and how many steps does the flat direction need to shrink its error by e?
Stability needs \(\eta < 2/100 = 0.02\). At, say, \(\eta = 0.019\) the flat component shrinks by a factor \((1 - 0.019\times0.01)\) per step, so about \(1/0.00019\approx 5{,}300\) steps per factor of \(e\). That gap (\(\kappa = 10^4\)) is why ill-conditioning makes plain gradient descent slow.
Hard: a weight matrix W is 4096 × 4096 with σ₁ = 40 and all other singular values below 1. What does that say about the layer, and what would spectral normalisation do?
The layer is close to rank 1 plus a small remainder: it amplifies one input direction \(\mathbf{v}_1\) by 40 into one output direction \(\mathbf{u}_1\), and damps everything else. Small input perturbations along \(\mathbf{v}_1\) are magnified 40×. Dividing by \(\sigma_1\) caps the gain at 1 (making the layer 1-Lipschitz), which also shrinks every other direction by 40×. That trade is acceptable in a GAN discriminator, where smoothness is the goal.
Hard: why does forming XᵀX before an eigen-decomposition lose accuracy compared with taking the SVD of X directly?
The condition number of \(X^\top X\) is \(\kappa(X)^2\). With \(\kappa(X) = 10^5\), \(\kappa(X^\top X) = 10^{10}\), and in float32 (about 7 significant digits) the small eigenvalues of \(X^\top X\) are swamped by rounding error: the smallest principal directions become noise. The SVD works on \(X\) itself and keeps the \(10^5\).
Go deeper¶
Papers
- On lines and planes of closest fit to systems of points in space — Karl Pearson, Philosophical Magazine, 1901. The birth of PCA, as a geometry problem.
- Analysis of a complex of statistical variables into principal components — Harold Hotelling, 1933. Where the name and the variance view come from.
- The approximation of one matrix by another of lower rank — Eckart and Young, Psychometrika, 1936. The optimality of truncated SVD.
- A Tutorial on Principal Component Analysis — Jonathon Shlens, 2014. The clearest derivation-first tutorial; read it in one sitting.
- Finding structure with randomness — Halko, Martinsson, Tropp, 2009. Randomised SVD; Section 1 is a superb overview of why low rank is everywhere.
- Spectral Normalization for Generative Adversarial Networks — Miyato et al., 2018. The spectral norm as a training tool.
- Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability — Cohen et al., 2021. Hessian eigenvalues meet real training.
- On the difficulty of training Recurrent Neural Networks — Pascanu, Mikolov, Bengio, 2013. Exploding and vanishing gradients through the spectral radius.
Videos and lectures
- Eigenvectors and eigenvalues — 3Blue1Brown, Essence of linear algebra, Chapter 14.
- Singular Value Decomposition (the SVD) — Gilbert Strang, MIT OpenCourseWare. The master explaining his favourite factorisation.
- Singular Value Decomposition (SVD): Mathematical Overview — Steve Brunton. First of a long, data-science-oriented series.
- SVD Visualized — Visual Kernel. The rotate–stretch–rotate picture in motion.
Articles and blog posts
- Principal Component Analysis explained visually — Victor Powell and Lewis Lehe. Interactive PCA in 2-D and 3-D.
- How to Use t-SNE Effectively — Wattenberg, Viégas, Johnson, Distill, 2016. What comes after PCA, and how it misleads.
Courses and books
- MIT 18.065 Matrix Methods in Data Analysis, Signal Processing, and Machine Learning — Gilbert Strang. Lectures 6–9 on the SVD and low rank.
- Mathematics for Machine Learning — Deisenroth, Faisal, Ong. Chapter 4 (decompositions) and Chapter 10 (PCA), derived three ways.
Where this leads¶
- Tensors, shapes and broadcasting — the batched array code every decomposition here runs on.
- Optimisation: convex and not — Hessian eigenvalues, conditioning and why Adam helps.
- PCA, t-SNE and UMAP — PCA's non-linear successors.
- Parameter-efficient fine-tuning: LoRA and QLoRA — low rank as a fine-tuning budget.
- Mechanistic interpretability — finding meaningful directions inside a network's activations.