Sub topic 13
Dimensionality reduction: summarizing many features with fewer
This chapter assumes you can read basic NumPy and scikit-learn code, know what a feature matrix is (rows are examples, columns are features), and understand mean and variance. You should also know the difference between supervised and unsupervised learning from earlier chapters.
What dimensionality reduction does
Dimensionality reduction is an unsupervised technique that turns a dataset with many features into one with fewer features while keeping as much useful information as possible. The number of features is the dataset's dimensionality. A table with 4 columns has 4 dimensions. A table of 28×28 pixel images has 784.
People reduce dimensions for four main reasons:
- Visualization. You can plot 2 or 3 dimensions, but not 50.
- Compression. Fewer columns means less memory and faster training.
- Noise removal. Small, noisy directions in the data can be discarded.
- Redundancy. Many features are correlated, such as petal length and petal width. A smaller set can carry nearly the same signal.
No labels are used. The method looks only at the feature matrix X, so it belongs with clustering under unsupervised learning.
Feature selection versus feature extraction
There are two ways to get fewer features, and they behave differently.
| Approach | What it does | Output features | Example |
|---|---|---|---|
| Feature selection | Keeps a subset of the original columns | Original, still interpretable | Drop columns with near-zero variance |
| Feature extraction | Builds new columns from combinations of the originals | New, often hard to interpret | PCA |
Dimensionality reduction usually means extraction. After PCA, "component 1" is a weighted blend of all the original features, not a measurement you can point to.
Principal component analysis
Principal component analysis (PCA) is the most common method. It finds new axes, called principal components, that point in the directions where the data varies most.
Here is the working model:
- Center the data by subtracting each feature's mean.
- Find the direction along which the centered data has the largest variance. This is component 1.
- Find the direction with the largest remaining variance that is perpendicular (orthogonal) to the first. This is component 2.
- Repeat until you have as many components as features.
- Keep the first
kcomponents and project each example onto them.
Each component is a vector of weights over the original features. Projecting an example means taking the dot product of its centered feature vector with each kept component. The result is k numbers per example, called the scores.
Internally, scikit-learn computes this with a singular value decomposition (SVD) of the centered data. The components are the right singular vectors. The variance each component captures follows from the singular values.
Running PCA on iris
The iris dataset has 4 features. This example compresses them to 2 and reports how much variance each component keeps.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
X, _ = load_iris(return_X_y=True)
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X)
print(X_2d.shape)
print(pca.explained_variance_ratio_)The shape is (150, 2): the same 150 examples, now with 2 columns. The explained_variance_ratio_ attribute is the fraction of total variance each component captures. On raw iris, the first component holds roughly 92% and the second roughly 5%, so two numbers preserve about 97% of the variance in four.
Notice that the labels were thrown away with _. PCA never saw the species. If you plot X_2d colored by species, the classes usually separate well. That is a useful sanity check, but it is a side effect of the species differing in the high-variance directions. PCA does not optimize for class separation.
Scale your features first
PCA chases variance, and variance depends on units. A feature measured in thousands will dominate one measured in fractions, simply because its numbers are bigger. Standardizing each column to mean 0 and standard deviation 1 puts features on equal footing.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)
pca = PCA().fit(X_scaled)
ratios = pca.explained_variance_ratio_
print(np.round(ratios, 3))
print(np.round(np.cumsum(ratios), 3))After scaling, the first component drops to roughly 73% and the second rises to roughly 23%. Together they keep about 96%. Which version is right depends on whether the original units carry meaning. When features have mixed units, standardize.
Choosing how many components
You have three practical rules.
- Fixed target. Use
n_components=2or3when the goal is a plot. - Variance threshold. Pass a float between 0 and 1, such as
PCA(n_components=0.95). scikit-learn keeps the smallest number of components whose cumulative explained variance reaches 95%. - Downstream performance. Treat
n_componentsas a hyperparameter and pick the value that gives the best validation score for the supervised model that follows.
The cumulative curve from the previous example is the basis for the first two rules. A sharp bend, where extra components add little, suggests a natural cutoff. The threshold of 95% is a convention, not a law.
Using PCA inside a supervised pipeline
PCA is often a preprocessing step. Putting it in a Pipeline guarantees that each fit step sees only the training portion, including inside cross-validation.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
clf = make_pipeline(
StandardScaler(),
PCA(n_components=2),
LogisticRegression(max_iter=200),
)
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))Compare this score with the full four-feature logistic regression from the classification chapter. On a dataset this small, the two are usually close. Reduction pays off more on wide datasets with hundreds of correlated columns.
Reconstruction error
You can map reduced data back to the original space with inverse_transform. The result is an approximation, and the gap measures what the reduction lost.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
X, _ = load_iris(return_X_y=True)
pca = PCA(n_components=2).fit(X)
X_back = pca.inverse_transform(pca.transform(X))
error = np.mean((X - X_back) ** 2)
print(error)A small mean squared error means the two kept components describe the data well. With all 4 components, the error is essentially zero, apart from floating-point noise. PCA is the linear projection that minimizes this reconstruction error for a given k.
Gotchas and failure modes
- High variance is not the same as high importance. A feature that varies a lot may be irrelevant to your prediction, while a low-variance direction may separate your classes. PCA is blind to labels.
- PCA is linear. It cannot unroll data that lies on a curved surface, such as a spiral. Nonlinear methods like t-SNE and UMAP handle that, but they come with their own costs.
- Components are hard to interpret. Inspect
pca.components_to see the weights, but expect blends rather than clean meanings. - Component signs are arbitrary. Flipping a component's sign gives an equivalent solution. Do not compare signs across runs or datasets.
- Outliers pull components. Because PCA maximizes squared deviations, a few extreme points can tilt the axes. Check for outliers first.
- t-SNE and UMAP plots are for looking, not measuring. Distances between clusters and cluster sizes in those plots are not reliable, and they do not give you a reusable transform in the same simple way.
Decision criteria
Use PCA when features are numeric, roughly linearly related, and you want a fast, deterministic, reusable transform. Prefer plain feature selection when you must keep original, explainable columns. Consider nonlinear methods when your goal is a visual map of complex structure and you accept that the picture is not a quantitative result.
Exercise
You fit PCA(n_components=0.95) on standardized training data and get 12 components out of 40 original features. A colleague says the 12 components are "the 12 most important original features." Is that correct? What would you tell them?
Show answer
No. Each component is a weighted combination of all 40 original features, not a subset of them. The components are ordered by the variance they capture, not by how useful each feature is for prediction. If you need an actual subset of original columns, use feature selection instead.
Exercise
A pipeline calls StandardScaler().fit_transform(X) and PCA(n_components=2).fit_transform(...) on the full dataset, and only afterwards splits into train and test sets. What is wrong, and how do you fix it?
Show answer
The scaler and PCA have learned means and components using the test examples, which leaks test information into training and can make scores look better than they should. Split first, then fit the scaler and PCA on the training set only, and apply transform to the test set. A Pipeline does this automatically.