Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 96/ 160
05. Classical Machine Learning

Principal Component Analysis (PCA)

Reduce dimensions via principal components while preserving variance for viz and models.

IntermediateComponents · Explained Variance3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

PCA squeezes many related columns into a few new columns that keep as much of the variation as possible.

Think of it like…

Finding the best angle from which to photograph a cloud of points: the first axis points along the longest stretch of the cloud, the second along the next longest at a right angle, and you keep only as many views as you need to capture most of the shape.

Where you’ve seen it

Two centred features have covariance matrix [[2, 1], [1, 2]]. Its eigenvalues solve λ² − 4λ + 3 = 0, giving 3 and 1, with eigenvectors (1, 1)/√2 and (1, −1)/√2. The first component explains 3 / 4 = 75% of the total variance and the second 25%. A centred point (2, 2) projects to a PC1 score of (2 + 2)/√2 = 2.828 and a PC2 score of 0; a point (1, −1) has PC1 = 0 and PC2 = 1.414, and dropping PC2 reconstructs it as (0, 0) with squared error 2. The average squared reconstruction error from keeping one component equals the dropped eigenvalue, 1. On a 50-feature customer dataset standardised to unit variance, the first three components explain 42%, 18% and 9% (69% together) and 12 components reach 95%, so a model trained on the 12 scores is 4 times smaller and nearly as accurate. The scaler and PCA are fitted inside a cross-validation pipeline so validation rows never influence the components.

Words you’ll hear

Principal component
A direction of maximum remaining variance, orthogonal to earlier components.
Explained variance ratio
The share of total variance captured by each component.
Loadings
The weights (eigenvector entries) relating original features to a component.
Whitening
Rescaling component scores to unit variance.

Visual diagram

Loading interactive diagram

Theory & deep dive

The math in brief

Centre the data (subtract each feature's mean) to get X. The covariance matrix is C = XᵀX / (n − 1). PCA finds the unit vector v₁ maximising the variance of the projection Xv, which is the top eigenvector of C with variance λ₁; v₂ maximises variance among directions orthogonal to v₁, and so on. For C = [[2, 1], [1, 2]] the eigenvalues are 3 and 1 and the eigenvectors (1, 1)/√2 and (1, −1)/√2, so PC1 points along the diagonal where both features rise together and carries 75% of the variance. Numerically, PCA is computed by the singular value decomposition X = UΣVᵀ: columns of V are the components and λᵢ = σᵢ² / (n − 1); scikit-learn's PCA does this, with randomised and incremental variants for large data.

The scores (projected data) are X V_k, the explained variance ratio is λᵢ / Σλ, and the reconstruction X̂ = X V_k V_kᵀ has mean squared error equal to the sum of the discarded eigenvalues (here 1 when keeping only PC1). Components are uncorrelated, and whitening divides scores by √λ to give unit variance. Signs of components are arbitrary (a component and its negative are equivalent), which matters when comparing runs. Without standardising, features measured in large units (dollars) dominate the first component simply because their variance is large; with standardised features, PCA operates on the correlation matrix.

A 2D worked example

C = [[2, 1], [1, 2]]. λ = 3 (v = (1, 1)/√2) and λ = 1 (v = (1, −1)/√2). Point (2, 2): PC1 = 4/√2 = 2.828, PC2 = 0. Point (1, −1): PC1 = 0, PC2 = 1.414. Explained variance: 75% and 25%.

Key takeaway: PCA diagonalises the covariance matrix; components are ordered by explained variance and are best computed with SVD on scaled data.

Choosing k, interpreting and avoiding pitfalls

Choose the number of components with a scree plot (look for the elbow), a cumulative explained variance target (95% is common; PCA(n_components=0.95) selects automatically), cross-validated downstream performance (treat k as a hyperparameter in a pipeline) or the Kaiser rule (keep components with eigenvalue above 1 on standardised data). For visualisation use 2 or 3 components, noting how much variance they hold (69% for 3 in the example). Interpret components through loadings: the features with the largest absolute weights define what a component means (for example PC1 = overall spend and activity, PC2 = recency versus frequency), though rotations such as varimax can help.

Pitfalls: PCA is linear, so curved structure (a spiral, a manifold) isn't captured (use kernel PCA, UMAP or autoencoders); it maximises variance, not predictive power, so a low-variance component can be the one that separates the classes (use supervised alternatives such as LDA or PLS when you have a target); it's sensitive to outliers and scaling; and fitting it on the full dataset before splitting leaks information, so always put scaler and PCA inside the pipeline. Components lose original-feature interpretability, which matters for regulated models. Typical uses: decorrelating predictors for regression (principal component regression), compressing features for KNN or SVM, denoising by reconstructing from the top components, anomaly detection by reconstruction error and exploratory plotting.

Pipeline

pipe = make_pipeline(StandardScaler(), PCA(n_components=0.95), LogisticRegression()) evaluated with cross-validation. On the 50-feature data PCA keeps 12 components (95.2% of variance) and the model's AUC is 0.842, versus 0.849 with all 50 features, with four times fewer inputs.

Key takeaway: Pick k from cumulative variance or cross-validation, interpret via loadings and keep PCA inside a leakage-safe pipeline.

How it works, step by step

Step 1 of 4
Analyst

1. Standardise

Centre and scale numeric features inside the training fold so each has unit variance.

StandardScaler first
Key numbers at this step
Categoricals
encode or exclude

When to use it & trade-offs

What it is

Principal component analysis (PCA) finds orthogonal directions, the principal components, along which the data varies most, ordered by variance. Formally the components are the eigenvectors of the covariance matrix (the right singular vectors of the centred data matrix), and each eigenvalue is the variance captured by its component. Projecting onto the first k components gives a lower-dimensional representation that preserves as much variance as possible and decorrelates the features. PCA is linear and unsupervised, requires centring (and usually standardising) the features, and is used for visualisation, noise reduction, removing multicollinearity and speeding up downstream models.

Why it matters: Real datasets often have dozens or hundreds of correlated features. PCA compresses them into a few uncorrelated scores, which makes models more stable and faster, lets you plot high-dimensional data in 2D and reveals the dominant structure. Using it correctly means knowing what it assumes (linear structure, variance equals importance), how many components to keep and how to avoid leakage by fitting it only on training data.

When to reach for it

  • Compressing correlated features before modelling
  • 2D and 3D visualisation of high-dimensional data
  • Denoising and reconstruction-error anomaly detection

When to avoid or be careful

  • PCA on unscaled features with different units
  • Fitting PCA on the full data before splitting
  • Assuming high-variance components are the most predictive

Dimensionality reduction options

PCA
Best for: Linear structure, decorrelation and compression

Strengths: Fast, deterministic, interpretable loadings.

Watch out: Linear only; variance is not relevance.

LDA or PLS
Best for: Reducing dimensions with class or target information

Strengths: Keeps predictive directions.

Watch out: Needs labels; can overfit with few samples.

t-SNE / UMAP
Best for: Nonlinear visualisation

Strengths: Reveals clusters and manifolds.

Watch out: Distances not meaningful; not for modelling inputs without care.

Interview signals & numbers to know

When this topic comes up

  • “Too many correlated features”
  • “How many components?”
  • Explained variance ratio
  • Scree plot
  • SVD and eigenvectors

Benchmarks & rules of thumb

λ = 3 and 1 -
eigenvalues of [[2, 1], [1, 2]]
75% / 25% -
explained variance of the two components
95% -
common cumulative variance target

Common mistakes & follow-ups

Common interview mistakes

  • Interpreting a component's sign as meaningful.
  • Keeping components by a rule of thumb without checking model performance.
  • Applying PCA to one-hot encoded categoricals and reading the result as numeric structure.

Likely interviewer follow-ups

  • How is PCA related to SVD?
  • How do you choose the number of components?
  • When would PCA hurt predictive performance?
Interview tip: Do the 2×2 eigen-decomposition aloud. Showing eigenvalues 3 and 1 and the 75% split proves you know what the library computes.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Principal Component Analysis (PCA) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
DBSCAN & Density-Based Clustering
Next topic
t-SNE & UMAP for Visualization