Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 07 / Topic 3 of 5

Dimensionality reduction with PCA

PCA finds new axes (principal components) that capture the most variance, in order. Keep the first few and you compress the data while losing as little information as possible.

# examples/02_pca_how_many_dimensions_do_the.py
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X = load_digits().data                      # 1797 images, 8x8 = 64 features
pca = PCA().fit(X)
cum = np.cumsum(pca.explained_variance_ratio_)
for target in [0.80, 0.90, 0.95]:
    print(f"{int(target*100)}% of variance needs {np.argmax(cum >= target) + 1} components")
# 80% of variance needs 13 components
# 90% of variance needs 21 components
# 95% of variance needs 29 components

The 64-pixel digits are really ~21-dimensional: pixels are correlated (strokes, not noise). Uses: speed up downstream models, denoise, and — most commonly — project to 2 components for a plot.

🧪 Quick quiz

  1. What does PCA find?
Show the answer

New axes (components) that capture the most variance — on digits, 21 components keep 90% of it. It finds directions, not clusters or labels.

Done here? The practice set for Part 7 — 4 exercises with solutions — is on the part page.

Search the guide