Angad Sandhu
Search
Browse
On this page

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 features

Goals of Dimensionality Reduction:

- Reduce storage and computation
- Remove noise and redundancy
- Enable visualization
- Improve model performance
- Feature extraction / representation learning

Types 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 features

4.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 variance

Mathematical 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 >= ... >= λ_d

Step 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, eigenvalues

Choosing 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 structure

Limitations

LimitationDescriptionSolution
Linear onlyCan't capture curvesKernel PCA, autoencoders
Variance ≠ importanceNoisy features dominateFeature scaling, selection
Sensitive to scaleLarge-scale features dominateStandardize first
No interpretabilityPCs are linear combinationsSparse PCA, NMF
Global structureIgnores local neighborhoodst-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 reduction

SVD vs PCA

AspectPCASVD
InputCentered dataAny matrix
ComputesEigenvectors of X^T*XFull decomposition
Numerical stabilityCan be unstableMore stable
Sparse dataNeeds dense covarianceWorks directly
RelationshipPCA uses SVD internallyMore general
Connection:
If X is centered:
- V from SVD = eigenvectors of X^T*X (principal components)
- σ_i^2 / (n-1) = eigenvalues of covariance matrix

4.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 distances

Algorithm

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 perplexity

Step 2: Initialize low-D embedding

y_i ~ N(0, 0.01) for each point

Step 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-D

Step 4: Minimize KL divergence

KL(P || Q) = sum_ij p_ij * log(p_ij / q_ij)

Gradient descent on y_i positions

Why 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/3

Hyperparameters

ParameterEffectTypical Values
perplexityNeighborhood size5-50
learning_rateStep size10-1000
n_iterIterations1000+
early_exaggerationInitial clustering12 (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 significantly

4.2.5 UMAP (Uniform Manifold Approximation and Projection)

Faster alternative to t-SNE with better global structure preservation.

Key Differences from t-SNE

Aspectt-SNEUMAP
SpeedO(n^2) or O(n log n)O(n^1.14)
Global structurePoorBetter
TheoryProbability divergenceTopological
New pointsCan't embedCan transform
DeterministicNoMore 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 forces

Hyperparameters

ParameterEffectTypical Values
n_neighborsLocal vs global5-50
min_distHow tight clusters are0.0-0.99
metricDistance functioneuclidean, 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 topology

4.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 representation

Types of Autoencoders

Vanilla Autoencoder:

- Simple encoder-decoder
- Deterministic latent space
- May learn identity if too powerful

Denoising Autoencoder:

- Add noise to input: x̃ = x + noise
- Train to reconstruct clean x from x̃
- Learns robust features

Sparse Autoencoder:

- Add sparsity penalty on latent z
- Loss = reconstruction + λ * sparsity(z)
- Learns sparse, interpretable features

Variational Autoencoder (VAE):

- Probabilistic: z ~ N(μ, σ) learned from x
- Loss = reconstruction + KL(q(z|x) || p(z))
- Smooth latent space, can generate new samples

Autoencoder vs PCA

AspectPCAAutoencoder
TransformationLinearNon-linear
OptimalityGlobal optimumLocal optimum
ComputationFast (SVD)Slow (training)
FlexibilityFixedArbitrary architecture
InterpretabilityEigenvectorsBlack box
Linear autoencoder (no activation) ≈ PCA
Non-linear autoencoder > PCA for complex data

4.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, polynomial

Linear 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 decomposition

Questions & Answers

⭐ Q1: What are methods for reducing dimensionality in a dataset, and how do they work?

Answer:

Linear Methods:

MethodHow it WorksUse Case
PCAFind orthogonal directions of max varianceGeneral purpose, preprocessing
SVDMatrix factorization X = UΣV^TSparse data, recommendations
LDAMaximize class separation (supervised)Classification preprocessing
NMFNon-negative factorizationInterpretable features, topics

Non-linear Methods:

MethodHow it WorksUse Case
t-SNEPreserve local neighborhoods via KL divergenceVisualization (2D/3D)
UMAPPreserve topological structureVisualization, faster than t-SNE
Kernel PCAPCA in kernel spaceNon-linear patterns
AutoencodersNeural network compressionComplex non-linear, deep learning
IsomapPreserve geodesic distancesManifold learning

Feature Selection (not transformation):

MethodHow it Works
FilterScore features independently (correlation, MI)
WrapperSearch subsets using model performance
EmbeddedFeature 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 variance

Assumptions:

AssumptionImplication
LinearityOnly captures linear relationships
Variance = importanceHigh-variance directions are meaningful
OrthogonalityComponents are uncorrelated
Large sample sizeCovariance estimates are reliable
Continuous featuresCategorical 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 neighborhoods

Use 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 sequencing

Comparison:

AspectPCAt-SNE
TypeLinearNon-linear
PreservesGlobal structureLocal structure
SpeedFastSlow
DeterministicYesNo
New dataYesNo
Use for MLYesNo (visualization only)
InterpretableYesNo

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 = variances

Practical Relationship:

PCA ConceptSVD Equivalent
Principal componentsColumns of V
Eigenvaluesσ_i^2 / (n-1)
Projected dataU * Σ (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 efficiency

Q5: 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-SNE

2. Variance ≠ Importance:

High variance might be noise, not signal

Example: Feature with measurement error
has high variance but low information

Solution: Domain knowledge, feature selection

3. 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 Analysis

5. No Interpretability:

PCs are linear combinations of all features
Hard to explain what PC1 "means"

Solution: Sparse PCA, feature selection

6. Assumes Gaussian:

Optimal for Gaussian data
May miss higher-order structure

Solution: ICA for non-Gaussian

7. Global Method:

Ignores local structure
Two nearby points may be far in PC space

Solution: t-SNE, UMAP, LLE

Q6: How do autoencoders compare to PCA for dimensionality reduction?

Answer:

Comparison:

AspectPCAAutoencoder
TransformationLinearNon-linear
OptimalityGlobal optimumLocal optimum
TrainingClosed-form (SVD)Gradient descent
SpeedFastSlow
FlexibilityFixedArbitrary architecture
InterpretabilityEigenvectorsBlack box
Data requirementsWorks with small dataNeeds 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 generalize

When 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 faster

Key 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

Browse the library