Principal component analysis

Principal component analysis computed live, one power iteration per step: centering, covariance, axes, deflation, projection, explained variance and reconstruction, in 2D, 3D and on iris.

Updated

  • Variance and covariance
  • Eigenvectors as directions of spread
  • Power iteration and deflation
  • Projection and reconstruction
  • How many components to keep
iter 0iter 1iter 2iter 3iter 4v ← Cv / ‖Cv‖
Preparing the lab…

Intuition

Find where the data spread most

A tilted, elliptical cloud of points varies a lot along both axes, but the two variations are one and the same: the points lie along a diagonal line. PCA rotates the axes onto that line: along it (the first principal component) the variance is largest, and perpendicular to it (the second) little is left. Dropping the second coordinate then loses almost nothing.

The three small labs below run power iteration for real in your browser. The orange arrow is the direction being iterated, turning step by step towards the direction of largest variance; the black arrows are components already found, of length 2λ2\sqrt\lambda.

2D correlated dataPreparing…
3D ellipsoid (first two features)Preparing…
Iris on its first two componentsPreparing…

First: 2D points lie along a diagonal; power iteration finds it in 6 iterations, and it explains 95.99% of the variance, leaving 4% for the second direction.

Second: 3D data seen from above. The first component explains 88.3%, the second 11.1% and the third only 0.6% — the cloud is nearly a flat ellipse, so two components keep 99.36% of the variance.

Third: the famous iris data, with 4 features (sepal and petal length and width), standardised and projected onto the first two components. The three species (colours) roughly separate along the first component alone — without PCA ever seeing the species labels.

Math

Centring and covariance

nn samples, dd features. Subtract each feature's mean (optionally divide by its standard deviation) to get ZZ, then compute the sample covariance:

C=1n−1Z⊤ZC = \frac{1}{n-1} Z^\top Z

CabC_{ab} is the covariance of features aa and bb, the diagonal holds the variances, and the trace tr⁡C\operatorname{tr}C is the total variance.

Components are eigenvectors

Find the unit vector vv that maximises the projected variance v⊤Cvv^\top C v. A Lagrange multiplier gives Cv=λvCv = \lambda v: the direction of greatest variance is the eigenvector of the largest eigenvalue, and that variance is λ\lambda. The next component maximises variance among directions perpendicular to the first — the second eigenvector. Component kk's explained-variance ratio is λk/tr⁡C\lambda_k / \operatorname{tr}C.

Power iteration

Instead of a general eigenvalue routine, this page multiplies step by step:

v←Cv∥Cv∥v \leftarrow \frac{Cv}{\|Cv\|}

Decompose vv along the eigenvectors: each multiplication by CC scales the kk-th component by λk\lambda_k, so after normalising, every component except the largest shrinks by λk/λ1\lambda_k/\lambda_1. The speed is therefore set by λ2/λ1\lambda_2/\lambda_1. The lab measures convergence by the change in direction 1−∣v⋅vold∣1 - |v\cdot v_{\text{old}}|, which shrinks by roughly (λ2/λ1)2(\lambda_2/\lambda_1)^2:

  • the default ellipsoid has λ2/λ1≈0.125\lambda_2/\lambda_1 \approx 0.125: the change goes 1→0.557→1.6×10−3→2.3×10−51 \to 0.557 \to 1.6\times10^{-3} \to 2.3\times10^{-5}, about ×0.016 per step, converging in 9 iterations;
  • the near-flat data have λ2/λ1≈0.455\lambda_2/\lambda_1 \approx 0.455 and need 21.

After each component comes deflation: C←C−λvv⊤C \leftarrow C - \lambda v v^\top removes that direction's variance, and iteration restarts from a point perpendicular to the components found; what was the second largest is now the largest.

Projection and reconstruction

Keep the first kk components VkV_k (k×dk\times d):

projection  z=(x−μ)Vk⊤,reconstruction  x^=μ+zVk\text{projection}\; z = (x - \mu)V_k^\top, \qquad \text{reconstruction}\; \hat x = \mu + zV_k

The reconstruction error equals exactly the sum of the discarded eigenvalues (times (n−1)/n(n-1)/n).

Standardisation

IrisPC1PC2
Centred only92.46%5.31%
Standardised72.96%22.85%

Unstandardised, the first component is about (0.361,−0.085,0.857,0.358)(0.361, -0.085, 0.857, 0.358) — mostly petal length, the feature with the widest range and hence the largest variance. Standardised, every feature has variance 1, all four compete equally, and the first component's share drops to 73%. Which is right depends on whether the units are comparable; with different units (metres and millimetres, money and head-counts) standardise.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: power iteration and variance

5 steps · each one: set up and run → look → answer

  1. 1. The direction turns

    2D correlated data, 3 steps. Watch the white dashed line (the vector being iterated) in "Original space".

    Why does multiplying by C a few times line the direction up with the long axis?
  2. 2. Three components

    The 3D ellipsoid, run to the end. Open "Explained variance".

    The third component holds only 0.6%. What does that mean?
  3. 3. Fast and slow convergence

    Switch to "Near-flat" and watch the convergence chart.

    Why does the first component need 21 iterations (the ellipsoid only 9)?
  4. 4. Iris

    Iris, centred only. Look at PC1's direction and share.

    PC1 explains 92%. Which feature dominates it?
  5. 5. Standardise

    Set scaling to "Standardized" and look at the component space.

    Why does PC1's share drop from 92% to 73%?

Try these settings

Exercises

Exercises

Exercise 1: which data are almost one-dimensional?

Keep a single component without standardising. Change the dataset so that it keeps at least 95% of the variance.

Hint

2D correlated: 95.99%. Iris gives 92.46%, the ellipsoid 88.3%, near-flat only 68.5%.

  • Variance kept (1) ≥ 0.950

Exercise 2: stop the first component dominating

With one component, iris keeps 92.46% of its variance. Change one setting to bring it to 75% or below.

Hint

Set scaling to "Standardized": 72.96%.

  • Variance kept (1) ≤ 0.750

Quiz

How are principal components related to each other?
When does power iteration converge slowly?
Does PCA use the samples' labels?

Further reading

Frequently asked questions

What are the principal components in PCA?

The eigenvectors of the data's covariance matrix, ordered by eigenvalue (variance) from largest to smallest. The first is the direction of greatest projected variance; each subsequent one has the greatest variance among directions perpendicular to those before it.

How many principal components should I keep?

Look at the cumulative explained variance: keeping 90% or 95% is common, or look for the bend in the scree plot. On this page's 3D ellipsoid, two components already keep 99.36%.

Should I standardise before PCA?

Yes, when features have different units or very different ranges; otherwise the large-valued features dominate. Unstandardised, iris's first component is almost pure petal length (92%); standardised it holds 73% with contributions from all four features.

How are PCA and SVD related?

Take the singular value decomposition of the centred data, Z = UΣVᵀ: the columns of V are the principal directions and the eigenvalues are λ = σ²/(n − 1). scikit-learn implements PCA with the SVD, which is numerically more stable; this page uses power iteration to show every step, with matching results.

Can PCA handle nonlinear structure?

No, it finds linear directions only. Curved manifolds call for kernel PCA, t-SNE, UMAP and similar methods.

Further reading