4.2 Dimensionality Reduction
4.2 Dimensionality Reduction
Key Concepts
4.2.1 Why Reduce Dimensions?
High-dimensional data poses several challenges:
Problems with High Dimensions:
1. Curse of dimensionality - data becomes sparse
2. Computational cost - O(d) or O(d^2) operations
3. Overfitting - more features than samples
4. Visualization - can't plot > 3D
5. Noise - irrelevant features add noise
6. Multicollinearity - correlated featuresGoals of Dimensionality Reduction:
- Reduce storage and computation
- Remove noise and redundancy
- Enable visualization
- Improve model performance
- Feature extraction / representation learningTypes of Methods
Dimensionality Reduction
|
┌───────────────┼───────────────┐
| | |
Linear Non-linear Feature Selection
| | |
PCA, SVD, t-SNE, UMAP, Filter, Wrapper,
LDA, FA Autoencoders Embedded
| | |
Global Local Subset of
structure structure original features4.2.2 Principal Component Analysis (PCA)
Linear transformation that finds directions of maximum variance.
Intuition
Original 2D data: After PCA:
● ● ● PC1 (max variance)
● ● ● ● ↗
● ● ● ● ● ●●●●●●●●●●●
● ● ● ● ↑
● ● ● PC2 (orthogonal)
Data spread along diagonal Axes aligned with varianceMathematical Formulation
Goal: Find orthogonal directions (principal components) that maximize variance.
Step 1: Center the data
X_centered = X - mean(X)Step 2: Compute covariance matrix
C = (1/n) * X^T * X (d × d matrix)
C_ij = Cov(feature_i, feature_j)Step 3: Eigendecomposition
C * v = λ * v
Where:
- v = eigenvector (principal component direction)
- λ = eigenvalue (variance along that direction)
Sort by eigenvalue: λ_1 >= λ_2 >= ... >= λ_dStep 4: Project data
Z = X * V_k
Where V_k = [v_1, v_2, ..., v_k] (top k eigenvectors)
Z is n × k (reduced from n × d)Algorithm
def pca(X, k):
# 1. Center data
X_centered = X - X.mean(axis=0)
# 2. Covariance matrix
C = (X_centered.T @ X_centered) / (n - 1)
# 3. Eigendecomposition
eigenvalues, eigenvectors = np.linalg.eigh(C)
# 4. Sort by eigenvalue (descending)
idx = np.argsort(eigenvalues)[::-1]
eigenvectors = eigenvectors[:, idx]
eigenvalues = eigenvalues[idx]
# 5. Select top k components
V_k = eigenvectors[:, :k]
# 6. Project
Z = X_centered @ V_k
return Z, V_k, eigenvaluesChoosing Number of Components
Explained Variance Ratio:
Variance explained by PC_i = λ_i / sum(λ)
Cumulative variance:
k
R(k) = sum(λ_i) / sum(λ)
i=1
Choose k where R(k) >= threshold (e.g., 0.95)Scree Plot:
Variance
|
|●
| ●
| ●
| ●●●●●●●
└──────────── Component
↑
"elbow"PCA via SVD
More numerically stable, especially for wide matrices:
X = U * Σ * V^T
Where:
- U: n × n (left singular vectors)
- Σ: n × d diagonal (singular values)
- V: d × d (right singular vectors = principal components!)
Relationship:
- Singular values: σ_i = sqrt(λ_i * (n-1))
- Principal components: columns of V
- Projected data: U * Σ (or X * V)Assumptions of PCA
1. Linearity
- Assumes linear relationships
- Non-linear patterns not captured
2. Large variance = important
- May not be true (high-variance noise)
- Consider scaling features first
3. Orthogonal components
- Components are uncorrelated
- May not match underlying factors
4. Mean and covariance sufficient
- Optimal for Gaussian data
- May miss higher-order structureLimitations
| Limitation | Description | Solution |
|---|---|---|
| Linear only | Can't capture curves | Kernel PCA, autoencoders |
| Variance ≠ importance | Noisy features dominate | Feature scaling, selection |
| Sensitive to scale | Large-scale features dominate | Standardize first |
| No interpretability | PCs are linear combinations | Sparse PCA, NMF |
| Global structure | Ignores local neighborhoods | t-SNE, UMAP |
4.2.3 Singular Value Decomposition (SVD)
Matrix factorization that generalizes eigendecomposition.
Definition
Any matrix X (n × d) can be decomposed as:
X = U * Σ * V^T
Where:
- U: n × n orthogonal (left singular vectors)
- Σ: n × d diagonal (singular values σ_1 >= σ_2 >= ...)
- V: d × d orthogonal (right singular vectors)Visualization:
X = U * Σ * V^T
(n × d) (n × n) (n × d) (d × d)
┌─────┐ ┌─────┐ ┌─────────┐ ┌─────┐
│ │ │ │ │σ1 │ │ │
│ │ = │ │ × │ σ2 │ × │ │
│ │ │ │ │ σ3 │ └─────┘
└─────┘ └─────┘ │ ...│
└─────────┘Truncated SVD (Low-Rank Approximation)
X ≈ U_k * Σ_k * V_k^T
Keep only top k singular values/vectors
Best rank-k approximation (Eckart-Young theorem)
Error = sum(σ_i^2 for i > k)Applications:
- Dimensionality reduction (like PCA)
- Matrix completion (recommendations)
- Image compression
- Latent semantic analysis (text)
- Noise reductionSVD vs PCA
| Aspect | PCA | SVD |
|---|---|---|
| Input | Centered data | Any matrix |
| Computes | Eigenvectors of X^T*X | Full decomposition |
| Numerical stability | Can be unstable | More stable |
| Sparse data | Needs dense covariance | Works directly |
| Relationship | PCA uses SVD internally | More general |
Connection:
If X is centered:
- V from SVD = eigenvectors of X^T*X (principal components)
- σ_i^2 / (n-1) = eigenvalues of covariance matrix4.2.4 t-SNE (t-Distributed Stochastic Neighbor Embedding)
Non-linear method for visualization that preserves local structure.
Intuition
High-dimensional: 2D embedding:
Points A, B close → A, B close
Points A, C far → A, C far (but distances not preserved)
Focus: Preserve NEIGHBORHOODS, not exact distancesAlgorithm
Step 1: Compute pairwise similarities in high-D
p_j|i = exp(-||x_i - x_j||^2 / 2σ_i^2) / sum_k exp(-||x_i - x_k||^2 / 2σ_i^2)
p_ij = (p_j|i + p_i|j) / 2n
Gaussian kernel: nearby points have high probability
σ_i chosen to achieve target perplexityStep 2: Initialize low-D embedding
y_i ~ N(0, 0.01) for each pointStep 3: Compute similarities in low-D
q_ij = (1 + ||y_i - y_j||^2)^(-1) / sum_{k≠l} (1 + ||y_k - y_l||^2)^(-1)
Student t-distribution (heavy tails)
Allows moderate distances in high-D to become larger in low-DStep 4: Minimize KL divergence
KL(P || Q) = sum_ij p_ij * log(p_ij / q_ij)
Gradient descent on y_i positionsWhy t-Distribution?
Gaussian in low-D: t-Distribution in low-D:
Crowding problem! Heavy tails solve it!
High-D: many "moderately t-dist allows moderate distances
close" neighbors to spread out more
●●●●●●●●● ● ● ● ● ●
(crowded) (spread out)Perplexity
Perplexity ≈ effective number of neighbors
Perplexity = 2^H(P_i) where H = entropy
Typical values: 5-50
- Low perplexity: focus on very local structure
- High perplexity: consider more neighbors
Rule of thumb: perplexity < n/3Hyperparameters
| Parameter | Effect | Typical Values |
|---|---|---|
| perplexity | Neighborhood size | 5-50 |
| learning_rate | Step size | 10-1000 |
| n_iter | Iterations | 1000+ |
| early_exaggeration | Initial clustering | 12 (default) |
Limitations
1. Non-deterministic
- Random initialization → different results
- Run multiple times
2. Doesn't preserve global structure
- Distances between clusters meaningless
- Only local neighborhoods preserved
3. Slow: O(n^2) or O(n log n) with approximations
- Not suitable for very large datasets
4. Can't embed new points
- Must rerun on full dataset
- No out-of-sample extension
5. Sensitive to hyperparameters
- Perplexity affects results significantly4.2.5 UMAP (Uniform Manifold Approximation and Projection)
Faster alternative to t-SNE with better global structure preservation.
Key Differences from t-SNE
| Aspect | t-SNE | UMAP |
|---|---|---|
| Speed | O(n^2) or O(n log n) | O(n^1.14) |
| Global structure | Poor | Better |
| Theory | Probability divergence | Topological |
| New points | Can't embed | Can transform |
| Deterministic | No | More consistent |
Algorithm Overview
1. Build fuzzy simplicial complex (graph) in high-D
- k-nearest neighbor graph
- Edge weights based on distance
2. Initialize low-D embedding
3. Optimize low-D to match high-D graph structure
- Cross-entropy loss (not KL divergence)
- Attractive and repulsive forcesHyperparameters
| Parameter | Effect | Typical Values |
|---|---|---|
| n_neighbors | Local vs global | 5-50 |
| min_dist | How tight clusters are | 0.0-0.99 |
| metric | Distance function | euclidean, cosine |
n_neighbors:
- Small: fine local structure, may fragment
- Large: broader structure, may merge clusters
min_dist:
- Small (0.0): tight clusters, may overlap
- Large (0.5): spread out, preserves topology4.2.6 Autoencoders
Neural networks for non-linear dimensionality reduction.
Architecture
Input Encoder Latent Decoder Output
(d dim) (compress) (k dim) (expand) (d dim)
x ──→ [Dense] ──→ [Dense] ──→ z ──→ [Dense] ──→ [Dense] ──→ x̂
(512) (128) (32) (128) (512)
↑
Bottleneck
(compressed representation)Training
Loss = ||x - x̂||^2 (reconstruction error)
Minimize: Learn to compress and reconstruct
If reconstruction is good with small z:
→ z captures essential information
→ z is a good low-dimensional representationTypes of Autoencoders
Vanilla Autoencoder:
- Simple encoder-decoder
- Deterministic latent space
- May learn identity if too powerfulDenoising Autoencoder:
- Add noise to input: x̃ = x + noise
- Train to reconstruct clean x from x̃
- Learns robust featuresSparse Autoencoder:
- Add sparsity penalty on latent z
- Loss = reconstruction + λ * sparsity(z)
- Learns sparse, interpretable featuresVariational Autoencoder (VAE):
- Probabilistic: z ~ N(μ, σ) learned from x
- Loss = reconstruction + KL(q(z|x) || p(z))
- Smooth latent space, can generate new samplesAutoencoder vs PCA
| Aspect | PCA | Autoencoder |
|---|---|---|
| Transformation | Linear | Non-linear |
| Optimality | Global optimum | Local optimum |
| Computation | Fast (SVD) | Slow (training) |
| Flexibility | Fixed | Arbitrary architecture |
| Interpretability | Eigenvectors | Black box |
Linear autoencoder (no activation) ≈ PCA
Non-linear autoencoder > PCA for complex data4.2.7 Other Methods
Kernel PCA
Apply PCA in kernel-induced feature space
1. Compute kernel matrix K_ij = k(x_i, x_j)
2. Center kernel matrix
3. Eigendecomposition of K
4. Project using kernel trick
Captures non-linear structure
Same kernels as SVM: RBF, polynomialLinear Discriminant Analysis (LDA)
Supervised dimensionality reduction
Maximize: between-class variance / within-class variance
J(w) = (w^T * S_B * w) / (w^T * S_W * w)
Where:
- S_B = between-class scatter matrix
- S_W = within-class scatter matrix
Projects to at most (C-1) dimensions (C = classes)PCA vs LDA:
PCA: Unsupervised, maximize variance
LDA: Supervised, maximize class separation
PCA: LDA:
●●● ●●●
●●● ○○○ ●●● ○○○
●●● ○○○ ●●● ○○○
↓ ↓
●●●●●●○○○○○○ ●●●●●● ○○○○○○
(mixed) (separated)Non-negative Matrix Factorization (NMF)
X ≈ W * H
Where X, W, H >= 0 (all non-negative)
- W: basis vectors (d × k)
- H: coefficients (k × n)
Interpretable: additive parts-based representation
Use case: topic modeling, image decompositionQuestions & Answers
⭐ Q1: What are methods for reducing dimensionality in a dataset, and how do they work?
Answer:
Linear Methods:
| Method | How it Works | Use Case |
|---|---|---|
| PCA | Find orthogonal directions of max variance | General purpose, preprocessing |
| SVD | Matrix factorization X = UΣV^T | Sparse data, recommendations |
| LDA | Maximize class separation (supervised) | Classification preprocessing |
| NMF | Non-negative factorization | Interpretable features, topics |
Non-linear Methods:
| Method | How it Works | Use Case |
|---|---|---|
| t-SNE | Preserve local neighborhoods via KL divergence | Visualization (2D/3D) |
| UMAP | Preserve topological structure | Visualization, faster than t-SNE |
| Kernel PCA | PCA in kernel space | Non-linear patterns |
| Autoencoders | Neural network compression | Complex non-linear, deep learning |
| Isomap | Preserve geodesic distances | Manifold learning |
Feature Selection (not transformation):
| Method | How it Works |
|---|---|
| Filter | Score features independently (correlation, MI) |
| Wrapper | Search subsets using model performance |
| Embedded | Feature selection during training (L1, trees) |
Choosing a Method:
Need visualization?
→ t-SNE or UMAP
Linear relationships sufficient?
→ PCA (fast, interpretable)
Have labels?
→ LDA (supervised)
Complex non-linear patterns?
→ Autoencoders or Kernel PCA
Sparse/non-negative data?
→ NMF
Very large dataset?
→ Randomized PCA, UMAP⭐ Q2: How does PCA work? What are its assumptions?
Answer:
How PCA Works:
1. Center data: subtract mean from each feature
2. Compute covariance matrix: C = X^T * X / (n-1)
3. Find eigenvectors/eigenvalues of C
- Eigenvectors = principal component directions
- Eigenvalues = variance along each direction
4. Sort by eigenvalue (descending)
5. Project data onto top k eigenvectors
Z = X * V_k (n × k result)Key Insight:
PC1 = direction of maximum variance
PC2 = direction of max variance orthogonal to PC1
...and so on
Each PC captures decreasing amount of varianceAssumptions:
| Assumption | Implication |
|---|---|
| Linearity | Only captures linear relationships |
| Variance = importance | High-variance directions are meaningful |
| Orthogonality | Components are uncorrelated |
| Large sample size | Covariance estimates are reliable |
| Continuous features | Categorical needs encoding |
When Assumptions Fail:
Non-linear data:
●●●●●
●●●●●
●●●●●
PCA finds wrong direction!
→ Use Kernel PCA or autoencoders
High-variance noise:
Feature with noise dominates PCs
→ Standardize features first
Categorical data:
Covariance not meaningful
→ Use MCA (Multiple Correspondence Analysis)Practical Tips:
# Always standardize for PCA
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
# Then apply PCA
from sklearn.decomposition import PCA
pca = PCA(n_components=0.95) # Keep 95% variance
X_reduced = pca.fit_transform(X_scaled)⭐ Q3: When would you use t-SNE vs PCA?
Answer:
Use PCA when:
1. Need to reduce dimensions for ML model
- PCA output can be used as features
- t-SNE output should NOT be used for ML
2. Want interpretable components
- PCA: linear combinations of original features
- t-SNE: no interpretable mapping
3. Need to transform new data
- PCA: pca.transform(X_new)
- t-SNE: must refit entire dataset
4. Large dataset
- PCA: O(min(n,d)^2 * max(n,d))
- t-SNE: O(n^2) or O(n log n)
5. Care about global structure
- PCA preserves global distances
- t-SNE only preserves local neighborhoodsUse t-SNE when:
1. Visualization is the goal
- t-SNE excels at 2D/3D visualization
- Reveals cluster structure
2. Data has non-linear structure
- t-SNE captures complex manifolds
- PCA misses non-linear patterns
3. Want to see local relationships
- t-SNE preserves neighborhoods
- Similar points stay together
4. Exploring high-dimensional data
- Word embeddings, image features
- Single-cell RNA sequencingComparison:
| Aspect | PCA | t-SNE |
|---|---|---|
| Type | Linear | Non-linear |
| Preserves | Global structure | Local structure |
| Speed | Fast | Slow |
| Deterministic | Yes | No |
| New data | Yes | No |
| Use for ML | Yes | No (visualization only) |
| Interpretable | Yes | No |
Visual Example:
Swiss Roll (3D manifold):
PCA projection: t-SNE projection:
●●●●●●●●●●● ●●●
●●●●●●●●●●● ●● ●●
●●●●●●●●●●● ●● ●●
(overlapping) ●●●●●●●●●
(unrolled!)Practical Advice:
1. Start with PCA for preprocessing
2. Use t-SNE/UMAP for visualization
3. Never use t-SNE output as ML features
4. For large data, try UMAP (faster, similar quality)Q4: Explain the relationship between PCA and SVD.
Answer:
SVD Decomposition:
X = U * Σ * V^T
Where:
- X: n × d data matrix
- U: n × n orthogonal (left singular vectors)
- Σ: n × d diagonal (singular values)
- V: d × d orthogonal (right singular vectors)Connection to PCA:
If X is centered (mean = 0):
Covariance matrix:
C = X^T * X / (n-1)
Substitute X = U * Σ * V^T:
C = (V * Σ * U^T) * (U * Σ * V^T) / (n-1)
= V * Σ^2 * V^T / (n-1)
This is eigendecomposition of C!
- V columns = eigenvectors of C = principal components
- Σ^2 / (n-1) = eigenvalues of C = variancesPractical Relationship:
| PCA Concept | SVD Equivalent |
|---|---|
| Principal components | Columns of V |
| Eigenvalues | σ_i^2 / (n-1) |
| Projected data | U * Σ (or X * V) |
| Explained variance | σ_i^2 / sum(σ^2) |
Why Use SVD for PCA?
1. Numerical stability
- SVD more stable than eigendecomposition
- Especially for ill-conditioned matrices
2. Efficiency for wide matrices (d >> n)
- SVD: O(n^2 * d)
- Covariance method: O(d^2 * n + d^3)
3. Sparse matrices
- SVD works directly on sparse X
- Covariance X^T*X becomes dense
4. Truncated computation
- Can compute only top k singular values
- sklearn uses randomized SVD for efficiencyQ5: What are the limitations of PCA?
Answer:
1. Linearity:
PCA only captures linear relationships
Non-linear structure: PCA result:
●●●●● ●●●●●●●●●●●●●
●●●●● (loses structure)
●●●●●
Solution: Kernel PCA, autoencoders, t-SNE2. Variance ≠ Importance:
High variance might be noise, not signal
Example: Feature with measurement error
has high variance but low information
Solution: Domain knowledge, feature selection3. Scale Sensitivity:
Features with larger scale dominate
Feature A: [0.1, 0.2, 0.3] (small scale)
Feature B: [100, 200, 300] (large scale)
PC1 ≈ Feature B direction
Solution: Standardize features (z-score)4. Orthogonality Constraint:
Real factors may not be orthogonal
Example: Height and weight are correlated
but neither is "more fundamental"
Solution: ICA, Factor Analysis5. No Interpretability:
PCs are linear combinations of all features
Hard to explain what PC1 "means"
Solution: Sparse PCA, feature selection6. Assumes Gaussian:
Optimal for Gaussian data
May miss higher-order structure
Solution: ICA for non-Gaussian7. Global Method:
Ignores local structure
Two nearby points may be far in PC space
Solution: t-SNE, UMAP, LLEQ6: How do autoencoders compare to PCA for dimensionality reduction?
Answer:
Comparison:
| Aspect | PCA | Autoencoder |
|---|---|---|
| Transformation | Linear | Non-linear |
| Optimality | Global optimum | Local optimum |
| Training | Closed-form (SVD) | Gradient descent |
| Speed | Fast | Slow |
| Flexibility | Fixed | Arbitrary architecture |
| Interpretability | Eigenvectors | Black box |
| Data requirements | Works with small data | Needs more data |
When Autoencoder Wins:
1. Non-linear relationships
Autoencoder can learn curves, manifolds
2. Complex data (images, text)
Deep architectures capture hierarchical features
3. Enough training data
Neural networks need data to generalizeWhen PCA Wins:
1. Linear relationships sufficient
PCA is optimal for linear
2. Small datasets
Autoencoders overfit
3. Need interpretability
PCA components are linear combinations
4. Computational constraints
PCA is much fasterKey Insight:
Linear autoencoder (no activation functions)
learns the same subspace as PCA!
Non-linearity is what makes autoencoders more powerful.Practical Workflow:
1. Try PCA first (baseline)
2. If PCA insufficient, try autoencoder
3. For images/text, go straight to deep autoencoders
4. Consider VAE if need generative capability