SeeingML
Working With Data Guide 8 of 8 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

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.

Interactive Lab 1: Rotate the Line to Discover Principal Component 1 (PC1)
Original flats (2D)Green shadows: spread captured (64%)Amber drops: total miss (16)
-2-10+1+2-10+1Floor Area (centered)Flat Price (centered)
Green Shadow Spread (Variance Kept)64%
Total Amber Drop-Line Miss (Reconstruction Error)16
0° (64% variance captured)
At 0°, this axis captures 64% of the variance, leaving a total amber drop-line miss (reconstruction error) of 16. Drag toward 37° (or click Snap to True PC1) to stretch the green shadows out as wide as possible.

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.

Interactive Lab 2: Scree Plot (How Many Components to Keep?)
Retained: 83% (3/8 components)
Click any bar (PC1 to PC8) to move your cutoff:Dropped: 5 tiny noise axes
Steep cliff (real signal)Flat gravel slope (tiny noise axes)
Ranked perpendicular shadow axes (most spread to least)Bar height = share of total variance
Cumulative Variance Preserved (target: 85% to 95%)83%
Classic scree elbow at the first 3 components! Compressing 8 housing columns down to just 3 perpendicular shadow axes keeps 83% of all variance while dropping 5 tiny noise axes.

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.

Interactive Lab 3: Why Unscaled Units Hijack PC1 Completely
What makes up Principal Component 1 (PC1)?Income hijacks 99.8% of PC1
Annual Income (£25,000 to £120,000)99.8% of PC1
Huge raw numbers -> massive variance (squared spread)
Floor Area (35 to 140 m²)0.19% of PC1
Medium raw numbers -> dwarfed by pounds
Bedrooms (1 to 4)0.01% of PC1
Tiny raw numbers -> practically invisible to PC1
Because PCA chases raw variance (squared spread), £25,000 to £120,000 produces roughly a billion times larger squared spread than 1 to 4 bedrooms. Unscaled PCA simply hands you back the Income column disguised as PC1! Switch to Fixed above to rescale every column first.

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.

Interactive Lab 4: PCA vs. t-SNE vs. UMAP (Same 15-Song Catalog)
ClassicalJazzElectronic
Best for: Fast ML preprocessing and projecting unseen test rows instantaneously
PC1 (widest straight-line spread)PC2Overlap zone: straight-line flattening mixes curved genres in the middle
Curved clusters
Overlaps in middle
How far apart islands sit
Honest global distances
New unseen songs
Instant (no refit)
PCA uses a flat straight-line projection. Overall distances stay honest and you can project brand-new unseen songs instantaneously without refitting, yet curved genres overlap right in the middle. Click t-SNE or UMAP above to watch them untangle!
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 X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} with sample covariance Σ=1n−1X⊤X\mathbf{\Sigma} = \frac{1}{n-1}\mathbf{X}^\top \mathbf{X}, finding the unit vector v1\mathbf{v}_1 maximizing projected variance reduces to an eigenvalue problem:

max⁡∥v∥2=1  v⊤Σ v⟹Σ vj=λj vj\max_{\|\mathbf{v}\|_2 = 1} \;\mathbf{v}^\top \mathbf{\Sigma}\,\mathbf{v} \quad \Longrightarrow \quad \mathbf{\Sigma}\,\mathbf{v}_j = \lambda_j\,\mathbf{v}_j

The eigenvectors v1,…,vd\mathbf{v}_1, \dots, \mathbf{v}_d form an orthonormal basis ordered by eigenvalues λ1≥λ2≥⋯≥λd≥0\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d \ge 0. The explained variance ratio of component jj is simply λj/∑m=1dλm\lambda_j / \sum_{m=1}^{d} \lambda_m.

2. Singular Value Decomposition (SVD) & Exact Reconstruction Optimality: Numerical libraries avoid forming X⊤X\mathbf{X}^\top \mathbf{X} directly and instead compute X=USV⊤\mathbf{X} = \mathbf{U}\mathbf{S}\mathbf{V}^\top (so λj=sj2/(n−1)\lambda_j = s_j^2 / (n-1)). By the Eckart-Young-Mirsky theorem, keeping the top kk components yields the unique rank-kk linear approximation X^k=UkSkVk⊤\hat{\mathbf{X}}_k = \mathbf{U}_k \mathbf{S}_k \mathbf{V}_k^\top minimizing Frobenius reconstruction error ∥X−X^k∥F2\|\mathbf{X} - \hat{\mathbf{X}}_k\|_F^2.

3. Unsupervised Caveat & Non-Linear Alternatives: Because PCA ignores labels yy, 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
python
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.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Geometrically, what two properties hold simultaneously along Principal Component 1 (PC1)?

Pick an option first, or peek anytime
2

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?

Pick an option first, or peek anytime
3

You want a fast dimensionality reducer inside a production workflow that must transform brand-new unseen customer records every millisecond. Which method fits best?

Pick an option first, or peek anytime
4

Because PCA keeps the directions with the largest variance, it is guaranteed to keep the single best feature for separating two classification labels.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is Principal Component Analysis (PCA) and how does it work?
Principal Component Analysis (PCA) is a dimensionality reduction technique that rotates correlated features onto new perpendicular axes called principal components, ordered from highest variance (PC1) to lowest. Dropping the lowest-variance components compresses wide tables while preserving most of the underlying signal.
What does Principal Component Analysis (PCA) do in simple terms?
PCA rotates your coordinate axes to line up with the directions where your data spreads out the most, then drops the flat, low-spread trailing directions. It compresses many correlated columns into fewer uncorrelated super-features while preserving most of the information.
Why must you standardize features before running PCA?
PCA searches for directions with the largest variance. If one column is in pounds (£25,000 to £120,000) and another is in bedrooms (1 to 4), pounds have a billion times larger variance (squared spread) and hijack 99.8% of PC1 unless you standardize first.
How do you choose how many PCA components (k) to keep?
Plot a scree chart of each component's explained variance ratio and pick the 'elbow' or choose the smallest k whose cumulative variance exceeds your threshold (commonly 85% to 95%, or k = 2 strictly for 2D charts).
What is the difference between PCA, t-SNE, and UMAP?
PCA is a fast linear projection ideal for ML preprocessing pipelines and transforming new unseen data. t-SNE and UMAP are non-linear methods built primarily for 2D/3D human visualization of complex clusters, where UMAP runs faster and preserves fairer global layout than t-SNE.
Does PCA use the target label y when compressing features?
No. PCA is completely unsupervised: it preserves the directions of maximum input spread, not necessarily the directions that best separate target classes. If a tiny-variance clue happens to predict y strongly, PCA can discard it.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/principal-component-analysis/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@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}
}
APA

Irshad, M. A. (2026). Principal Component Analysis (PCA): Interactive Visual Guide. SeeingML. https://seeingml.com/learn/principal-component-analysis/