TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Principal Component Analysis

Principal Component Analysis

A table with 64 pixel columns, or 30 blood measurements, or 13 chemical properties of wine, rarely has 64, 30 or 13 independent directions of variation: the columns move together. Principal component analysis (PCA) finds new axes, the principal components, ordered so that the first captures as much of the data's variance as possible, the second as much of the rest as possible while being perpendicular to the first, and so on. Keeping the first few gives a compact description of the data for plotting, compression, denoising or as input to another model. The Machine Learning course applies it with scikit-learn; here you compute it two ways and see why both work.

Two equivalent definitions

Centre the data (subtract each column's mean), giving Xc∈Rn×dX_c \in \mathbb{R}^{n \times d} with covariance matrix Σ=1n−1Xc⊤Xc\Sigma = \frac{1}{n-1} X_c^\top X_c.

Maximum variance. The first component is the unit vector w\mathbf{w} along which the projected data has the largest variance:

w1=arg⁡max⁡∥w∥=1w⊤Σ w.\mathbf{w}_1 = \arg\max_{\lVert \mathbf{w} \rVert = 1} \mathbf{w}^\top \Sigma \, \mathbf{w} .

With a Lagrange multiplier this becomes Σw=λw\Sigma \mathbf{w} = \lambda \mathbf{w}: the components are the eigenvectors of the covariance matrix, and the variance along each is its eigenvalue λ\lambda. Sorting by eigenvalue gives the order.

Minimum reconstruction error. Projecting onto the first kk components and mapping back loses as little as possible in squared error; the error left is the sum of the dropped eigenvalues, ∑j>kλj\sum_{j > k} \lambda_j.

Both views give the same axes. Since Σ\Sigma is symmetric, its eigenvectors are orthogonal. In practice PCA is computed from the singular value decomposition Xc=USW⊤X_c = U S W^\top: the rows of W⊤W^\top are the components and λj=sj2/(n−1)\lambda_j = s_j^2/(n-1), without ever forming Σ\Sigma. Derivations: PCA: Maximum Variance, PCA: Minimum Reconstruction Error, Singular Value Decomposition, Eigendecomposition and Principal Component Analysis in Linear Algebra.

See it

The lab draws 120 centred points with correlation ρ\rho, turns the cloud onto its principal axes, and with k=1k = 1 drops every point onto the first component. The arrows are the components (twice the standard deviation along each), the bars the explained variance. At the start, ρ=0.8\rho = 0.8, PC1 keeps 90.8 % of the variance (λ1=3.868\lambda_1 = 3.868, λ2=0.392\lambda_2 = 0.392). Raise ρ\rho towards 0.95: almost all variance lies along PC1, and projecting onto it loses little. Set ρ=0\rho = 0 with equal spreads and there is no preferred direction at all.

−505−505PC1 scorePC2 scoreProjected onto PC1 (k = 1)PC1PC2Explained variance ratio0%25%50%75%100%90.8 %PC19.2 %PC2kept with k = 1: 90.8 %

From scratch, two routes

Three features: x2x_2 strongly correlated with x1x_1, and a small independent x3x_3:

python · try it yourself
import numpy as np
from sklearn.decomposition import PCA

rng = np.random.default_rng(0)
n = 200
x1 = rng.normal(size=n)
x2 = 0.8 * x1 + 0.6 * rng.normal(size=n)               # correlation about 0.8
x3 = 0.3 * rng.normal(size=n)                          # a small independent direction
X = np.column_stack([x1, x2, x3])
Xc = X - X.mean(axis=0)                                # PCA works on centred data

# route 1: eigendecomposition of the covariance matrix
cov = Xc.T @ Xc / (n - 1)
lam, V = np.linalg.eigh(cov)                          # ascending order
lam, V = lam[::-1], V[:, ::-1]
# route 2: SVD of the centred data, Xc = U S W^T, eigenvalues = S^2 / (n - 1)
U, S, Wt = np.linalg.svd(Xc, full_matrices=False)

pca = PCA().fit(X)
print("eigenvalues      ", lam.round(4))
print("from the SVD     ", (S ** 2 / (n - 1)).round(4))
print("sklearn variances", pca.explained_variance_.round(4))
print("explained variance ratio:", pca.explained_variance_ratio_.round(3))
same_dirs = np.allclose(np.abs(V.T), np.abs(pca.components_))   # equal up to the sign of each axis
print("same axes as sklearn (up to sign):", same_dirs)
print("first axis:", pca.components_[0].round(3))

Z = Xc @ V[:, :2]                                      # project onto the first two axes
X_back = Z @ V[:, :2].T                                # reconstruct
err = ((Xc - X_back) ** 2).sum() / (n - 1)
print("reconstruction error with 2 axes:", round(err, 4), " = third eigenvalue:", round(lam[2], 4))
eigenvalues       [1.6255 0.2166 0.0896]
from the SVD      [1.6255 0.2166 0.0896]
sklearn variances [1.6255 0.2166 0.0896]
explained variance ratio: [0.841 0.112 0.046]
same axes as sklearn (up to sign): True
first axis: [0.711 0.703 0.019]
reconstruction error with 2 axes: 0.0896  = third eigenvalue: 0.0896

The eigendecomposition, the SVD and scikit-learn give the same variances and the same axes; an axis and its negative describe the same line, so signs are arbitrary (scikit-learn fixes them by a convention). The first component, (0.711,0.703,0.019)(0.711, 0.703, 0.019), is essentially "x1+x2x_1 + x_2" and carries 84.1 % of the variance. Dropping the third component loses exactly its eigenvalue, 0.0896, as the minimum-error view predicts.

Using the components

  • transform gives the scores Z=XcWkZ = X_c W_k, the coordinates on the first kk axes; use them for plots or as features.
  • inverse_transform maps scores back to the original space, a denoised or compressed version of the data.
  • explained_variance_ratio_ tells you how much each component keeps; its cumulative sum guides the choice of kk.
  • components_ are the loadings: how each original feature contributes to each component, the key to interpreting them.

PCA in Practice covers scaling, choosing kk and PCA inside a model pipeline.

Strengths, weaknesses, when to use it

Strengths Weaknesses
exact, fast (one SVD), no hyperparameters except kk only linear structure; curved manifolds need kernel PCA, t-SNE, UMAP or autoencoders
components are uncorrelated depends on feature scales
reconstruction error is known exactly components mix all features, so they can be hard to interpret
denoises by dropping small components high variance is not the same as useful for prediction

Use it to visualise high-dimensional data in 2-D, to compress correlated features, to remove noise, and to speed up or stabilise models that suffer from many correlated inputs. Its unsupervised cousins are in Data Preparation (dimensionality reduction), its neural generalisation in Autoencoders.

Pitfalls

  • Not centring. PCA without centring finds the direction of the mean, not of the variance. PCA centres for you; a hand-made SVD must too.
  • Fitting PCA on all the data before a train/test split. It is a fitted transformation; put it in the pipeline.
  • Assuming the top components predict the target. A low-variance direction can be the one that separates the classes.

Practice

  1. A 2-D data set has covariance matrix (3001)\begin{pmatrix} 3 & 0 \\ 0 & 1 \end{pmatrix}. What are the components and the explained variance ratios?
Answer

The matrix is diagonal, so its eigenvectors are the axes: PC1 =(1,0)= (1, 0) with λ1=3\lambda_1 = 3, PC2 =(0,1)= (0, 1) with λ2=1\lambda_2 = 1. Ratios 3/4=0.753/4 = 0.75 and 1/4=0.251/4 = 0.25.

  1. In the example, what reconstruction error would one component leave?
Answer

The sum of the dropped eigenvalues: 0.2166+0.0896=0.30620.2166 + 0.0896 = 0.3062, which is 0.112+0.046=15.80.112 + 0.046 = 15.8 % of the total variance.

Test yourself

What are the principal components of centred data?

  1. The columns with the largest values
  2. The eigenvectors of the covariance matrix, ordered by eigenvalue
  3. The cluster centroids
  4. The rows of the data

Keeping the first kk of dd components, what is the squared reconstruction error (per n−1n - 1)?

  1. λ1\lambda_1
  2. The sum of the kept eigenvalues
  3. The sum of the dropped eigenvalues
  4. Zero

How do the SVD Xc=USW⊤X_c = U S W^\top and the eigenvalues of the covariance relate?

  1. λj=sj\lambda_j = s_j
  2. λj=sj2/(n−1)\lambda_j = s_j^2/(n-1)
  3. λj=1/sj\lambda_j = 1/s_j
  4. They are unrelated