PCA and SVD: The Linear Algebra You Actually Need

Derive PCA via eigen decomposition and SVD. Prove they give identical results, build geometric intuition for SVD, and compress images with truncated SVD.

Cover Image for PCA and SVD: The Linear Algebra You Actually Need

A table has many correlated columns, and you want a smaller representation that keeps the main patterns. PCA approaches this through directions of variation, while SVD decomposes a matrix into components that can also be used for compression and recommendation. Connecting PCA and SVD makes it easier to understand why these apparently different tasks share a calculation.

The shared calculation can be checked both numerically and visually. PCA's two derivations agree to about 10−1610^{-16}. A rank-10 SVD reduces a 4,096-pixel face to 1,290 numbers while keeping it recognisable. We derive both routes and reconstruct the image as components are removed.

PCA on the Iris Dataset

Watch the Iris dataset project from four dimensions down to two. Each point is a flower; each colour is a species:

Iris dataset projected onto the first two principal components. Three species (setosa, versicolor, virginica) form distinct clusters, with PC1 explaining 73.0% and PC2 explaining 22.9% of the variance.

Let's Build It

Click the badge to run this yourself:

Open In Colab

import numpy as np
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler

# Load and standardise the Iris dataset
iris = load_iris()
X = StandardScaler().fit_transform(iris.data)  # 150 x 4
labels = iris.target

# PCA via eigen decomposition of the correlation matrix
cov_matrix = np.cov(X, rowvar=False)           # 4 x 4
eigenvalues, eigenvectors = np.linalg.eigh(cov_matrix)

# Sort by decreasing eigenvalue
idx = np.argsort(eigenvalues)[::-1]
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:, idx]

# Project onto the first two principal components
scores = X @ eigenvectors[:, :2]
Eigenvalues: [2.938 0.920 0.148 0.021]
Variance explained: [73.0% 22.9% 3.7% 0.5%]
Cumulative: [73.0% 95.8% 99.5% 100.0%]

Four features compressed to two, retaining 95.8% of the variance. Setosa separates cleanly on the first component alone; versicolor and virginica need both. If you have seen our post on LDA vs PCA, you will recognise this plot. The difference is that PCA found these axes without ever looking at the species labels.

What Just Happened?

Standardisation: Making Features Comparable

The original R code uses scale(X), which centres each feature to mean zero and divides by the standard deviation. Our Python equivalent is StandardScaler. Without this step, a feature measured in centimetres would dominate one measured in millimetres, simply because it has a larger variance. Standardising puts all features on equal footing, so PCA finds directions of genuine multivariate variation rather than tracking whichever variable has the largest units.

The R code explicitly notes this choice:

"You tend to use the covariance matrix when the variable scales are similar and the correlation matrix when variables are on different scales. Using the correlation matrix standardises the data."

When you standardise first and then compute the covariance matrix, you get the correlation matrix. Our code does exactly this.

Eigen Decomposition: Finding the Best Axes

The covariance matrix C=1n−1X⊤X\mathbf{C} = \frac{1}{n-1}\mathbf{X}^\top\mathbf{X} is a p×pp \times p symmetric matrix (here 4 x 4). Its eigenvectors are the principal component directions; its eigenvalues are the variances along those directions.

Cvi=λivi\mathbf{C}\mathbf{v}_i = \lambda_i \mathbf{v}_i

The first eigenvector v1\mathbf{v}_1 points in the direction that captures the most variance. The second, v2\mathbf{v}_2, captures the most remaining variance while being orthogonal to v1\mathbf{v}_1. And so on. The eigenvalue λi\lambda_i tells you how much variance that component explains.

Choosing How Many Components to Keep

Individual and cumulative variance explained by each principal component. PC1 alone captures 73.0%, PC1+PC2 capture 95.8%.

The variance explained chart shows that two components capture 95.8% of the total variance. The third and fourth components contribute only 3.7% and 0.5%, respectively. For the Iris dataset, two dimensions are enough. For higher-dimensional datasets, you would look for the "elbow" in the cumulative curve, similar to the elbow method for choosing k in K-Means.

Going Deeper: The SVD Connection

Here is the key insight. There is a second way to compute PCA that never forms the covariance matrix. Instead, you decompose the centred data matrix directly using SVD:

X=UΣV⊤\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top

where X\mathbf{X} is n×pn \times p (150 x 4), U\mathbf{U} is n×nn \times n, Σ\boldsymbol{\Sigma} is n×pn \times p with singular values on the diagonal, and V\mathbf{V} is p×pp \times p.

The columns of V\mathbf{V} are the principal component directions (the eigenvectors we computed above). The singular values σi\sigma_i relate to the eigenvalues by:

λi=σi2n−1\lambda_i = \frac{\sigma_i^2}{n - 1}

Let's verify this:

# PCA via SVD of the centred data matrix
U, S, Vt = np.linalg.svd(X, full_matrices=False)

# Eigenvectors from SVD
V_svd = Vt.T

# Eigenvalues from singular values
n = X.shape[0]
eigenvalues_from_svd = S**2 / (n - 1)
                Eigen     SVD s²/(n-1)     Difference
PC1            2.9381       2.9381       2.78e-16
PC2            0.9202       0.9202       2.22e-16
PC3            0.1477       0.1477       1.39e-17
PC4            0.0207       0.0207       4.34e-18

Side-by-side comparison of eigenvalues computed via eigen decomposition and via SVD, showing they match to machine precision (differences of order 10^-16).

The differences are on the order of 10−1610^{-16}, which is machine epsilon for 64-bit floating point. The two methods are mathematically identical.

The Underlying Mechanism

Substitute the SVD into the covariance formula:

C=1n−1X⊤X=1n−1(UΣV⊤)⊤(UΣV⊤)\mathbf{C} = \frac{1}{n-1}\mathbf{X}^\top\mathbf{X} = \frac{1}{n-1}(\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top)^\top(\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top)

Since U\mathbf{U} has orthonormal columns (U⊤U=I\mathbf{U}^\top\mathbf{U} = \mathbf{I}):

C=1n−1VΣ⊤ΣV⊤=V(Σ2n−1)V⊤\mathbf{C} = \frac{1}{n-1}\mathbf{V}\boldsymbol{\Sigma}^\top\boldsymbol{\Sigma}\mathbf{V}^\top = \mathbf{V}\left(\frac{\boldsymbol{\Sigma}^2}{n-1}\right)\mathbf{V}^\top

This is exactly the eigendecomposition of C\mathbf{C}, with eigenvectors V\mathbf{V} and eigenvalues σi2/(n−1)\sigma_i^2/(n-1). The R code computes this as sdev <- s$d / sqrt(var) where var = nrow(X) - 1, then values <- sdev * sdev.

The Geometry of SVD

SVD says that every linear transformation can be decomposed into three steps: a rotation, a scaling, and another rotation. To see this, imagine applying the matrix X\mathbf{X} to a unit circle:

Four-panel diagram showing SVD geometry: (1) unit circle, (2) after rotation by V^T, (3) after scaling by singular values, (4) after final rotation by U. The unit circle becomes an axis-aligned ellipse.

  1. V⊤\mathbf{V}^\top rotates the coordinate system to align with the principal directions.
  2. Σ\boldsymbol{\Sigma} scales each axis by the corresponding singular value, stretching the circle into an ellipse.
  3. U\mathbf{U} rotates the ellipse into its final orientation in the output space.

The singular values are the semi-axis lengths of the ellipse. The largest singular value corresponds to the direction of greatest "stretch," which is exactly the first principal component.

This geometric interpretation explains why PCA and SVD are the same: PCA finds the axes of the ellipse that best describe the data cloud. SVD finds the axes of the ellipse that describe any linear transformation. When the "transformation" is the centred data matrix itself, you get PCA.

Image Compression with Truncated SVD

The real power of SVD emerges when you truncate it. Keep only the top kk singular values and their corresponding vectors:

X≈UkΣkVk⊤\mathbf{X} \approx \mathbf{U}_k\boldsymbol{\Sigma}_k\mathbf{V}_k^\top

This is the best rank-k approximation in the Frobenius norm (the Eckart-Young-Mirsky theorem). Watch a face emerge as we increase the rank:

Animated GIF showing a face image reconstructed with increasing SVD rank, from rank 1 (blurry silhouette) to rank 64 (nearly photographic), demonstrating progressive detail recovery.

from sklearn.datasets import fetch_olivetti_faces

faces = fetch_olivetti_faces()
face = faces.images[0]  # 64 x 64 pixels

U, S, Vt = np.linalg.svd(face, full_matrices=False)

# Reconstruct with k components
def reconstruct(U, S, Vt, k):
    return U[:, :k] @ np.diag(S[:k]) @ Vt[:k, :]

Six panels showing a face reconstructed at ranks 1, 2, 5, 10, 20, and 64. At rank 1 only the overall brightness gradient is visible; by rank 10 the face is recognisable; at rank 20 most details are present.

The original image has 64 x 64 = 4,096 pixel values. A rank-10 approximation stores only 10 x (64 + 1 + 64) = 1,290 numbers (the 10 columns of U, 10 singular values, and 10 rows of V^T), just 31% of the original, yet the face is already recognisable. By rank 20, most fine detail is recovered at 63% of the original storage, a worthwhile trade when applied to thousands of images.

Why This Works: The Singular Value Spectrum

Bar chart of singular values showing rapid decay: the first few values are large, capturing coarse structure, while later values are small, encoding fine detail and noise.

The singular values decay rapidly. The first few capture the coarse structure (overall brightness, face shape), while later ones encode fine detail and noise. Truncating at rank k discards the small singular values, keeping the signal and removing the noise. This is the same principle behind denoising, dimensionality reduction for regression (PCR uses exactly this truncation), and latent semantic analysis in NLP.

Where This Comes From

PCA and SVD have separate historical origins that converged over decades.

PCA was introduced by Karl Pearson in 1901 as a method for fitting lines and planes to point clouds. Harold Hotelling independently developed it in 1933 as a tool for analysing psychological test scores, introducing the term "principal components" and the eigenvalue formulation we use today.

"The object of this paper is to find a few 'principal components' of the scores, a number of hypothetical variables possessing certain optimal properties."

Hotelling, H. (1933). Analysis of a complex of statistical variables into principal components. Journal of Educational Psychology, 24(6), 417-441.

SVD was developed by Eugenio Beltrami (1873) and Camille Jordan (1874) for square matrices, and extended to rectangular matrices by Carl Eckart and Gale Young in 1936. The connection to low-rank approximation (the Eckart-Young theorem) made SVD fundamental to numerical linear algebra. Gene Golub and William Kahan published the definitive numerical algorithm in 1965, later refined in Golub and Van Loan's classic textbook Matrix Computations (1996).

The practical equivalence of PCA and SVD was well understood by the 1960s, but using SVD for PCA became the standard numerical approach because it avoids forming X⊤X\mathbf{X}^\top\mathbf{X} explicitly. Squaring a matrix squares its condition number, amplifying numerical errors. SVD works directly with the data matrix, giving more accurate results for ill-conditioned datasets. This is why scikit-learn's PCA uses SVD internally, not eigen decomposition.

The original R code in this post's companion repository demonstrates both paths: eigen(cor(X)) for the eigenvalue approach and svd(scale(X), nu=0) for the SVD approach, verifying that they give the same eigenvalues, eigenvectors, and scores.

Further Reading

Try It Yourself

  1. Try a larger dataset. Replace Iris with the Wine or Breast Cancer dataset from scikit-learn. How many components do you need to capture 95% of the variance?
  2. Compress a colour image. Apply SVD separately to the R, G, and B channels. How does the compression ratio compare to greyscale?
  3. Denoise with truncated SVD. Add Gaussian noise to a face image, then reconstruct at various ranks. Find the rank that minimises reconstruction error on a held-out clean image.
  4. Compare with scikit-learn. Run sklearn.decomposition.PCA on the Iris data and verify that its components_ match our eigenvectors and its explained_variance_ matches our eigenvalues.

Interactive Tools

  • PCA Visualizer: Drag a point cloud and watch the principal components, scree plot and explained variance follow, then project onto one component to see what the reduction discards.
  • Eigenvalue and SVD Visualizer: Load the covariance-matrix preset and read the principal components straight off the plot as eigenvectors, then switch to the SVD tab to see the unit circle become an ellipse through the rotate-scale-rotate decomposition this post derives.
  • Distribution Explorer: Visualise the multivariate Gaussian whose covariance matrix PCA diagonalises.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions