Principal component analysis (PCA): reducing dimensions

Sometimes you want to shrink data with many numbers down to just a few. Drop numbers at random and you lose a lot. Principal component analysis finds the directions you can drop with the least regret. Turn the line and watch how the shadows of the points change.

Short answer. Principal component analysis (PCA) finds the direction in which the data is most spread out and uses that direction as a new axis. Drop the directions with less spread, and you cut down the number of values (the dimension) while losing as little information as possible. That direction is the eigenvector with the largest eigenvalue of the data's covariance matrix.

Squeezed onto one line: only the shadows, in 1D

°

What stays (spread of the shadows)

What is lost (mean of squared drop lengths)

( , )

Drag a blue point, or pick a point and change its numbers. The green line always passes through the mean (the black dot). Turn it with the slider, the number box, or the green handle at the end of the line. Each orange dashed line drops from a point to the line at a right angle, and the small black dot where it lands is the shadow. Press "Show answer" and the line turns to the first principal component, and two purple arrows appear (principal components 1 and 2). Each arrow is as long as the standard deviation in its direction. The points are made up by a random number generator with a fixed seed, so you get the same 20 points every time you open the page. "Remove a point" removes the chosen point (the black ring).

Definitions

The text below explains with pictures and experiments. These are the textbook definitions. The data are n points with d numbers each, 𝐱1,…,𝐱n∈ℝd, and 𝐱¯ is their mean. This page divides variances and covariances by n (some books divide by n − 1).

covariance matrix
Let X be the n × d matrix that has one mean-subtracted point in each row. The covariance matrix is the d × d matrix below. Its (j, k) entry is the covariance of the j-th and k-th numbers, and its diagonal entries are the variance of each number. It is a symmetric matrix.

C=1nX𝖳X=1n∑i=1n(𝐱i−𝐱¯)(𝐱i−𝐱¯)𝖳

eigenvalue, eigenvector
For a square matrix C, if a nonzero vector v and a number λ satisfy the equation below, λ is an eigenvalue of C and v is an eigenvector for λ. If C is symmetric, all its eigenvalues are real, and you can choose d unit eigenvectors that are orthogonal to each other. The eigenvalues of a covariance matrix are 0 or more.

C𝐯=λ𝐯

principal component
Order the eigenvalues of the covariance matrix as λ1≥λ2≥…≥λd. The principal components are matching orthogonal unit eigenvectors v₁, v₂, …, vd. The first principal component is the direction of length 1 that makes the variance of the projected values (the shadows), uᵀCu, as large as possible, and that largest value is λ₁. The k-th principal component is the direction, orthogonal to the first k − 1, that makes this variance as large as possible.

max‖𝐮‖=1𝐮𝖳C𝐮=𝐯1𝖳C𝐯1=λ1

principal component analysis (PCA)
A dimensionality reduction method. It projects each mean-subtracted point onto the first k principal components, turning a point in d dimensions into k coordinates. Vk=[𝐯1⋯𝐯k] is the d × k matrix with the principal components as columns.

𝐳i=Vk𝖳(𝐱i−𝐱¯)=((𝐱i−𝐱¯)·𝐯1,…,(𝐱i−𝐱¯)·𝐯k)

explained variance ratio
The share of the total variance (the sum of the eigenvalues, which is the trace of the covariance matrix) taken by the variance in the direction of the k-th principal component (its eigenvalue).

λkλ1+λ2+…+λd

reconstruction error
The average squared distance between each mean-subtracted point and the point you get back from its k coordinates. With the first k principal components, this equals the sum of the eigenvalues you dropped, and it is the smallest among all orthogonal projections down to k dimensions.

1n∑i=1n‖(𝐱i−𝐱¯)−VkVk𝖳(𝐱i−𝐱¯)‖2=λk+1+…+λd

1. Shrinking with shadows

A point on a plane is written with two numbers, (x, y). Drop the point onto a line at a right angle and you get a shadow. The shadow can be written with a single number: where it sits along the line. Two numbers became one. That is dimension reduction. Shrinking data with 1000 numbers per row down to 10 is the same idea in a bigger space.

Shrinking always loses something. What you lose is the distance from the point to the line (the drop). From the shadow alone you cannot tell how far, or on which side, the original point was.

Which line is best? If the shadows are widely spread, different points stay different numbers. If the shadows bunch together, different points get almost the same number and you can no longer tell them apart. So you pick the direction in which the shadows spread out the most. Spread is measured with the variance. That direction is the first principal component, and the direction at a right angle to it is the second principal component.

Try this. ① The line starts at 0° (flat). What stays is 3.03, what is lost is 1.82, and together they make 4.85. ② Turn the slider to 90° and the two swap: 1.82 and 3.03. At 45° they are 4.29 and 0.56. Wherever you turn it, the sum is 4.85. ③ Press "Show answer" and the line turns to 36°. What stays is 4.39, the largest it can be, and what is lost is 0.46, the smallest it can be. The dots on the strip below are also spread out the most at this angle.

2. Variance and covariance: how spread out, and moving together?

Variance is the average of the squared distances from the mean. x̄ ("x bar") is the mean of the x values, n is the number of points, and Σ means "add them all up".

variance of x = Σ (x − x̄)² ÷ n

The square root of the variance is the standard deviation. It undoes the squaring, so it is the spread back in the original units. In the lab, each purple arrow is as long as the standard deviation in its direction.

Covariance measures whether two numbers move together.

covariance of x and y = Σ (x − x̄)(y − ȳ) ÷ n

Put the variances and covariances in one table and you get the covariance matrix. The diagonal holds the variance of each number, and the other cells hold the covariances. Swapping the top right and bottom left gives the same value (it is symmetric), so a 2×2 one is set by three numbers. For data with d numbers per point, it is a d×d table.

C = [ sxx sxy / sxy syy ] (sxx is the variance of x, syy is the variance of y, sxy is the covariance)

With this one table you can work out the variance in any direction. Drop the shadows along a direction u = (u₁, u₂) of length 1, and their variance is:

variance along u = sxx·u₁² + 2·sxy·u₁·u₂ + syy·u₂² (as matrices: uᵀ C u)

Put in u = (1, 0) (that is, 0°) and you get sxx. That is why, in the lab's starting picture, what stays (3.03) equals sxx in the readout. This page divides by n, so the numbers match the bar for "spread of the shadows" (common question 5).

To see where this formula and "the most spread out direction is an eigenvector" come from, step through 4. How the formula is built.

3. The recipe: five steps

  1. Subtract the mean. For each number (each column of the table), subtract its mean. The center of the data moves to the origin. x − x̄, y − ȳ
  2. Build the covariance matrix. If X is the table after subtracting the mean (one point per row), then C = Xᵀ X ÷ n. Xᵀ is X with rows and columns swapped.
  3. Find the eigenvalues and eigenvectors. These are the length-1 vectors v and numbers λ with C v = λ v (see the eigenvalues and eigenvectors page). For a 2×2 C = [ a b / b d ] there is a formula:
    λ = (a + d) ÷ 2 ± √(((a − d) ÷ 2)² + b²), and the eigenvector is (b, λ − a) divided by its length (when b is not 0).
  4. Pick the biggest first. Sort the eigenvalues from largest to smallest and take the first k eigenvectors. These are principal components 1, 2, ..., k.
  5. Project. For each point, subtract the mean, then take the dot product with each chosen component. new coordinates = ((x − x̄)·v₁, (x − x̄)·v₂, ..., (x − x̄)·vₖ). d numbers become k numbers.

Why eigenvectors? C is symmetric, so it has two eigenvectors v₁ and v₂ at a right angle to each other. Any direction u of length 1 is a mix of the two: u = c₁·v₁ + c₂·v₂ with c₁² + c₂² = 1. Put that into the formula above and you get variance along u = λ₁·c₁² + λ₂·c₂². Since λ₁ ≥ λ₂, this can never be more than λ₁, and it equals λ₁ exactly when u = v₁ (c₁ = 1). In other words, the direction with the most spread is the eigenvector with the largest eigenvalue, and the variance in that direction is that eigenvalue. For the same reason, the direction with the least spread is v₂, and its variance is λ₂.

4. How the formula is built: the most spread out direction is an eigenvector

"Why eigenvectors?" in section 3 started from the answer (the eigenvectors) and checked it. Here we start without knowing the answer: measure the variance of the shadows, turn the line to find where it is largest, and watch C u = λ u appear there. The data is the lab's starting data (20 points). Press "Next" and a piece is added to the formula at the top (the orange background marks the new piece), the pictures change by that much, and the reason appears below.

The point picture uses the lab's colors. Blue points are the data, the green line and arrow u are the current direction, orange dashed lines drop at a right angle, and the small black dots are the shadows. The purple arrow is C u, the covariance matrix C times u, and the light purple band is the shadow of C u (its length is the variance in that direction). On the graph, across is the angle θ of the line and up is the variance in that direction.

  1. Start: x. The mean of the 20 points is (0.67, 0.45). We are looking for "the direction in which the shadows spread out the most when we squeeze the data onto one line" (section 1). There is no formula yet.
  2. Subtract the mean: x − x̄. Take (0.67, 0.45) away from every point and the cloud moves to the origin. The distances between points stay the same, so the covariance matrix stays the same too. Why: spread is measured from the mean. With the mean at the origin, the lab's "line through the mean" becomes "a line through the origin", and you can write its direction as one arrow u of length 1.
  3. Square the shadows and average: Var(u) = Σ ((x − x̄)·u)² ÷ n. Drop a point onto the line at a right angle and the position of its shadow is one dot product, (x − x̄)·u (see dot product). We subtracted the mean, so the shadow positions average to 0. That is why squaring the positions and averaging them gives exactly the variance of the shadows. For u = (0.71, 0.71) (45°) it is 4.29, the same as "what stays" in the lab when you turn the line to 45°.
  4. Write it out: = uᵀ C u. A shadow's position is (sideways gap)·u₁ + (up-down gap)·u₂. Squared, that is (sideways gap)²·u₁² + 2·(sideways gap)·(up-down gap)·u₁·u₂ + (up-down gap)²·u₂². Average over the points: the average of (sideways gap)² is sxx, the average of (sideways gap)·(up-down gap) is sxy, and the average of (up-down gap)² is syy (section 2). So Var(u) = sxx·u₁² + 2·sxy·u₁·u₂ + syy·u₂², the formula from section 2. You no longer need the 20 points one by one: the four numbers of the covariance matrix (3.03, 1.87, 1.87, 1.82) give the variance in any direction. With an angle θ, u = (cos θ, sin θ), so this is sxx·cos²θ + 2·sxy·cosθ·sinθ + syy·sin²θ. At 45°, cos²θ = sin²θ = cosθ·sinθ = 0.5, so 3.03 × 0.5 + 2 × 1.87 × 0.5 + 1.82 × 0.5 ≈ 4.29. Written with matrices this is uᵀ C u. Multiply C by u first and you get the arrow C u = (sxx·u₁ + sxy·u₂, sxy·u₁ + syy·u₂). Its dot product with u is exactly the formula above. In the picture, the variance is the length of the shadow that the purple arrow C u drops on the line. At 45°, C u = (3.46, 2.61).
  5. Turn the line all the way round: uᵀ C u ≤ λ₁. Turn the line from 0° to 180° and plot the variance, and you get a wave (after 180° the line is back where it started, so that is the end). It is 3.03 (sxx) at 0° and 1.82 (syy) at 90°. The top is 4.39 at 36° and the bottom is 0.46 at 126°. The top and the bottom are always exactly 90° apart. The formula says why. Rewrite it with trigonometry rules such as cos²θ = (1 + cos 2θ) ÷ 2, and it becomes (sxx + syy) ÷ 2 + √(((sxx − syy) ÷ 2)² + sxy²) × cos(2 × (θ − 36°)): a single cosine wave in twice the angle. Because the angle is doubled, one full wave takes 180°, and going from the top to the bottom, half a wave, takes 90°. The height of the top, (sxx + syy) ÷ 2 + √(((sxx − syy) ÷ 2)² + sxy²), is the + side of the 2×2 eigenvalue formula in section 3, and the bottom is the − side. Call the height of the top λ₁: no direction has more variance than λ₁.
  6. At the top: C u = λ₁ u. At 0°, C u = (3.03, 1.87) points 31.6° away from the line. The orange dashed line is the part of C u at a right angle to the line. Turn the line up to the top, 36°, and that part shrinks to 0, so C u lines up with u: C u = 4.39 u. That is the eigenvector equation C v = λ v from section 3, and the stretch factor is the variance at the top, 4.39, because the part of C u along the line is always the variance in that direction (step 4). Why the right-angle part is 0 at the top: it is half the slope of the graph (with the angle measured in radians; you can check this with calculus, and we do not prove it here). The orange line on the graph is that slope. At the top the slope is 0, so the right-angle part is 0. The slope is also 0 at the bottom (126°), where C u = 0.46 u. These two directions are principal components 1 and 2, and their variances, 4.39 and 0.46, are the eigenvalues λ₁ and λ₂.

5. Work it out by hand: four points

Four points: (3, 3), (−1, −1), (2, 0), (0, 2). The lab's "Hand example (4 points)" button places these points.

xyx − x̄y − ȳ(x − x̄)²(y − ȳ)²(x − x̄)(y − ȳ)
3322444
−1−1−2−2444
201−111−1
02−1111−1
Sum10106
  1. Mean. x̄ = (3 − 1 + 2 + 0) ÷ 4 = 1, ȳ = (3 − 1 + 0 + 2) ÷ 4 = 1.
  2. Subtract the mean. (2, 2), (−2, −2), (1, −1), (−1, 1). These are the third and fourth columns of the table.
  3. Covariance matrix. Divide the sums by 4. sxx = 10 ÷ 4 = 2.5, syy = 10 ÷ 4 = 2.5, sxy = 6 ÷ 4 = 1.5. So C = [ 2.5 1.5 / 1.5 2.5 ]. sxy is positive, so x and y tend to grow together.
  4. Eigenvalues. λ = (2.5 + 2.5) ÷ 2 ± √(0² + 1.5²) = 2.5 ± 1.5. λ₁ = 4, λ₂ = 1. Check: the sum 4 + 1 = 5 = 2.5 + 2.5 (the sum of the diagonal), and the product 4 × 1 = 4 = 2.5 × 2.5 − 1.5 × 1.5.
  5. Eigenvectors. For λ₁ = 4: (b, λ − a) = (1.5, 1.5). Divide by its length to get v₁ = (1, 1) ÷ √2 ≈ (0.71, 0.71), pointing at 45°. For λ₂ = 1: v₂ = (−1, 1) ÷ √2 ≈ (−0.71, 0.71), pointing at 135°. Their dot product is 0.71 × (−0.71) + 0.71 × 0.71 = 0, so they are at a right angle.
  6. Explained share. Principal component 1 explains 4 ÷ 5 = 80%, and principal component 2 explains 1 ÷ 5 = 20%.
  7. Squeeze onto one line. Take the dot product of each mean-subtracted point with v₁. (2 + 2) ÷ √2 ≈ 2.83, (−2 − 2) ÷ √2 ≈ −2.83, (1 − 1) ÷ √2 = 0, (−1 + 1) ÷ √2 = 0. The four numbers are 2.83, −2.83, 0, 0. Their variance is (8 + 8 + 0 + 0) ÷ 4 = 4 = λ₁.
  8. What was lost. The coordinates along v₂ are 0, 0, −1.41, 1.41. The mean of their squares is (0 + 0 + 2 + 2) ÷ 4 = 1 = λ₂. And 4 + 1 = 5, the same as the starting total spread 2.5 + 2.5. After squeezing, (2, 0) and (0, 2) both become 0, so you can no longer tell them apart. That difference is exactly the information that was lost.

Try this. Press "Hand example (4 points)". These four points appear and the line is at 0°. What stays is 2.5 and what is lost is 2.5, half and half. The readout shows the covariance matrix 2.5, 1.5, 1.5, 2.5, the eigenvalues 4 and 1, and the shares 80% and 20%. Press "Show answer" and the line turns to 45°, the bars become 4 and 1, and the strip below shows dots at −2.83, 0 (two dots on top of each other) and 2.83.

6. Most spread out = least lost

Look at one point. The segment from the mean to the point is the long side of a right triangle. The other two sides are the shadow's position along the line and the drop to the line. The Pythagorean theorem says:

(distance from mean to point)² = (shadow position)² + (drop length)²

Average this over all the points and you get:

total spread = what stays + what is lost, that is, sxx + syy = (variance along u) + (mean of squared drop lengths)

The total spread on the left depends only on the points. Turning the line does not change it. So whatever the spread gains, the loss gives up. "Find the direction with the most spread" and "find the line that fits the points most closely" are the same problem. Karl Pearson's 1901 paper described this method as finding "lines and planes of closest fit to systems of points", and Harold Hotelling's 1933 paper described it as finding the directions with the most variance (see Sources).

It is not the least squares line. Least squares measures the vertical gap from each point to the line. PCA measures the right-angle distance. Least squares treats y as "the value to predict", while PCA treats x and y the same way. In the starting data, the least squares slope is sxy ÷ sxx = 1.87 ÷ 3.03 ≈ 0.62, which is 31.6°, while principal component 1 is at 36°.

7. How many to keep: explained share

Each eigenvalue is the variance along its principal component, and all the eigenvalues add up to the total spread. So the share of one component is:

share explained by component k = λₖ ÷ (λ₁ + λ₂ + ... + λ_d)

Say data with 5 numbers per point has eigenvalues 6, 2, 1, 0.6 and 0.4 (made-up numbers). They add up to 10.

ComponentEigenvalueShareRunning total
1660%60%
2220%80%
3110%90%
40.66%96%
50.44%100%

Keep three and you go from 5 numbers to 3 while keeping 90% of the spread. There is no fixed rule for how many to keep. Common choices:

In the lab's starting data, principal component 1 explains 90.5%. Squeeze it onto one line and 90.5% of the spread stays. But the share measures "spread", not "usefulness" (section 10).

8. Different units? Standardize first

PCA looks at variance, and variance depends on units. Height in meters is around 1.6 to 1.9, but in centimeters it is 160 to 190. When the numbers get 100 times bigger, the variance gets 100² = 10,000 times bigger. Same people, but just changing the unit pulls principal component 1 almost entirely toward "height". Not because height spreads more, but because its numbers are bigger.

So when numbers with different units are mixed (height and weight, money and counts), first standardize each one:

z = (x − mean) ÷ standard deviation

Now every number has variance 1 and the units are gone. The covariance matrix of standardized data is called the correlation matrix. On the other hand, when all the numbers share one unit and their size differences mean something (like pixel brightness in photos), leave them as they are.

scikit-learn's PCA subtracts the mean but does not rescale (its documentation says the input is "centered but not scaled"). If you need standardizing, do it yourself first.

9. Properties worth knowing

PropertyWhat it meansIn the lab
Principal components are at right anglesThe covariance matrix is symmetric, so its eigenvectors are at right angles. The new coordinates therefore have zero covariance with each other. No information is shared between themThe two purple arrows
Eigenvalue = variance in that directionλ₁ is at least the variance in any direction, and λ₂ is at most the variance in any directionAfter "Show answer", what stays is 4.39 = λ₁
Sum of eigenvalues = total spreadλ₁ + λ₂ = sxx + syy (the sum of the diagonal). Turning the axes does not change the totalThe two bars add up to 4.85
The sign of a direction is not fixedv and −v are the same line. Programs may flip the sign, and the answer is still the sameDrag the line handle to the other side: same line
Sensitive to the mean, units and far-off pointsSubtract the mean first, standardize if the units differ. It uses squares, so one far-off point can pull itSections 8 and 10, Try this

10. What PCA cannot do

Points around a circle. One number, "which point along the circle", tells them all apart. But whichever line you drop the shadows onto, a top point and a bottom point land on the same spot (the black dot).

To unroll curved shapes, people use other methods: kernel PCA, autoencoders (neural networks), t-SNE and UMAP. t-SNE and UMAP place the points on a 2D map again so that nearby points stay neighbors. That lets them unroll curves, but their axes have no meaning, and you should not trust the distances between groups or the sizes of groups as they appear. PCA has axes and shares that mean something, always gives the same answer, and is fast.

Try this. ① With the starting data, choose point 4, (0, 0.2), and type (−4, 4) into the number boxes. You moved just one point, yet principal component 1 turns from 36° to 26.1°, the eigenvalues become 4.58 and 1.89, and the share of principal component 1 drops from 90.5% to 70.8%. ② Press "Remove a point" until only two points are left. Two points always lie on one line. Press "Show answer": what is lost becomes 0 and principal component 1 explains 100%.

11. How it connects to other topics

# The hand example in Python (numpy): principal components with SVD
import numpy as np
X = np.array([[3, 3], [-1, -1], [2, 0], [0, 2]], dtype=float)
Xc = X - X.mean(axis=0)                 # subtract the mean: (2,2), (-2,-2), (1,-1), (-1,1)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
print(Vt[0])                            # component 1: [-0.71 -0.71]. Only the sign is flipped, same line
print(S**2 / len(X))                    # eigenvalues (divided by n): [4. 1.]
print(Xc @ Vt[0])                       # squeezed onto one line: -2.83, 2.83, 0, 0

Where is it used?

Common questions

What is principal component analysis (PCA)?

It finds the directions in which data is most spread out, one after another, and uses them as new axes. Keep only the coordinates along the first few directions and you cut down the number of values (the dimension) while losing as little information as possible. Those directions are the eigenvectors of the covariance matrix.

How many principal components should I keep?

There is no fixed answer. Add up the share each component explains, starting from the largest, and stop where the total is big enough (often around 90%), or stop where the shares suddenly drop. To draw a picture, keep 2.

Why subtract the mean first?

Principal components look at which way the data spreads out from its mean. If you skip this step, the first direction gets pulled from the origin toward the data cloud, so it measures where the data sits instead of how it spreads.

Is the principal component line the same as the least squares line?

No. Least squares makes the squared vertical gaps (the errors in y) small. PCA makes the squared right-angle distances to the line small. Least squares treats y as the value to predict, while PCA treats x and y the same way. With this page's starting data, the least squares line is at 31.6° and principal component 1 is at 36°.

Do you divide the covariance by n or by n − 1?

This page divides by n (the number of points). numpy.cov and scikit-learn's PCA divide by n − 1. That only scales every eigenvalue by the same factor, so the principal directions and the explained shares stay the same.

Words

Word used hereWord used in textbooks
new axes, picked from the most spread out direction downprincipal components (PC)
the method that finds themprincipal component analysis (PCA)
how many numbers each point hasdimension
cutting down the number of valuesdimensionality reduction
spread (average squared distance from the mean)variance
square root of the variancestandard deviation
growing together or moving oppositecovariance
the table of variances and covariancescovariance matrix
shadow, the point reached at a right angleorthogonal projection. Its position number is the principal component score
what is lost (squared drop lengths)reconstruction error
share explainedexplained variance ratio
subtracting the meancentering
removing units with (x − mean) ÷ standard deviationstandardization, z-score
covariance matrix of standardized datacorrelation matrix
sum of the diagonaltrace
curved shapenonlinear structure, manifold
eigenfaceeigenface

Sources

← Normalization and standardizationLinear discriminant analysis (LDA) →