A photo of a handwritten digit in a small data set has 64 numbers, one per pixel. You cannot draw 64 axes, but you can draw 2. How many numbers do we have to keep before the digit is still recognizable? The answer is far fewer than 64, because neighbouring pixels move together: when one pixel is dark, the next one probably is too. Data with many features often really vary along only a few directions, and principal component analysis (PCA) finds them. This lesson ties together five ideas from Part 1, the covariance matrix (P1.D7), eigenvectors (P1.B12), the singular value decomposition (P1.B13), projections (P1.B11) and constrained optimization (P1.F7), and shows that they all describe one method.
Why reduce the dimension?
There are four common reasons.
- Seeing. A person can look at 2 or 3 numbers per example, not 64. The first two components give a flat picture of the data.
- Compressing. Storing 20 numbers per example instead of 64 saves space, and the loss is known in advance.
- Removing noise. Directions along which the data barely vary are often noise. Dropping them can clean the data.
- Speeding up. Models with fewer inputs train faster, and distance-based methods behave better when the distances are measured in fewer, more meaningful directions (P3.B1). This helps only if the data lie near a lower-dimensional subspace. Noise columns are not fixed by PCA: they add variance, and PCA may keep them.
Something is always lost. The question PCA answers is: which directions to keep so that the least is lost? It measures “lost” as squared distance, as we will see.
The picture: rotate a line
The widget shows 20 made-up points, already centred so that their average is the origin. A line passes through the origin. Each point is projected onto the line (the blue dot is the closest point on the line) and the red segment is the perpendicular distance from the point to the line. The bar splits the total variance into two parts: the variance of the blue dots (blue) and the sum of the squared red lengths divided by (red). Both use as the divisor, so they add up to the total variance, which does not depend on the angle.
Things to try:
- Rotate the line on the elongated cloud and watch the two numbers trade off. The blue part is largest, , near (the long axis of the cloud) and smallest, , at the perpendicular angle, . The red part does the opposite. “Snap to PC1” jumps to the best angle. The line at the best angle is the first principal component (PC1); the line at to it is PC2.
- Round cloud. The two spreads are almost equal ( and ), so every angle keeps almost the same variance, and the best direction means little. A few more points could turn PC1 to a very different angle. PCA has little to offer when the data spread evenly in all directions.
- Unequal units. The points are heights in cm and weights in kg. Without standardizing, PC1 sits at because kilograms vary more than centimetres. Tick “Standardize first”: PC1 moves to . Which of the two is right depends on whether the units are arbitrary. The last section before the code explains the choice.
- Keyboard. Tab to the round handle and press the arrow keys ( steps, Shift for ).
Centring and the covariance matrix
PCA first centres the data: subtract each column’s mean, so that every column has mean and the cloud is centred on the origin. In NumPy, X - X.mean(axis=0) does it by broadcasting, shapes and (P1.B14). Without it, the line through the origin would chase the mean of the data instead of the spread.
Here is the small example of P1.B12 and P1.B13 in raw form (the data are made up). Four people with two measurements each: , , , . After subtracting the means and we get exactly the centred points those lessons used:
The sample covariance matrix of centred data is (P1.D7). Here , so we divide by :
Each variance is and the covariance is : the two features rise together. The total variance is the sum of the diagonal, (the trace). Some books divide by ; every number below would change by the same factor. scikit-learn divides by , and so does this lesson.
For a unit vector (length ), the variance of the projections of the data onto the line along is
Why: the projection of the centred point is the number (P1.B11), these numbers have mean , and their mean square is .
Three ways to the same direction
Way 1: maximize over unit vectors (P1.F7). With and above, . This is at , at , at and again at . The largest value is , at , and the smallest is , at . The widget’s curve is this kind of function. The general problem is “maximize with ”, the constrained problem of P1.F7; the Go-deeper box below shows that its solutions are eigenvectors of .
Way 2: the top eigenvector of (P1.B12). The eigenvalues of are and , with eigenvectors along and . The eigenvalue is the variance: along , the direction, the variance is ; along the perpendicular direction it is . The eigenvalues add up to , the trace and the total variance. PCA is exactly this eigen-decomposition of the covariance matrix of the centred data: the eigenvectors, sorted by eigenvalue, are the principal components.
Way 3: the SVD of the centred data (P1.B13). Write with singular values . (P1.B13 writes the singular-value matrix as ; this lesson keeps for the covariance, so the singular-value matrix is .) Then . So the right singular vectors (the columns of ) are the principal directions, and the variance along is
For the four points, the singular values are and , so and . The same numbers, the same directions. The SVD works on directly and never forms , which squares the condition number (P1.B11), so it is what software uses. The coordinates of the data along the directions are the columns of .
Orthogonal, uncorrelated, and the later components
The second principal component is the direction of largest variance among the directions perpendicular to the first, the third among those perpendicular to both, and so on. Because is symmetric, the spectral theorem (P1.B10, P1.B12) says its eigenvectors can be chosen perpendicular: the components form an orthonormal set. In the example PC1 and PC2 . (Their signs are arbitrary: the negatives of these vectors are just as valid, and different programs will print either.)
The coordinates along the components, called scores, are uncorrelated: their covariance matrix is , as in the example of P1.D7. The score of the first person on PC1 is and on PC2 is . Rotating onto the eigenvectors turns correlated features into uncorrelated ones. The two scores can still depend on each other in other ways: uncorrelated is not independent.
The picture of P1.D7 helps: the data of a Gaussian-looking cloud fill an ellipse. Its axes are the principal components, and the semi-axis lengths are proportional to (here and ).
Explained variance, scree plots and choosing k
The explained variance ratio of component is its share of the total variance: . In the example, and . A scree plot draws the eigenvalues, or their ratios, in decreasing order; a cumulative version adds them up. How many components should we keep? There is no single rule. Common choices:
- Keep enough components to reach a target share of the variance, often to . This is a convention, not a theorem, and the right level depends on the task.
- Look for an “elbow” in the scree plot, where the eigenvalues stop falling steeply. It is a judgement, and some data have no clear elbow.
- Treat as a hyperparameter and pick it by the score of the model that uses the components, measured on validation data (P3.A4).
Eigenvalues also tell the rank (P1.B7). Four centred points in 3-D that lie exactly in the plane , for example , , , , have rank , and the covariance eigenvalues are , and : two directions describe everything. Real data are noisy, so the last eigenvalue is small but not . What PCA reports is an effective dimension: how many directions carry most of the variation.
Projecting and reconstructing
Keep the first components as the columns of a matrix with orthonormal columns. The scores of a centred example are , and the point of the -dimensional subspace closest to it is , the projection of P1.B11. For the whole data matrix, the codes are and the reconstruction is . To get back to the original units, add the mean again.
With in the example, the four points are rebuilt as , , and . Their squared errors are , , and : the total is , and divided by it is . That is the discarded eigenvalue, . This holds in general:
The error is the sum of the discarded eigenvalues, and the share of variance kept is minus the error over the total. Keeping the top directions is the best rank- approximation of the data matrix (the Eckart–Young theorem of P1.B13): no other -dimensional subspace leaves less squared error.
The line of least perpendicular distance
There is a second way to say what the first component is. For each centred point, Pythagoras gives , where is the perpendicular distance to the line. The left side does not depend on the line. So the sum of squared projections plus the sum of squared perpendicular distances is a constant: here , which is times the total variance. Maximizing the first sum is the same as minimizing the second. PCA’s line is the line of least squared perpendicular distance, and also the line of greatest projected variance. This is the bar of the widget: its two colours always add up to the same total.
This is not the regression line of P3.A2. Linear regression minimizes vertical distances, the errors in predicting . For the four points, the regression of on has slope and a vertical squared error of . Regressing on gives a line with slope in the plane. The PC1 line has slope , between them, and its perpendicular squared error is , lower than the that the regression line has when measured the same way. The PC1 line is also called total least squares. Unlike the regression line, it changes if you rescale one of the features, which brings us to the next topic.
Standardizing: when the units decide
PCA looks for the largest variance, and the size of a variance depends on the unit. Measure the second feature of the four-point example in units that are times smaller (grams instead of kilograms, say). The covariance matrix becomes , the eigenvalues are and , and PC1 is almost exactly the second axis, , with of the variance. Nothing about the people changed, only a unit. The widget’s unequal-units preset shows the same effect.
The remedy is to standardize each column first (subtract the mean, divide by the standard deviation, P3.A11), then run PCA. The covariance matrix of standardized data is the correlation matrix, so this is also called correlation PCA. For the example the correlation is and the matrix is , with eigenvalues and : shares of and , whatever the units. With two features the first component of standardized data is always at (or for a negative correlation), unless the correlation is exactly , when every direction ties. A correlation near makes that direction very unstable. Only the shares, over , carry information. The total variance of standardized data is , the number of features.
When to standardize? If the features have different units or arbitrary scales, standardize. If they share a natural unit whose differences in size are meaningful, such as the pixels of an image, centring alone is usual. This is a choice, and the two give different components; neither is wrong, they answer different questions.
PCA in practice, with real output
The code below uses scikit-learn, which the in-browser runner does not have, so it is shown as a static block with real output from a local run (scikit-learn 1.8). The two data sets, iris (150 flowers, 4 measurements in cm) and digits (1797 images of pixels), come bundled with scikit-learn; no data are copied into this site.
import numpy as np
from sklearn.datasets import load_iris, load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, _ = load_iris(return_X_y=True)
print("iris raw", PCA().fit(X).explained_variance_ratio_.round(4))
Xs = StandardScaler().fit_transform(X)
print("iris std", PCA().fit(Xs).explained_variance_ratio_.round(4))
d, y = load_digits(return_X_y=True)
pca = PCA().fit(d)
cum = pca.explained_variance_ratio_.cumsum()
print("digits, first two:", pca.explained_variance_ratio_[:2].round(4))
for t in (0.90, 0.95, 0.99):
print(f" components for {t:.0%}:", int(np.searchsorted(cum, t) + 1))
p2 = PCA(n_components=2).fit(d)
err = ((d - p2.inverse_transform(p2.transform(d))) ** 2).sum() / (len(d) - 1)
print("k=2 error/(N-1):", err.round(2))
print("discarded eigenvalues:", pca.explained_variance_[2:].sum().round(2))
Xtr, Xte, ytr, yte = train_test_split(d, y, test_size=0.25, random_state=0, stratify=y)
full = LogisticRegression(max_iter=5000).fit(Xtr, ytr)
model = make_pipeline(PCA(n_components=0.95),
LogisticRegression(max_iter=5000)).fit(Xtr, ytr)
print("64 pixels, test accuracy:", round(full.score(Xte, yte), 4))
print("PCA components kept:", model[0].n_components_)
print("PCA test accuracy:", round(model.score(Xte, yte), 4))
iris raw [0.9246 0.0531 0.0171 0.0052]
iris std [0.7296 0.2285 0.0367 0.0052]
digits, first two: [0.1489 0.1362]
components for 90%: 21
components for 95%: 29
components for 99%: 41
k=2 error/(N-1): 859.42
discarded eigenvalues: 859.42
64 pixels, test accuracy: 0.96
PCA components kept: 28
PCA test accuracy: 0.9556
What the output shows:
- Iris. The raw features are all in cm, but their spreads differ (standard deviations from to ). The first component takes of the variance, and most of it is the feature with the largest spread, the petal length. After standardizing, the first takes and the second : the answer depends on whether you standardize.
- Digits. The first two components together hold only of the variance, so a 2-D picture of the digits is a rough view. It takes components for , for and for . So of the components, about a third, hold of the variance.
- Reconstruction. With the error divided by is , exactly the sum of the other eigenvalues, as the formula above says.
- A pipeline. The logistic regression on all pixels scores on the held-out test set. With PCA keeping components (enough for of the training variance) it scores . This is one split of one data set: it shows that far fewer inputs lose little, not that PCA helps accuracy.
Fit on the training data only
PCA learns from data: the means to subtract and the directions to keep. If it is fitted on all rows before a train and test split, the test rows have shaped the features, which is leakage (P3.A11, P3.A4). Fit on the training rows only, and apply the training mean and directions to validation and test rows: reduce(rows) = (rows - train_mean) @ W. In scikit-learn, put PCA in a pipeline, as above, and the pipeline does this each time it is fitted.
Limits
- Only straight directions. PCA is linear. Data on a curve, such as a spiral or a ring, may need many components to describe, though a single number (the position along the curve) would do. Nonlinear maps are the subject of P3.C4 (t-SNE and UMAP), and autoencoders are neural networks that learn a curved code (P8.2).
- Outliers. Variance is a sum of squares, so far-away points have a big say. Add one more person at , which is after subtracting the old mean . Centre all five points on their new mean and the covariance eigenvalues become and with PC1 at , turned by from the of before. Look for outliers before PCA.
- Interpretation. Each component is a mixture of all the original features. A component may have no tidy meaning, and its signs are arbitrary.
- Variance is not relevance. PCA never sees a label. The direction with the least variance can be the one that separates two classes. Whether to keep a component is a question for the task, which is why the number of components can be chosen on validation data.
- It needs numbers that make sense to add. Categories encoded as integers, or columns with wildly different meanings, give components with no meaning.
Depth: three ways to see it
Intuition
Think of the shadow of a cloud of points on a wall. Turn the wall and the shadow changes: from a bad angle the points pile on top of each other and the shadow is short, from a good angle the shadow is long and the points stay spread out. PCA picks the wall angle with the longest, most spread-out shadow, then the next best angle at right angles, and so on. The analogy breaks because a real shadow is of a 3-D object on a 2-D wall, while PCA also works with 64 features and any number of kept directions, and because the shadow only shows straight projections.
Math
For centred , with . The component , and maximizes the same quantity among unit vectors perpendicular to . Explained variance ratio . Scores , with covariance . Reconstruction from components: , with . From the SVD ( holds the singular values, called in P1.B13): and .
Code
import numpy as np
def pca_fit(X, k):
mean = X.mean(axis=0)
U, S, Vt = np.linalg.svd(X - mean, full_matrices=False)
eig = S**2 / (len(X) - 1) # variance along each component
return mean, Vt[:k].T, eig # mean, (d, k) directions, all eigenvalues
def pca_transform(X, mean, W):
return (X - mean) @ W # always the TRAIN mean and directionsscikit-learn’s PCA does the same and adds transform, inverse_transform and explained_variance_ratio_. It centres the data but does not scale it.
Go deeper Why the top eigenvector maximizes the variance, and why the next one is perpendicular
Maximize subject to . The Lagrangian is , and setting its gradient to zero gives : is an eigenvector and an eigenvalue (P1.F7). At such a point the value is , so the largest value is the largest eigenvalue. For the second component, add the constraint . In the eigenbasis, write with . Then the variance is , a weighted average of the eigenvalues, so it is largest when all the weight sits on the largest eigenvalue allowed. With that is , at .
Go deeper Whitening
Dividing each score by gives scores with variance and covariance : a whitened version of the data. It is sometimes used before algorithms that assume a round cloud. Directions with tiny eigenvalues are mostly noise, and dividing by their small boosts that noise, so whitening is usually combined with dropping them.
Try it in NumPy
In the first cell, the four points go through the three routes: a scan over angles, eigh on the covariance matrix and svd of the centred data. In the second cell, a made-up data set with five features that are mixtures of two hidden factors shows the explained ratios, a fit on the training rows only, and the reconstruction error as the sum of the discarded eigenvalues. np.linalg.eigh is for symmetric matrices and returns the eigenvalues in ascending order, so the code reverses them.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
To see the outlier of the limits section, add the row [16, 14] to raw (the point in centred coordinates, shifted by the old mean ) and watch PC1 turn.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The ratios show two strong directions, which matches the two hidden factors, and the three small ones are noise. The test error is about the same as the training error, because the directions describe the structure and not the particular rows. Notice that the test rows were centred with the training mean.
Common mistakes
Exercises
- A covariance matrix has eigenvalues , and . Give the explained variance ratios, the smallest that reaches , and the error (divided by ) when .
Show answer
The total is , so the ratios are , and . One component gives and two give , so reaches . With the error is the sum of the discarded eigenvalues, . - For , find the variance of the projections onto the unit vector .
Show answer
. This is between the smallest and largest eigenvalues, and , as it must be. - A centred data matrix with rows has singular values and (and no others). Find the two variances and the explained variance ratios.
Show answer
, so and . The ratios are and ; the divisor cancels in a ratio. - Two features have standard deviations and and correlation . Which direction does PCA on the raw covariance follow, and what are the explained ratios of PCA on the standardized data?
Show answer
On the raw data the variances are and , so PC1 follows the second feature almost exactly. On standardized data the correlation matrix has eigenvalues and , so the ratios are and , with PC1 at . - Why must new rows be centred with the training mean, and not with their own mean?
Show answer
The directions were learned for data centred on the training mean. A new row means the same thing only if it is shifted by the same amount. Centring each test set with its own mean would shift every test set differently (a single row would become the zero vector), and using test data to fit anything is leakage. - Centred 3-D data have covariance eigenvalues , and . What is the rank of the data matrix, and what is the reconstruction error with ?
Show answer
The rank is , one eigenvalue being . With the error is the discarded eigenvalue : the reconstruction is exact. - The five points , , , and have mean . After centring them on that mean, the covariance eigenvalues are and . What share of the variance does PC1 explain?
Show answer
, so . The share is high, but PC1 now points along , the outlier’s direction, which says more about one point than about the other four.
Check your understanding
Which unit vector gives the largest variance of the projections of centred data?
The variance along a unit vector is , and its largest value is the largest eigenvalue, reached at its eigenvector. The eigenvector with the smallest eigenvalue gives the smallest variance. The largest single entry and the farthest point depend on single numbers or points, not on the spread of all the data.
A covariance matrix has eigenvalues and . Keeping only the first component, what is the squared reconstruction error divided by ?
The error equals the sum of the discarded eigenvalues, here . The eigenvalue is what is kept. The value is the fraction of the variance that is lost, not the error, and is the total, which would be the error only if nothing were kept.
A data set has columns in kilograms and in grams, and you run PCA on the raw covariance matrix. What happens, and what is the usual fix?
A variance measured in grams is a million times larger than in kilograms, so the grams column decides the direction. Dividing each column by its standard deviation removes the unit. The kilogram column would dominate only if the units were swapped. The columns do not cancel, and the ratios are computed from the same unit-dependent variances.
You want to test a model that uses 10 PCA components as inputs. Which procedure avoids leakage?
The mean and the directions are learned from data, so they must come from the training rows alone, and the test rows are only transformed with them. Fitting on all rows lets the test rows shape the features. Fitting on the test rows, whether separately or alone, uses the test data to build the pipeline.
How does the first principal component line differ from the least-squares regression line of on ?
PC1 measures the error at right angles to the line, which is the same as maximizing the variance of the projections. Regression measures the error in the direction only. The two lines differ unless the data are perfectly aligned. PC1 does not maximize the perpendicular distances; it minimizes them.
Next: P3.C4 draws data with curved, nonlinear maps and explains how to misread them. P3.C5 uses reconstruction error to find anomalies, and P8.2 replaces PCA’s straight directions with a neural network. P3.C1 and P3.C2 group the same kind of unlabelled data without reducing it.