Module 22

Principal Component Analysis

Reducing dimensions while preserving information

Dimensionality Reduction

  • 01

    Variance

    Information is in the spread

  • 02

    Principal Components

    New axes of maximum variance

  • 03

    Loadings

    Original variable contributions

  • 04

    Scree Plot

    Choosing number of components

01

Why Reduce Dimensions?

The Curse of Dimensionality

1000
Original Variables
→
10
Principal Components
High dimensions cause: sparse data, overfitting, computational cost, visualization impossibility

High-dimensional data (many variables) creates problems: data becomes sparse, distances lose meaning, models overfit, computation slows, and visualization is impossible beyond 3D. Dimensionality reduction compresses data while preserving the important structure.

The Core Insight

PC1
Data lies mostly along one direction.
PC1 captures most of the variance.

Variables are often correlated - when one goes up, others tend to go up or down predictably. This means the data actually lies in a lower-dimensional space. PCA finds that space by identifying directions (principal components) that capture the most variance.

Where PCA Helps

Visualization
Project high-D data to 2D/3D for plotting
Preprocessing
Remove noise, reduce features before modeling
Compression
Store images/signals with fewer numbers
Feature Engineering
Create uncorrelated composite variables
Denoising
Remove components that are mostly noise
Multicollinearity
Fix correlated predictors in regression

PCA is a Swiss army knife: visualize high-D data in 2D, reduce features before ML, compress images, create uncorrelated variables, remove noise, fix multicollinearity. It's often the first step in exploring complex datasets.

02

How PCA Works

The PCA Algorithm

1
Standardize data (center, scale)
2
Compute covariance matrix
3
Find eigenvalues & eigenvectors
4
Sort by eigenvalue (variance explained)
5
Project data onto top k components

PCA finds orthogonal directions that maximize variance. Mathematically: compute the covariance matrix, find its eigenvalues and eigenvectors. Eigenvectors are the principal component directions; eigenvalues indicate how much variance each captures. Sort by eigenvalue, keep the top k.

Geometric View

PC1 (major axis)
PC2 (minor axis)
PC1 aligns with the direction of maximum spread.
PC2 is perpendicular, captures remaining variance.

Think of data as an ellipsoid cloud. PC1 is the longest axis - the direction of greatest spread. PC2 is perpendicular to PC1 and is the next longest. Each subsequent PC is perpendicular to all previous ones, capturing decreasing amounts of variance.

Why Standardize First

✗ Without Standardization
Height (cm): 150-200
Weight (kg): 50-100
Income ($): 30,000-150,000
Income dominates PCA!
✓ With Standardization
Height: z-score
Weight: z-score
Income: z-score
All variables equal footing

PCA maximizes variance, so variables with larger scales dominate. Income in dollars has more variance than height in centimeters just due to units, not importance. Standardizing (z-scores) puts all variables on equal footing. Always standardize unless variables are already comparable.

What PCA Produces

Eigenvalues (λ)
λ₁ = 3.2, λ₂ = 1.5, λ₃ = 0.8, λ₄ = 0.3, λ₅ = 0.2
Variance captured by each PC
Loadings (Eigenvectors)
PC1 = 0.5×X₁ + 0.4×X₂ - 0.6×X₃ + ...
How original variables combine
Scores (Projections)
Each observation's coordinates on PCs
New reduced representation of data

PCA outputs: (1) Eigenvalues showing variance per component, (2) Loadings showing how original variables combine into PCs, (3) Scores - each observation's values on the new PC axes. Use eigenvalues to choose k, loadings to interpret PCs, scores for downstream analysis.

03

Variance Explained

How Much Information Kept?

% Variance Explained = λᵢ / Σλ × 100
PC1
45%
PC2
25%
PC3
15%
PC4
8%
PC5
4%

Each PC captures a portion of total variance. PC1 captures the most, PC2 the second most, etc. The percentage is the eigenvalue divided by sum of all eigenvalues. Keeping PC1 and PC2 (70% in this example) means 70% of the original information is preserved.

The Elbow Method for PCA

elbow
Scree plot: eigenvalues vs component number. Look for the 'elbow' where the curve flattens - keep components before the elbow.

The scree plot shows eigenvalues (or variance explained) for each PC. The curve typically drops steeply then flattens. The 'elbow' where it bends suggests how many PCs to keep. Components after the elbow add little information but add noise and complexity.

How Many Components?

Cumulative Variance Rule
Keep enough PCs to explain 80-95% of variance
Kaiser Criterion
Keep PCs with eigenvalue > 1
(for standardized data)
Scree Plot Elbow
Visual inspection for diminishing returns
Cross-Validation
Choose k that optimizes downstream task

Several rules exist: keep enough for 80-95% variance, keep eigenvalues > 1 (Kaiser), use scree plot elbow, or cross-validate based on downstream performance. No single rule is best - use multiple and consider your goals.

04

Interpreting Components

What Variables Contribute?

PC1 Loadings (Component = Linear Combination)
VariableLoadingInterpretation
Income+0.82Strong positive
Education+0.75Strong positive
Age+0.25Weak positive
Debt-0.60Strong negative
PC1 ≈ "Socioeconomic Status"

Loadings show how much each original variable contributes to a PC. High absolute loadings indicate important variables. Same-sign loadings move together; opposite signs move inversely. Use loadings to name/interpret components - here PC1 captures 'socioeconomic status'.

Visualizing Loadings and Scores

Var1
Var2
Points = observations; Arrows = variable loadings

A biplot shows both scores (observations as points) and loadings (variables as arrows) on the same plot. Arrow direction shows loading signs; length shows magnitude. Points near an arrow have high values on that variable. Arrows pointing same direction indicate correlation.

Varimax and Other Rotations

Before Rotation
.65, .55, .40, .35
.50, .45, .60, .30
Mixed loadings
After Varimax
.90, .85, .10, .05
.10, .15, .88, .82
Clear structure
Rotation keeps total variance but redistributes it for simpler interpretation.

Raw PCA loadings can be hard to interpret - variables load on multiple components. Rotation (like varimax) redistributes loadings to push them toward 0 or ±1, making each component depend on fewer variables. Doesn't change total variance explained, just makes interpretation easier.

05

PCA in Practice

Step-by-Step PCA

1
Check for missing data; impute or remove
2
Standardize all variables (z-scores)
3
Run PCA; examine scree plot
4
Choose number of components (80-95%)
5
Examine loadings; interpret/name PCs
6
Use scores for visualization or modeling

A typical PCA workflow: handle missing data, standardize variables, run PCA, examine scree plot to choose k, interpret loadings to understand components, then use scores for downstream tasks (visualization, clustering, regression). Document your choices.

When Does PCA Work?

✓
Linear relationships between variables
✓
Continuous (or ordinal) variables
✓
No severe outliers (or handle them first)
✓
Adequate sample size (n > p preferred)
If violated: Use robust PCA, kernel PCA (nonlinear), or factor analysis (categorical)

PCA assumes linear relationships - it finds linear combinations. Non-linear patterns need kernel PCA. Outliers distort results - robust PCA helps. Binary/categorical data may need different methods. More observations than variables is ideal, though not strictly required.

Common Mistakes

✗
Forgetting to standardize (scale matters!)
✗
Keeping too few PCs (losing information)
✗
Keeping too many PCs (keeping noise)
✗
Over-interpreting small loadings
✗
Ignoring outliers
✗
Applying to non-numeric data directly
✗
Confusing correlation with causation

Common errors: not standardizing lets large-scale variables dominate; keeping too few/many PCs either loses signal or keeps noise; over-interpreting weak loadings; not handling outliers. PCA shows correlation structure - don't claim causal relationships from it.

Beyond PCA

Factor Analysis
Models latent factors causing correlations
t-SNE / UMAP
Non-linear; great for visualization
ICA
Independent components (signal separation)
Autoencoders
Neural network dimensionality reduction
PCA for linear relationships; t-SNE/UMAP for visualization; autoencoders for complex patterns

PCA alternatives: Factor Analysis models underlying latent variables. t-SNE and UMAP capture non-linear structure for visualization. ICA finds independent sources. Autoencoders use neural networks for non-linear reduction. Choose based on your goals and data characteristics.

★

Real-World Examples

Apply your knowledge to practical scenarios

01

Eigenfaces for Face Recognition

A face recognition system has a database of 10,000 face images, each 100×100 pixels (10,000 dimensions). PCA reduces each face to 150 principal components while retaining 95% of variance.

Q How does PCA make face recognition practical? +
A Instead of comparing 10,000-dimensional vectors (100×100 pixels), we compare 150-dimensional PC scores. This is 66× fewer dimensions, making storage, search, and matching much faster.
Q What are 'eigenfaces' in this context? +
A Eigenfaces are the principal components—they look like ghostly average faces. Each eigenface captures a mode of variation (lighting direction, expression, face shape). A face is represented as a weighted combination of eigenfaces.
Q Why does keeping 95% of variance mean losing 5% of information? +
A The discarded 5% is mostly noise—random pixel variations that don't help distinguish faces. By removing noise, we actually improve recognition! The signal-to-noise ratio increases.
Q When would this approach fail? +
A PCA captures linear variation. If faces vary non-linearly (extreme poses, dramatic lighting changes), PCA struggles. Also fails with disguises, aging, or accessories that weren't in training data.
Key Insights
  • PCA enables high-dimensional pattern recognition by reducing noise
  • Principal components can have interpretable meanings (eigenfaces)
  • Dimensionality reduction often IMPROVES downstream performance
02

Portfolio Risk Factor Analysis

A fund manager tracks returns of 500 stocks. PCA on the correlation matrix reveals: PC1 explains 40% of variance, PC2 explains 15%, PC3 explains 8%. The first 10 PCs explain 80% of total variance.

Q What does PC1 (40% variance) likely represent? +
A In stock returns, PC1 is almost always the 'market factor'—all stocks moving together when the overall market rises or falls. High PC1 loading means high market sensitivity (beta).
Q If PC2 has high loadings for tech stocks and negative loadings for utilities, what does it capture? +
A PC2 likely captures a 'growth vs. value' or 'sector rotation' factor. When PC2 is high, tech outperforms utilities; when low, utilities outperform. It's a second source of systematic risk.
Q How can the fund manager use this information? +
A Understand that '500 stocks' actually means '~10 independent risk factors.' Diversifying across many stocks in the same factor doesn't reduce risk. True diversification requires exposure to different PCs.
Q What risk does the remaining 20% variance represent? +
A Idiosyncratic (stock-specific) risk. This is company-specific news, earnings surprises, management changes—randomness that diversification CAN eliminate. The 80% systematic risk cannot be diversified away.
Key Insights
  • Stock returns are driven by a few systematic factors, not 500 independent variables
  • PC1 in finance is typically the market factor
  • PCA reveals the true dimensionality of portfolio risk
03

Gene Expression Analysis

A cancer researcher measures expression of 20,000 genes in 100 tumor samples. PCA visualization shows samples naturally clustering into 3 groups in PC1-PC2 space, corresponding to different cancer subtypes.

Q Why is PCA essential for this type of data? +
A With 20,000 genes and 100 samples, you have far more variables than observations. Most analyses would fail. PCA compresses 20,000 genes into a few PCs that capture the main patterns.
Q The researcher sees 3 clusters. What should they do next? +
A Examine which genes have high loadings on PC1 and PC2—these drive the subtype differences. They might be therapeutic targets or diagnostic markers. Also validate with known cancer subtypes.
Q PC1 explains 30% and PC2 explains 15%. Is this good? +
A For gene expression data, explaining 30% with one component is excellent! These 20,000 genes aren't random—they're controlled by common regulatory pathways. PCA finds these shared patterns.
Q A gene has loading 0.05 on all PCs. What does this suggest? +
A This gene doesn't co-vary with others—its expression is independent of the main patterns. It might be housekeeping gene (always on), or simply noisy/uninformative. It contributes to residual variance, not PCs.
Key Insights
  • PCA handles p >> n situations where most methods fail
  • Loadings reveal which original variables drive each PC
  • Visualization in PC space can reveal natural groupings
?

PCA Quiz

Test your understanding • Passing score: 70%

0 of 10 answered
Q1 multiple-choice

Principal components are:

Explanation: PCs are new variables created as linear combinations of originals. They are orthogonal (uncorrelated) and ordered by variance explained. They represent the main directions of variation in the data.
Q2 multiple-choice

PC1 always:

Explanation: PC1 is defined as the direction in which the data varies most. PC2 captures the most remaining variance orthogonal to PC1, and so on.
Q3 multiple-choice

Why standardize variables before PCA?

Explanation: Without standardization, variables with larger scales dominate the variance and thus the PCs. Standardizing (mean 0, SD 1) puts all variables on equal footing.
Q4 multiple-choice

A scree plot helps determine:

Explanation: A scree plot shows variance explained by each PC. Look for an 'elbow' where the line flattens—retain PCs before the elbow. This balances dimensionality reduction with information retention.
Q5 multiple-choice

If you retain components explaining 85% of variance, you lose:

Explanation: The discarded 15% is a mix of minor signal and noise. For well-structured data, most of it is noise. Removing it can improve downstream analyses by reducing overfitting.
Q6 multiple-choice

Loadings in PCA represent:

Explanation: Loadings are the weights of original variables in the PC linear combination. High loading means that variable strongly influences that PC. Loadings help interpret what each PC represents.
Q7 multiple-choice

PCA is a linear method, meaning:

Explanation: PCA creates new variables as linear (weighted sum) combinations of originals: PC = w₁X₁ + w₂X₂ + ... This means it captures linear relationships but may miss non-linear structure.
Q8 multiple-choice

Compared to PCA, t-SNE is better for:

Explanation: t-SNE (and UMAP) excel at non-linear dimensionality reduction for visualization. They reveal clusters and local structure that PCA might miss. However, they don't provide loadings or variance explained.
Q9 multiple-choice

If all variables are uncorrelated, PCA will:

Explanation: When variables are uncorrelated, each is already a 'principal direction.' The PCs would essentially be the original variables, each explaining equal variance. PCA provides no compression.
Q10 multiple-choice

The cumulative variance explained by the first 3 PCs is 60%. This means:

Explanation: Cumulative variance explained tells you how much information is retained when reducing to k PCs. Here, projecting 3D captures 60% of total variance; 40% is in remaining PCs.

Quiz Results

0 %

← Clustering Next: Qualitative & Mixed Methods →