Machine learning algorithms › Unsupervised learning
What is PCA? A plain guide to principal component analysis
What PCA (principal component analysis) is, how it sums up many tangled features with a few new axes, why scaling matters, and how many components to keep.
If you’ve followed a data analysis tutorial, or seen a paper with a scatter plot whose axes read PC1 and PC2, you’ve already met PCA. In a 2010 review, Hervé Abdi and Lynne Williams call it probably the most popular multivariate statistical technique, used in almost every scientific discipline (Principal component analysis). Perhaps it also keeps coming up because tables with dozens or hundreds of columns are no longer unusual.
PCA, short for principal component analysis, is a dimensionality reduction method that takes many features that move together and replaces them with new axes, called principal components, so that a few of them can summarize the data. The axes are found one at a time, starting with the direction in which the data spreads out the most, and a dimension here simply means one feature, one column of the table. The scikit-learn PCA user guide likewise describes it as breaking data into successive components that explain as much of the variance as possible. And since PCA never looks at labels, the answers a model would try to predict, it belongs to unsupervised learning.
Why fewer dimensions help
People can only see two or three axes at a time, so a table with thirteen features can’t be drawn as it is, while two principal components fit on one plot. Directions in which the data barely spreads also tend to carry little more than noise, so dropping them can leave a cleaner signal. And fewer columns mean less memory and faster training for whatever model comes next. scikit-learn’s page on t-SNE, another dimensionality reduction method, makes the last two points as well. When there are very many features, it recommends first reducing them to something like 50 with a method such as PCA, which suppresses some noise and speeds up the distance calculations. Behind all of this sits what’s often called the curse of dimensionality, where data grows sparse as features are added and distances between points tell you less and less.
Principal components and explained variance
Picture shining a flashlight on a cloud of points. As you turn the light, there’s an angle at which the shadow on the wall stretches out the widest, and that direction is the first principal component. In practice, PCA first subtracts each feature’s mean to move the center of the data to zero. Then it finds the direction with the largest variance, the average squared distance from the mean. The second component is the direction with the most remaining spread among those at right angles to the first, and so on, up to as many components as there are features. Because the axes meet at right angles, the new columns are uncorrelated with each other.
Each component is a weighted sum of the original features, something like “PC1 = weight 1 × alcohol + … + weight 13 × proline,” and finding those weights is PCA’s whole job. The explained variance ratio is the share of the total spread that one component captures. So if you keep every component, the ratios add up to exactly 1.
An idea from 1901
In 1901 Karl Pearson published On lines and planes of closest fit to systems of points in space, looking for the line or plane that best fits points scattered in two or more dimensions. His test was the smallest sum of squared perpendicular distances from the points to the line, whereas regression measures distance only along the variable it predicts. The line found this way is also the direction of greatest spread, the widest shadow above. In 1933 Harold Hotelling published “Analysis of a complex of statistical variables into principal components.” The Abdi and Williams review credits him with formalizing the modern method and coining the term principal component. Of course, it also notes that some trace the mathematics back to Cauchy and Jordan in the 1800s.
scikit-learn describes its PCA as using the singular value decomposition (SVD) of the centered data (PCA API). When I checked version 1.9.1, though, the default svd_solver='auto' chose an eigendecomposition of the covariance matrix for data with far more rows than columns, like the examples below, and as the page explains, either route gives the same axes.
Wine data, with and without scaling
The wine dataset in scikit-learn holds 178 wines grown in the same region of Italy by three different cultivators, each described by 13 numbers from a chemical analysis. The code below prints the narrowest and the widest feature ranges, then runs PCA twice, once on the original numbers and once after StandardScaler has rescaled every feature to a mean of 0 and a standard deviation of 1.
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X = load_wine(as_frame=True).data # 178 wines, 13 features
print((X.max() - X.min()).sort_values().iloc[[0, -1]].round(2).to_string())
X_scaled = StandardScaler().fit_transform(X) # each feature: mean 0, std 1
for name, data in [("raw", X), ("scaled", X_scaled)]:
pca = PCA().fit(data)
w = pd.Series(pca.components_[0], index=X.columns) # weights that make up PC1
print(f"{name:<6} PC1 ratio {pca.explained_variance_ratio_[0]:.3f}, "
f"weights over 0.1: {(w.abs() > 0.1).sum()}, top: {w.abs().idxmax()}")
nonflavanoid_phenols 0.53
proline 1402.00
raw PC1 ratio 0.998, weights over 0.1: 1, top: proline
scaled PC1 ratio 0.362, weights over 0.1: 11, top: flavanoids
Proline spans 1,402 while nonflavanoid phenols span 0.53. Without scaling, the first component explains 99.8% of the variance and proline’s is the only weight above 0.1, so PCA simply rediscovered the proline column. That’s because, as the API page says, scikit-learn’s PCA centers each feature but doesn’t scale it, and variance grows with the square of the units. After standardizing, the first component explains 36.2%, and 11 of the 13 weights are above 0.1. scikit-learn’s Importance of Feature Scaling example shows the same effect on this dataset. That’s why, as the Abdi and Williams review says, standardizing first is the usual choice when features come in different units.
How many components to keep
Next, let’s add up the ratios from the standardized run and see how many components it takes to reach a target.
import numpy as np
pca = PCA().fit(X_scaled)
print(" ".join(f"{v:.3f}" for v in np.cumsum(pca.explained_variance_ratio_)))
for target in (0.90, 0.95):
n = PCA(n_components=target).fit(X_scaled).n_components_ # a fraction picks the count
print(f"{target:.0%} of the variance needs {n} components")
0.362 0.554 0.665 0.736 0.802 0.851 0.893 0.920 0.942 0.962 0.979 0.992 1.000
90% of the variance needs 8 components
95% of the variance needs 10 components
Two components keep 55.4% of the variance, and reaching 90% takes 8 of the 13. When you pass a fraction between 0 and 1 as n_components, scikit-learn picks the smallest number of components whose cumulative ratio goes past it. The API page describes this option together with svd_solver='full', but I confirmed that in 1.9.1 it works the same with the default 'auto'. Of course, 90% and 95% are only rules of thumb. For a plot you’d keep two or three, and when PCA feeds a model, it’s better to try a few counts and compare how the model does on data it hasn’t seen.
Compressing and restoring handwritten digits
Since each component is a weighted sum, you can also turn component scores back into the original features with inverse_transform. Whatever was in the dropped components can’t come back, so the result is an approximation, and its distance from the original is the reconstruction error. The digits dataset holds 1,797 handwritten digits as 8×8 images with pixel values from 0 to 16. All 64 features are pixels on the same scale, so this time I didn’t standardize.
from sklearn.datasets import load_digits
digits = load_digits().data # 1,797 images of 8x8 pixels, each 0 to 16
n90 = PCA(n_components=0.90).fit(digits).n_components_
print(f"{digits.shape[1]} pixels, {n90} components keep 90% of the variance")
for k in (2, 10, n90, 40):
pca = PCA(n_components=k).fit(digits)
restored = pca.inverse_transform(pca.transform(digits)) # back to 64 pixels
error = np.mean((digits - restored) ** 2) # reconstruction error
print(f"{k:>2} components kept {pca.explained_variance_ratio_.sum():.3f} error {error:.3f}")
64 pixels, 21 components keep 90% of the variance
2 components kept 0.285 error 13.421
10 components kept 0.738 error 4.914
21 components kept 0.903 error 1.817
40 components kept 0.988 error 0.221
Here 21 of the 64 components keep 90% of the variance. The error is the mean squared difference per pixel, 1.817 with 21 components and 0.221 with 40. Two components keep only 28.5%, which is enough for a rough plot but far from enough to redraw the images. It’s the same idea as lossy compression, where you store fewer numbers and accept some error in return.
How it differs from feature selection, t-SNE, and UMAP
Feature selection also cuts down the columns, but it keeps some of the original features and drops the rest, so the ones that survive keep their meaning (feature selection). PCA instead builds new columns that mix every feature, like the 11 sizable weights in the wine example. That’s why it can often pack more information into fewer columns, while explaining what a PC1 score of 2 means gets harder. And to compute that score, you still have to measure all thirteen features.
PCA’s axes are straight lines, so it can’t unroll data that lies along a curve, which is the job of nonlinear methods. scikit-learn’s Kernel PCA extends PCA to nonlinear reduction with the help of kernels. t-SNE, introduced in the 2008 paper Visualizing Data using t-SNE, is mostly used to draw high-dimensional data in two or three dimensions. UMAP is often used for plots too, and its docs say it also works for general nonlinear dimension reduction. Unlike PCA, though, neither builds its axes as weighted sums of the original features.
When it fits and when it doesn’t
PCA fits best when many features are strongly tangled, meaning several columns largely measure the same underlying thing. Neighboring pixels in an image and chemical measurements that rise and fall together are typical, and then a few components hold most of the spread, as they did with the digits. It’s also a handy preprocessing step, whether for a first look at a new table, before clustering or t-SNE, or to shrink the input of a model.
It fits less well in three situations. Curved structure only gets flattened by straight axes. When results have to be explained one feature at a time, components that mix everything get in the way. The third is easy to miss, because large variance doesn’t always mean important. In a classification problem, the direction that separates the classes may have only a small spread, and PCA, which never looks at labels, may throw it away along with the noise. So I’d suggest first comparing how a model does with and without PCA.
Trying it yourself
If you’d like to try it, install scikit-learn with pip install -U scikit-learn, run the three code blocks above in order, and then change one thing at a time. When I left out the StandardScaler step and asked for 90%, PCA kept a single component, the proline axis. If PCA comes before a model, it’s a good idea to chain StandardScaler, PCA, and the model with make_pipeline. A pipeline keeps statistics from the test data from leaking into the earlier steps during cross-validation. I ran these examples on November 2, 2026, with Python 3.13.12, scikit-learn 1.9.1, NumPy 2.5.4, and pandas 3.1.0.
AI tools helped with the research for this post.