TExcelTAD
Home › Linear Algebra & Matrix Theory › Application: Principal Component Analysis

Application: Principal Component Analysis

Principal component analysis (PCA) finds the directions along which a cloud of data points varies the most. In linear algebra terms it is nothing more than the spectral decomposition of the covariance matrix, and it is one of the most used tools in data science.

The setup

Suppose we have nn data points in Rd\mathbb{R}^d, stored as the rows of an n×dn \times d matrix XX. PCA works in three steps:

1. Centre:Xc=X−mean of each column2. Covariance:C=XcTXc/(n−1)(d×d, symmetric, PSD)3. Diagonalize:C=QΛQT,λ1≥λ2≥⋯≥λd≥0\begin{aligned} &\text{1. Centre:} && X_c = X - \text{mean of each column} \\ &\text{2. Covariance:} && C = X_c^TX_c / (n - 1) && (d \times d,\ \text{symmetric, PSD}) \\ &\text{3. Diagonalize:} && C = Q\Lambda Q^T, \quad \lambda_1 \ge \lambda_2 \ge \cdots \ge \lambda_d \ge 0 \end{aligned}

The columns q1,q2,…\mathbf{q}_1, \mathbf{q}_2, \ldots of QQ are the principal components (directions) and λi\lambda_i is the variance of the data along qi\mathbf{q}_i. The scores XcQX_cQ are the coordinates of each point in the new orthonormal basis.

Why the eigenvectors?

The variance of the data projected onto a unit vector u\mathbf{u} is

Var⁡(Xcu)=(Xcu)T(Xcu)n−1=uTCu\operatorname{Var}(X_c\mathbf{u}) = \frac{(X_c\mathbf{u})^T(X_c\mathbf{u})}{n - 1} = \mathbf{u}^TC\mathbf{u}

a quadratic form. Over all unit vectors, uTCu\mathbf{u}^TC\mathbf{u} is largest at the top eigenvector of CC, where it equals λ1\lambda_1 (the Rayleigh quotient fact). Among directions orthogonal to q1\mathbf{q}_1 the maximum is λ2\lambda_2 at q2\mathbf{q}_2, and so on. CC is symmetric and positive semidefinite, so the spectral theorem guarantees real, nonnegative eigenvalues and orthogonal components.

The explained variance ratio of component ii is λi/(λ1+⋯+λd)\lambda_i / (\lambda_1 + \cdots + \lambda_d). Since the trace is preserved, λ1+⋯+λd\lambda_1 + \cdots + \lambda_d equals the total variance (the sum of the column variances).

By hand with NumPy

Made-up data: height and weight-like measurements that are strongly correlated, plus a third feature that is mostly noise.

python · try it yourself
import numpy as np

rng = np.random.default_rng(42)
n = 200
t = rng.normal(0, 1, n)
X = np.column_stack([170 + 8 * t + rng.normal(0, 2, n),
                     65 + 6 * t + rng.normal(0, 2, n),
                     rng.normal(0, 1, n)])

Xc = X - X.mean(axis=0)
C = Xc.T @ Xc / (n - 1)
lam, Q = np.linalg.eigh(C)
order = np.argsort(lam)[::-1]          # eigh gives ascending order; PCA wants descending
lam, Q = lam[order], Q[:, order]
print("eigenvalues (variances):", np.round(lam, 3))
print("explained ratio:", np.round(lam / lam.sum(), 4))
print("total variance check:", round(float(lam.sum()), 3), "=", round(float(np.trace(C)), 3))
print("PC1 direction:", np.round(Q[:, 0], 4))
scores = Xc @ Q
print("score covariance is diagonal:", np.allclose(np.cov(scores.T), np.diag(lam)))
eigenvalues (variances): [79.04   4.019  1.022]
explained ratio: [0.94   0.0478 0.0122]
total variance check: 84.082 = 84.082
PC1 direction: [-0.7991 -0.6012  0.0022]
score covariance is diagonal: True

The first component explains about 94% of the variance and points (up to sign) along (0.80,0.60,0.00)(0.80, 0.60, 0.00): mostly "size", a mix of the first two features. The noise feature contributes almost nothing to it. In the new coordinates the features are uncorrelated: the covariance of the scores is diagonal.

The same thing with scikit-learn

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

rng = np.random.default_rng(42)
n = 200
t = rng.normal(0, 1, n)
X = np.column_stack([170 + 8 * t + rng.normal(0, 2, n),
                     65 + 6 * t + rng.normal(0, 2, n),
                     rng.normal(0, 1, n)])

pca = PCA(n_components=3).fit(X)
print("sklearn variances:", np.round(pca.explained_variance_, 3))
print("sklearn ratio    :", np.round(pca.explained_variance_ratio_, 4))

Xc = X - X.mean(axis=0)
lam, Q = np.linalg.eigh(Xc.T @ Xc / (n - 1))
Q = Q[:, ::-1]
same = [bool(np.isclose(abs(float(pca.components_[i] @ Q[:, i])), 1.0)) for i in range(3)]
print("same directions up to sign:", same)

Z = pca.transform(X)[:, :2]                       # keep 2 of 3 dimensions
X_back = pca.inverse_transform(np.column_stack([Z, np.zeros(n)]))
print("mean squared reconstruction error:", round(float(np.mean((X - X_back) ** 2)), 4))
sklearn variances: [79.04   4.019  1.022]
sklearn ratio    : [0.94   0.0478 0.0122]
same directions up to sign: [True, True, True]
mean squared reconstruction error: 0.339

scikit-learn does not form the covariance matrix: it computes the SVD of the centred data, Xc=UΣVTX_c = U\Sigma V^T. Then XcTXc=VΣ2VTX_c^TX_c = V\Sigma^2V^T, so the right singular vectors are the principal components and λi=σi2/(n−1)\lambda_i = \sigma_i^2/(n - 1). The SVD route is more accurate because it avoids squaring the condition number, exactly as with least squares.

Dropping the last component loses only its variance: the mean squared error per entry is about λ3⋅(n−1)/(n⋅3)\lambda_3 \cdot (n - 1)/(n \cdot 3), here 1.022⋅199/600≈0.3391.022 \cdot 199/600 \approx 0.339.

Note: Eigenvectors are only defined up to sign, so two correct PCA implementations may report q\mathbf{q} and −q-\mathbf{q}. Compare directions with ∣q⋅q′∣≈1\lvert \mathbf{q} \cdot \mathbf{q}' \rvert \approx 1, never entry by entry.

Tip: Standardize features measured in different units (StandardScaler) before PCA. Otherwise the feature with the biggest numbers wins regardless of how informative it is: PCA on the covariance of unscaled data is not scale-invariant.

In software

  • Dimensionality reduction. Compress hundreds of features to the few components that hold most of the variance before clustering or regression (PCA in ML).
  • Visualization. Projecting high-dimensional data (or word embeddings) onto the top two components gives a quick 2D scatter plot.
  • Faces and images. "Eigenfaces" are the principal components of a set of face images.
  • Graphics and games. The principal axes of a point cloud give a tight oriented bounding box and the best-fit plane (the normal is the smallest-variance component).
  • Finance. PCA of interest-rate curves finds the "level, slope, curvature" factors.

Exercises

Exercise 1: Two points

Data points (1,1)(1, 1) and (3,3)(3, 3). What is the first principal component and its variance?

Answer

q1=(1,1)/2\mathbf{q}_1 = (1, 1)/\sqrt{2} with variance 4 (sample covariance, n−1=1n - 1 = 1); the second variance is 0.

Solution

The mean is (2,2)(2, 2); centred points are ±(1,1)\pm(1, 1). C=[(1,1)T(1,1)+(1,1)T(1,1)]/1=[2222]C = [(1,1)^T(1,1) + (1,1)^T(1,1)] / 1 = \begin{bmatrix} 2 & 2 \\ 2 & 2 \end{bmatrix}. Its eigenvalues are 4 (on (1,1)(1, 1)) and 0 (on (1,−1)(1, -1)).

Exercise 2: Explained variance

A covariance matrix has eigenvalues 6, 3, 1. How many components keep at least 85% of the variance?

Answer

Two (90%).

Solution

Total 10. One component keeps 60%, two keep 90%≥85%90\% \ge 85\%.

Exercise 3: Uncorrelated already

Data with covariance matrix diag⁡(5,2)\operatorname{diag}(5, 2). What are the principal components?

Answer

The coordinate axes: e1\mathbf{e}_1 with variance 5, then e2\mathbf{e}_2 with variance 2.

Solution

A diagonal matrix's eigenvectors are the standard basis vectors and its eigenvalues are its diagonal entries; sort them in descending order.

Exercise 4: PCA from scratch (code)

For the points (2,0)(2, 0), (0,1)(0, 1), (−2,0)(-2, 0), (0,−1)(0, -1), compute the covariance matrix and principal components.

Answer

C=diag⁡(8/3,2/3)C = \operatorname{diag}(8/3, 2/3); PC1=x-axis\text{PC1} = x\text{-axis} (variance 8/3≈2.66678/3 \approx 2.6667), PC2=y-axis\text{PC2} = y\text{-axis} (variance 2/3≈0.66672/3 \approx 0.6667).

Solution

The mean is 0. XTX=[8002]X^TX = \begin{bmatrix} 8 & 0 \\ 0 & 2 \end{bmatrix}; divide by n−1=3n - 1 = 3.

python · try it yourself
import numpy as np
X = np.array([[2, 0], [0, 1], [-2, 0], [0, -1]], dtype=float)
C = np.cov(X.T)
lam, Q = np.linalg.eigh(C)
print(np.round(C, 4).tolist(), np.round(lam[::-1], 4), np.abs(Q[:, ::-1]).tolist())
[[2.6667, 0.0], [0.0, 0.6667]] [2.6667 0.6667] [[1.0, 0.0], [0.0, 1.0]]

Test yourself

The first principal component is…

  1. the column of XX with the largest mean
  2. the eigenvector of the covariance matrix with the largest eigenvalue
  3. the eigenvector with the smallest eigenvalue
  4. the first row of XX

Why might your PCA give −q-\mathbf{q} where scikit-learn gives q\mathbf{q}?

  1. One of them has a bug
  2. Eigenvectors are only determined up to sign
  3. scikit-learn does not centre the data
  4. Because the data was not standardized

If the eigenvalues of the covariance are 9, 0.9 and 0.1, the first component explains…

  1. 9%
  2. 50%
  3. 90%
  4. 99%