Concepts 🚀 Project 🧮 Labs
🧮 Labs / ML Advanced / PCA visualized — variance + projection (iris + digits)

PCA visualized — variance + projection (iris + digits)

SEE PCA reduce 4D iris to 2D. SEE the scree plot. SEE 64D digits collapse to 2D. The geometry of dimensionality reduction.

script.py v3.1
Python output click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
🧠 How it works

PCA (Principal Component Analysis) — VISUALIZED: WHAT: reduces dimensions while keeping maximum variance. 4D → 2D for visualization. MATHS: (1) Center data (subtract mean). (2) Covariance matrix Σ = (1/n) XᵀX — shows how features vary together. (3) Eigendecomposition: Σ = VΛVᵀ. V = eigenvectors (directions), Λ = eigenvalues (variance). (4) Top k eigenvectors = the k principal components (directions of max variance). (5) Project: X_proj = X · V[:,:k]. New features = linear combinations of old. SCREE PLOT: bar chart of variance per component. Look for the 'elbow' — components after the elbow add little value. IRIS: 4D → 2D captures 95.8% of variance. Setosa is perfectly separated. Versicolor + virginica overlap slightly — they're genuinely similar. DIGITS: 64D → 2D captures only 28% of variance, but digit clusters are STILL VISIBLE. This is the power of PCA — even with massive dimensionality reduction, structure survives. ALWAYS scale before PCA! Without scaling, features with large values (like salary in thousands) dominate the variance, and PCA just finds them.

✏️ Try these changes
  • Change n_components from 2 to 3 for iris PCA
    → captures more variance — try plotting in 3D with ax.scatter3D
  • Remove StandardScaler (use raw X instead of X_scaled)
    → petal length (0-7cm) dominates — sepal width (2-4cm) is ignored
  • Add a 3rd subplot: PCA with 3 components on iris, colored by species
    → 3D scatter shows even better separation
  • Change load_digits to load_breast_cancer (30 features)
    → 30D → 2D — see how cancer/benign separate