Working With Data Guide 8 of 8 · tap to switch
Principal Component Analysis (PCA)
How to rotate and compress dozens of correlated features into a few clean axes without throwing away the real story.
Imagine holding a 3D teapot in front of a lamp and casting its shadow onto a flat 2D wall. If you point the spout straight toward the wall, the shadow collapses into an unrecognizable blob. Turn the teapot sideways, and suddenly the shadow captures the handle, body, and spout clearly.
Principal Component Analysis (PCA) does that exact camera rotation for wide tables of numbers. When dozens of columns move together (such as floor area, rooms, garden size, and property price), PCA finds the best new rotated axes so just the first few capture almost all of the real variation.
To score any candidate camera angle, PCA measures variance: the total spread of the data cloud, calculated as squared distance from the center. When you project each point straight onto a candidate line, the cloud’s total variance splits cleanly into two parts: the captured variance (how wide the green projected shadows spread along the line) plus the reconstruction error (the total squared length of the perpendicular amber drop lines from each dot to its shadow). By Pythagoras’ theorem on centered data, those two parts always sum to the exact same fixed total, so rotating the line to maximize spread automatically shrinks the drop-line miss to its smallest possible value.
Drag the Projection Axis Angle slider below and watch both effects lock in at the exact same angle: the green projected shadows stretch to their widest spread, AND the amber dashed drop lines shrink to their shortest possible length.
Notice the subtle difference from Linear Regression: Linear Regression minimizes vertical miss lines to predict a target y, while PCA minimizes perpendicular (orthogonal) drop lines, treating all input features symmetrically.
Just remember one crucial caveat: PCA is completely unsupervised, meaning it ignores answer labels y and ONLY chases wide spread across the input columns. If a subtle, tiny-spread measurement happens to be the exact clue that separates Healthy patients from Sick patients, blind PCA may throw that signal away.
How many components should you keep? (The Scree Plot)
Once PCA rotates an 8-column housing dataset into 8 perpendicular components (PC1 through PC8), each axis comes ranked from most informative (46% of total variance) down to near-noise (1%).
To pick how many components to keep, analysts look at a Scree Plot, named after a mountain gravel slope where a steep rocky cliff drops abruptly into a flat apron of tiny pebbles (called scree). In the same way, the first few components form a steep cliff of real signal before bending at an “elbow” into flat pebbles of noise. Most workflows keep enough leading components to hold 85% to 95% of total variance.
Click any bar on the Scree Plot below to test different cutoffs and watch how much total information survives.
Why Principal Component Analysis (PCA) Requires Feature Scaling First
Because PCA hunts purely for large variance (squared spread), raw measurement units can hijack it instantly. Always rescale every column to mean 0 and equal spread (standard deviation = 1) using only your training data before running PCA, then apply that same rescaling to unseen test rows.
Start on the broken Raw Unscaled Units view below, then switch to Rescaled to Equal Spread (SD = 1) to watch a single large-unit column lose its monopoly over PC1.
Beyond straight projections: PCA vs. t-SNE vs. UMAP
PCA can only rotate and flatten space along straight lines. Because it learns fixed rotated axes during training, it projects brand-new unseen customer or song records instantaneously without refitting, making it the go-to compressor inside fast production workflows.
When a music catalog or complex collection of measurements lives on curved, folded shapes that a flat shadow squashes together, analysts turn to t-SNE or UMAP: curved neighborhood mapmakers that unroll folded clusters into 2D while keeping local neighbors close. Standard t-SNE builds crisp local islands for one-off 2D exploration, yet it distorts how far apart separate islands sit and requires refitting the whole map for new points; UMAP runs faster, keeps a fairer global layout of separate islands, and supports mapping new points.
Start on PCA below to see straight-line flattening tangle curved music genres in the middle, then switch to t-SNE and UMAP to see when each tool shines.
See the Covariance Eigendecomposition, SVD & Eckart-Young OptimalityThesis / Reference
1. Variance Maximization & Covariance Eigenvectors (Pearson, 1901; Hotelling, 1933): Given centered (and usually standardized) data matrix with sample covariance , finding the unit vector maximizing projected variance reduces to an eigenvalue problem:
The eigenvectors form an orthonormal basis ordered by eigenvalues . The explained variance ratio of component is simply .
2. Singular Value Decomposition (SVD) & Exact Reconstruction Optimality: Numerical libraries avoid forming directly and instead compute (so ). By the Eckart-Young-Mirsky theorem, keeping the top components yields the unique rank- linear approximation minimizing Frobenius reconstruction error .
3. Unsupervised Caveat & Non-Linear Alternatives: Because PCA ignores labels , a small-variance direction carrying decisive classification signal can be discarded (whereas supervised Linear Discriminant Analysis (LDA) explicitly maximizes between-class separation). For non-linear manifolds, t-SNE (van der Maaten & Hinton, 2008) minimizes KL divergence between local Gaussian and Student-t neighborhood affinities, while UMAP (McInnes et al., 2018) optimizes fuzzy topological graphs with faster scaling and stronger global preservation.
See leak-free StandardScaler + PCA in PythonOptional Code
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
# Fit StandardScaler AND PCA strictly on X_train!
# n_components=0.90 automatically picks the fewest PCs keeping 90% variance.
pipe = make_pipeline(
StandardScaler(),
PCA(n_components=0.90, random_state=42),
LogisticRegression(),
)
pipe.fit(X_train, y_train)
pca = pipe.named_steps["pca"]
print("Components kept:", pca.n_components_)
print("Explained variance ratios:", pca.explained_variance_ratio_.round(3))Congratulations: you just completed Path 02!
Across Working With Data, you mastered data types, summary statistics, probability distributions and the Central Limit Theorem, missing data & outlier cleaning, categorical encoding, feature scaling, distance metrics & Cosine similarity, feature engineering & Lasso selection, and PCA compression.
Ready to put clean, engineered data to work inside real algorithms? Continue straight into Path 03: Core ML Models (K-Nearest Neighbors) or browse the full Visual Library.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
Geometrically, what two properties hold simultaneously along Principal Component 1 (PC1)?
You run PCA on an unscaled housing table containing Annual Income (£20k to £150k) and Number of Bathrooms (1 to 4). PC1 explains 99.9% of variance. Why?
You want a fast dimensionality reducer inside a production workflow that must transform brand-new unseen customer records every millisecond. Which method fits best?
Because PCA keeps the directions with the largest variance, it is guaranteed to keep the single best feature for separating two classification labels.
Common Questions
What is Principal Component Analysis (PCA) and how does it work?
What does Principal Component Analysis (PCA) do in simple terms?
Why must you standardize features before running PCA?
How do you choose how many PCA components (k) to keep?
What is the difference between PCA, t-SNE, and UMAP?
Does PCA use the target label y when compressing features?
Related Visual Guides
Eigenvalues and Eigenvectors
Spin a probe arrow to catch the rare directions that refuse to tilt under a matrix warp, and see why they power PCA and PageRank.
Vector Spaces, Span & Basis
See how two basis arrows tile an entire 2D plane, watch dependent columns collapse into a 1D rail, and rotate rulers like PCA.
Feature Scaling: Normalization vs Standardization
Why salary in pounds bullies age in years, how Min-Max, Standardization, and RobustScaler compare under outliers, and which models actually care.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026principalcomponentanalysis,
author = {Irshad, Muhammad Aashir},
title = {Principal Component Analysis (PCA): Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/principal-component-analysis/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). Principal Component Analysis (PCA): Interactive Visual Guide. SeeingML. https://seeingml.com/learn/principal-component-analysis/