Dimensionality Reduction
Dimensionality reduction is describing data with fewer features while keeping as much of its information as possible. Each feature is a dimension, so six study habits put every student in a six-dimensional space that nobody can picture. Reducing it to two dimensions lets you plot it, speeds up models, and removes features that repeat each other.
PCA (principal component analysis) is the most widely used method. It finds new axes, called principal components, that each combine the original features, ordered so the first captures the most variation in the data, the second the next most, and so on.
Why Reduce Dimensions
| Reason | Description |
|---|---|
| Visualize | It is used to plot high-dimensional data in 2D or 3D |
| Remove repetition | It is used to combine features that move together into one |
| Speed up models | It is used to train faster on fewer inputs |
| Reduce noise | It is used to drop the small components that are mostly noise |
Example: PCA
This program uses study_habits.csv from "Unsupervised Learning and Clustering".
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
students = pd.read_csv("study_habits.csv")
X = StandardScaler().fit_transform(students)
pca = PCA().fit(X) # keep every component, to see how much each explains
for i, share in enumerate(pca.explained_variance_ratio_, start=1):
print(f"Component {i}: {share:.1%} of the variation (running total {pca.explained_variance_ratio_[:i].sum():.1%})")
pca2 = PCA(n_components=2).fit(X)
loadings = pd.DataFrame(pca2.components_.T, index=students.columns, columns=["PC1", "PC2"]).round(2)
print(loadings)
points = pca2.transform(X) # 300 students, now 2 numbers each instead of 6
print("Shape before:", X.shape, "after:", points.shape)
print("First student:", points[0].round(2))Component 1: 50.0% of the variation (running total 50.0%)
Component 2: 21.2% of the variation (running total 71.3%)
Component 3: 12.5% of the variation (running total 83.8%)
Component 4: 7.2% of the variation (running total 90.9%)
Component 5: 5.5% of the variation (running total 96.4%)
Component 6: 3.6% of the variation (running total 100.0%)
PC1 PC2
hours_per_week 0.47 0.31
videos_watched -0.10 0.81
quizzes_taken 0.35 -0.36
forum_posts 0.43 -0.02
days_active 0.49 0.30
avg_quiz_score 0.47 -0.17
Shape before: (300, 6) after: (300, 2)
First student: [-2.08 -2.53]Explanation: PCA is fit on scaled data, like k-means. explained_variance_ratio_ shows that the first component alone keeps 50.0% of the variation, and the first two keep 71.3%. The loadings show what each component is made of:
| Component | Biggest weights | Meaning |
|---|---|---|
| PC1 | days active 0.49, hours 0.47, quiz score 0.47, forum posts 0.43, quizzes 0.35 | Overall effort: high for students who do a lot of everything |
| PC2 | videos watched 0.81, quizzes −0.36 | Watching instead of practicing |
transform() turns each student's six numbers into two, so the shape goes from (300, 6) to (300, 2). The first student scores −2.08 on effort and −2.53 on watching: a low-effort student who watches few videos, which matches the crammers. In the plot above, the four groups found by clustering stay clearly apart in just two dimensions.
Choosing How Many Components
Instead of a number of components, you can ask PCA for a share of the variation to keep.
This program uses study_habits.csv from "Unsupervised Learning and Clustering".
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
students = pd.read_csv("study_habits.csv")
X = StandardScaler().fit_transform(students)
pca = PCA(n_components=0.90).fit(X) # keep as many components as needed for 90%
print("Components kept:", pca.n_components_, f"explaining {pca.explained_variance_ratio_.sum():.1%}")Components kept: 4 explaining 90.9%Explanation: n_components=0.90 keeps adding components until at least 90% of the variation is kept. Here that takes 4 of the 6 components (90.9%), a modest saving because the six habits mostly measure different things. On data with hundreds of related features, such as pixels in an image, PCA can often keep 90% with a small fraction of the features.
| Goal | A common choice |
|---|---|
| A plot | 2 or 3 components |
| Faster models, little loss | Enough components for 90% to 99% of the variation |
| Choosing by eye | Plot the cumulative share and look for where it levels off |
PCA Terms
| Term | Description |
|---|---|
| Principal component | A new axis that combines the original features |
| Explained variance ratio | The share of the data's variation a component captures |
| Loadings | The weights that show how much each feature contributes to a component |
| Projection | A data point's coordinates on the new axes, from transform() |
Other Methods
| Method | Description | Best for |
|---|---|---|
| PCA | Straight-line combinations of features | A fast, general first choice |
| t-SNE | Keeps nearby points nearby in a 2D map | Visualizing clusters; not for feeding models |
| UMAP | Like t-SNE, faster, keeps more overall structure | Visualizing large datasets |
| Feature selection | Keeps some original features and drops others | When features must stay understandable |
| Embeddings | Learned dense vectors | Text and images (see "What Are Embeddings") |
Common Mistakes
Running PCA on unscaled data. The component directions then reflect units, not structure.
Fitting PCA on all the data before splitting. Fit it on the training data only, inside a pipeline, as with any preprocessing step.
Treating components as original features. "PC1" is a blend; explain it through its loadings.
Reading distances in a t-SNE plot. t-SNE keeps neighbors together, but the gaps between clusters mean little.
Interview Corner
What does PCA do?
It finds new axes, the principal components, along which the data varies most, ordered from most to least variation. Keeping the first few gives a smaller description that retains most of the information.
How do you choose the number of principal components?
By the share of variance to keep, such as 90% or 95%, or 2 or 3 for plotting, checked by looking at the cumulative explained variance.
Practice
Exercise: compress, then cluster. Run k-means with 4 clusters on the two PCA components instead of the six scaled features, and compare the groups with adjusted_rand_score. Does clustering still find the same groups with a third of the information gone?
Check your understanding:
- How much variation do the first two components keep?
- What does PC2 mostly measure?
- Why does keeping 90% need 4 components here?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| PCA with 2 components | PCA(n_components=2).fit(X) |
| Keep 90% of the variation | PCA(n_components=0.90) |
| Share per component | pca.explained_variance_ratio_ |
| Loadings | pca.components_ |
| Project data | pca.transform(X) |
Was this tutorial helpful?