Sub topic 1
Why Reduce Dimensionality
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Python and NumPy, including array shapes and slicing.
- Explain mean, variance and correlation.
- Multiply matrices and describe a basis as a set of directions used to describe points.
- Treat a dataset as a feature matrix, with rows as samples and columns as features.
You do not need to know what an eigenvector is yet. A later chapter covers eigenvectors and eigenvalues in brief.
What dimensionality means
The dimensionality of a dataset is the number of features that describe each sample. A table of 1,000 houses with 12 columns has 1,000 samples and 12 dimensions. A 28 by 28 grayscale image has 784 dimensions, one per pixel. A gene expression profile can have 20,000 dimensions.
Dimensionality reduction maps each sample from its original d features to a smaller number k of new features. The goal is to keep the information that matters for your task and drop the rest. Principal component analysis (PCA) is the standard linear method for this. It builds the k new features as weighted sums of the original ones, and it chooses the weights so that the new features keep as much variance as possible.
In code, the shapes change like this:
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(1000, 12)) # 1000 samples, 12 features
W = rng.normal(size=(12, 3)) # a projection to 3 features
Z = X @ W # 1000 samples, 3 features
print(X.shape, Z.shape)This W is random, so it keeps no particular information. PCA is a way to pick W well. The rest of this chapter explains why you would want to.
Four reasons to reduce dimensions
Four practical motivations come up again and again: noise, redundancy, visualization and computation.
Noise
Real measurements contain signal and noise. If the signal lives in a few directions and the noise is spread across all directions, then projecting onto the high-variance directions keeps most of the signal and only a small share of the noise.
Here is a small experiment. We build data whose true structure has 2 dimensions, embed it in 10 dimensions, and add noise.
import numpy as np
rng = np.random.default_rng(1)
n, d, k = 500, 10, 2
latent = rng.normal(size=(n, k)) * np.array([5.0, 3.0])
embed = rng.normal(size=(k, d))
clean = latent @ embed
noisy = clean + rng.normal(scale=1.0, size=(n, d))
mean = noisy.mean(axis=0)
Xc = noisy - mean
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
top = Vt[:k]
denoised = (Xc @ top.T) @ top + mean
clean_c = clean - clean.mean(axis=0)
print("error before:", np.mean((noisy - clean) ** 2))
print("error after: ", np.mean((denoised - clean) ** 2))The error after projection is lower than the error before, because the discarded directions held mostly noise. The SVD call computes the same principal directions that a later chapter derives from the covariance matrix. For now, treat top as the two best directions.
This only works when the signal really is concentrated. If the noise is larger than the signal in the directions you keep, projection will not help.
Redundancy
Features are often correlated. Height in centimeters and height in inches carry the same information. Several sensors placed next to each other measure nearly the same thing. When two features move together, one of them adds little that the other lacks.
Redundancy causes practical trouble:
- Linear regression becomes unstable when features are nearly collinear, because many different weight vectors fit the data almost equally well. This is called multicollinearity, and it makes coefficients large, noisy and hard to interpret.
- Models spend capacity and training data on repeated information.
- Reported importance gets split arbitrarily across duplicate features.
PCA replaces correlated features with new features that are uncorrelated with each other. The new features are linear combinations of the old ones, so nothing is invented. The same information is re-expressed in a better set of axes.
The sketch below shows two almost identical features and how little the second one adds.
import numpy as np
rng = np.random.default_rng(2)
a = rng.normal(size=500)
b = a + rng.normal(scale=0.1, size=500) # almost a copy of a
X = np.column_stack([a, b])
print("correlation:", np.corrcoef(X, rowvar=False)[0, 1])
Xc = X - X.mean(axis=0)
S = np.linalg.svd(Xc, compute_uv=False)
var = S**2 / (len(X) - 1)
print("variance share per direction:", var / var.sum())You should see a correlation near 0.99 and a first direction that holds about 99 percent of the total variance. Two columns behave like one.
Visualization
People can look at two or three dimensions. A dataset with 50 features cannot be plotted directly. Projecting to 2 dimensions gives a scatter plot where you can look for clusters, outliers and trends.
A 2D picture is a summary, not the truth. Points that look close in the plot may be far apart in the dropped dimensions. Use the plot to form hypotheses, then check them with the full data.
Computation
The cost of many algorithms grows with the number of features. Distance computations, matrix inversions and neural network input layers all get more expensive as d rises. Storage grows too: a float64 matrix with 1,000,000 samples and 784 features takes about 6.3 GB, and with 50 features it takes about 0.4 GB.
Reducing dimensions before a costly step can make it faster and cheaper. It can also make a model small enough to run where memory is limited.
The curse of dimensionality
A fifth reason sits behind the others. As the number of dimensions grows, the volume of the space grows exponentially, and a fixed number of samples covers it more and more thinly. This is the curse of dimensionality.
One consequence concerns distances. In high dimensions, the distance from a point to its nearest neighbor and to its farthest neighbor become similar. Methods that rely on "close" versus "far", such as k-nearest neighbors and many clustering algorithms, lose contrast.
You can see this with random points:
import numpy as np
rng = np.random.default_rng(3)
for d in [2, 10, 100, 1000]:
points = rng.uniform(size=(500, d))
q = rng.uniform(size=d)
dist = np.linalg.norm(points - q, axis=1)
print(d, "min/max distance ratio:", round(dist.min() / dist.max(), 3))The ratio starts small in 2 dimensions, where the nearest point is much closer than the farthest one. It climbs toward 1 as d grows, which means all points look about equally far away.
A second consequence is overfitting. With many features and few samples, a model can find patterns that exist only by chance. The usual rule of thumb is that the number of samples needed to cover the space grows quickly with d, so having more features than samples is a warning sign.
Feature selection versus feature extraction
There are two ways to get fewer features.
| Approach | What it does | Example | Keeps original meaning |
|---|---|---|---|
| Feature selection | Keeps a subset of the original columns | Drop columns with near-zero variance | Yes |
| Feature extraction | Builds new features from combinations of the originals | PCA | No |
PCA is feature extraction. Each new feature, called a principal component, mixes all the original columns. That gives strong compression, but a component such as "0.4 times height plus 0.3 times weight minus 0.2 times age" is harder to explain than "height". A later chapter on loadings covers how to read these mixtures.
PCA is also unsupervised. It looks only at the features X and never at a target y. It keeps directions of high variance, and high variance does not always mean useful for predicting y. Section "When reduction hurts" returns to this point.
What you give up
Dimensionality reduction is lossy. Every dimension you drop removes some information, and you cannot get it back from the reduced data. You trade information for simplicity, so you should measure the trade.
Two measures appear in the chapters ahead:
- Explained variance: the share of the total variance that the kept directions carry.
- Reconstruction error: the average squared difference between the original data and the data rebuilt from the reduced version.
The sketch below shows both on the earlier two-feature example. It keeps one direction and rebuilds the data.
import numpy as np
rng = np.random.default_rng(2)
a = rng.normal(size=500)
b = a + rng.normal(scale=0.1, size=500)
X = np.column_stack([a, b])
mean = X.mean(axis=0)
Xc = X - mean
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
v = Vt[:1] # keep one direction
Z = Xc @ v.T # 500 x 1 reduced data
X_back = Z @ v + mean # rebuilt 500 x 2 data
print("reduced shape:", Z.shape)
print("reconstruction error:", np.mean((X - X_back) ** 2))The reconstruction error is small, about 0.005, because the dropped direction held only the small gap between a and b. Had the two features been independent, the error would have been much larger.
When reduction hurts
Reduction is not free in every setting. Watch for these cases.
- Variance is not relevance. PCA keeps directions with high variance. A feature with small variance can still be the one that predicts your target. If you drop it, accuracy falls.
- Scale decides what counts as variance. A feature measured in meters and the same feature measured in millimeters have variances that differ by a factor of one million. Without standardizing, the large-scale feature dominates the first component. The chapter on centering and standardizing covers this.
- Nonlinear structure. PCA finds straight directions. Data that lies on a curve or a spiral cannot be flattened well by a straight projection.
- Interpretability. If stakeholders need to know which original feature drove a decision, combined features make that harder.
- Small gains. If your data has 8 features and a fast model, reduction may add complexity for no benefit.
A short check can catch the relevance problem. Compare a model trained on all features with one trained on the reduced features, using cross-validation, which is repeated train and test splitting on different parts of the data.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(4)
n = 600
big = rng.normal(scale=10.0, size=(n, 3)) # high variance, irrelevant
small = rng.normal(scale=0.1, size=(n, 1)) # low variance, decisive
X = np.hstack([big, small])
y = (small[:, 0] > 0).astype(int)
full = LogisticRegression(max_iter=1000)
reduced = make_pipeline(PCA(n_components=3), LogisticRegression(max_iter=1000))
print("all features:", cross_val_score(full, X, y, cv=5).mean())
print("PCA to 3: ", cross_val_score(reduced, X, y, cv=5).mean())The model on all features scores close to 1.0. The PCA model scores near 0.5, which is chance. PCA kept the three high-variance noise columns and dropped the one column that carried the label.
A decision checklist
Use these questions to decide whether PCA fits your problem.
- Are many features correlated? If not, PCA gains little.
- Is the structure roughly linear? If the data lies on a curve, consider a nonlinear method.
- Do you need to explain results in terms of the original features? If so, prefer feature selection.
- Are the features on comparable scales, or can you standardize them?
- Can you measure the effect on the downstream task?
If the answers are mostly yes, PCA is a good first tool. The chapters ahead build it step by step: covariance, eigenvectors, components, explained variance, and finally working code.
Exercises
Exercise
A dataset has 200 samples and 5,000 features. Name two problems this causes and one way PCA helps with each.
Show answer
Overfitting and high cost. With far more features than samples, a model can fit chance patterns, and PCA reduces the number of inputs so the model has fewer parameters to fit. Distance-based methods also lose contrast in high dimensions, and compute and storage grow with feature count, so projecting to a small number of components makes both cheaper.
Exercise
Explain the difference between feature selection and feature extraction, and say which one PCA is.
Show answer
Feature selection keeps a subset of the original columns, so each kept feature keeps its meaning. Feature extraction builds new features from combinations of the originals. PCA is feature extraction, because each principal component is a weighted sum of all the original features.
Exercise
In the last experiment, PCA with 3 components scored near chance while the full model scored close to 1.0. Why did this happen, and what would you do to detect it on your own data?
Show answer
PCA is unsupervised and keeps the directions with the highest variance. The three high-variance columns were irrelevant to the label, and the one decisive column had tiny variance, so it was dropped. To detect this, compare cross-validated performance of the full-feature model against the reduced-feature model before committing to the reduction.