UNIT 10 Machine Learning & Applied AI Track

Dimensionality Reduction & Manifold Learning

Mathematical foundations, spectral variance decomposition, supervised discriminant projections, and non-linear manifold embeddings: PCA, LDA, t-SNE, and UMAP.

01

The Need for Reduction & The Curse of Dimensionality

In modern machine learning, datasets frequently span hundreds to millions of features—from genomic sequencing matrices (D > 20,000) to high-resolution imagery and LLM latent embeddings (D > 4,096). As the feature dimensionality D expands, Euclidean geometry exhibits pathological behaviors termed the Curse of Dimensionality (Bellman, 1961):

1. Exponential Volume Explosion

The volume of a unit hypercube is V = 1^D. If we partition each axis into k bins, the space divides into k^D cells. To maintain constant data density, sample size N must scale exponentially: N propto O(k^D). Real-world datasets become vanishingly sparse.

2. Distance Concentration

In high dimensions, the contrast between the nearest neighbor distance D min and the farthest neighbor distance D max vanishes relative to the distance itself:

Formulation:
limD → infty (D max - D min / D min) → 0

All points become essentially equidistant from one another.

3. The Hubness Phenomenon

Certain data points ("hubs") emerge that unintentionally become the nearest neighbors to a disproportionately large fraction of the entire dataset, severely degrading nearest-neighbor classifiers (k-NN) and clustering trees.

System Architecture • Impact of Dimensionality Reduction
High-D Input
Raw Feature Space (D gg 100)
Multicollinearity, high computational complexity O(N D^2), extreme variance, and model overfitting.
➔
Projection Engine
Manifold Extraction
Compress D dimensions onto intrinsic subspace d ll D preserving variance, class margins, or topological neighborhoods.
➔
Optimized Space
Latent Representation (d)
Accelerated inference, eliminated collinearity, improved generalization, and direct 2D/3D visual interpretability.
02

Feature Selection versus Feature Reduction (Extraction)

Machine learning practitioners must carefully distinguish between Feature Selection and Feature Reduction (Extraction):

Evaluation Dimension Feature Selection (Subset Search) Feature Reduction / Extraction (Projection)
Mathematical Operation Masking / Filtering: Selects a subset S subset of {x_1, dots, x_D } without modifying the underlying coordinate values. Functional Mapping: Transforms raw input x in R^D into a new latent vector z = f(x) in R^d where d < D.
Interpretability High: Retains original physical units and semantic meaning (e.g., Patient_Age, Monthly_Income). Low to Moderate: Synthesizes composite linear or non-linear combinations (e.g., z_1 = 0.54 x_1 - 0.32 x_2 + 0.18 x_3).
Information Loss Discards unselected features entirely; risk of eliminating subtle non-linear interactions. Retains global variance or neighborhood topology spread across all original features into condensed principal axes.
Primary Algorithms Filter methods (ANOVA F-test, Mutual Info), Wrapper methods (RFE), Embedded methods (Lasso L_1 regularization, Tree feature importances). PCA, SVD, Factor Analysis, Linear Discriminant Analysis (LDA), Multidimensional Scaling (MDS), t-SNE, UMAP.
03

Principal Component Analysis (PCA) & Spectral Steps

Principal Component Analysis (PCA) is an unsupervised linear transformation technique that identifies orthogonal axes—termed Principal Components—along which the variance of the data is maximized. It constructs a new coordinate system where feature covariance is zero (complete decorrelation).

Step-by-Step Algorithmic Derivation

  1. Step 1: Standardization & Mean-Centering: Because PCA is variance-driven, variables with large numerical magnitudes dominate principal axes. Data must be zero-centered (and standardized to unit variance):
    Formulation: Formulation: Xstd = (X - μ / σ) quad such that quad E[X] = 0, quad Var(x_j) = 1
  2. Step 2: Covariance Matrix Computation: Compute the sample covariance matrix Σ in RD × D, capturing all pairwise linear relationships:
    Formulation: Formulation: Σ = (1 / N - 1) Xstd^T Xstd
  3. Step 3: Spectral Eigenvalue Decomposition: Compute the eigenvalues λ_i and corresponding eigenvectors v_i satisfying the characteristic equation:
    Formulation: Formulation: Σ v_i = λ_i v_i quad ⇔ quad (Σ - λ_i I) v_i = 0
    Every eigenvector v_i in R^D represents an orthogonal principal direction; its eigenvalue λ_i equals the exact variance of the data projected onto that axis.
  4. Step 4: Sorting & Projection Matrix Assembly: Sort the eigenvalues in descending order (λ_1 ≥ λ_2 ≥ dots ≥ λ_D ≥ 0). Select the top d eigenvectors to form the transformation matrix W_d = [v_1, v_2, dots, v_d] in RD × d.
  5. Step 5: Latent Subspace Projection: Project the original N × D data matrix onto the d-dimensional subspace:
    Formulation: Formulation: Z = Xstd W_d in RN × d
SVD (Singular Value Decomposition) Equivalence
In production systems (including Scikit-Learn), PCA is rarely computed via X^T X due to numerical instability and floating-point round-off errors. Instead, it utilizes Singular Value Decomposition (SVD) directly on centered matrix X:
Formulation: X = U S V^T
Where right singular vectors V are the eigenvectors of X^T X, and singular values relate to eigenvalues via λ_i = (s_i^2 / N - 1).
04

Explained Variance, Cumulative Variance & Scree Plots

The total variance of the standardized dataset equals the trace of the covariance matrix, which is the sum of all eigenvalues: Total Var = Sum i=1^D λ_i = D.

Individual Explained Variance Ratio

The proportion of total system variance captured by the i-th principal component:

Formulation:
EVR_i = (λ_i / Sum j=1^D λ_j)

Cumulative Explained Variance

The cumulative fraction of information retained by retaining the first d components:

Formulation:
CEV_d = (Sum i=1^d λ_i / Sum j=1^D λ_j)

Heuristics for Retaining Components

05

Linear Discriminant Analysis (LDA): Supervised Reduction

While PCA is unsupervised (ignoring class labels and seeking maximum overall variance), Linear Discriminant Analysis (LDA) is a supervised dimensionality reduction technique. LDA maximizes class separability by identifying linear combinations of features that maximize between-class variance while simultaneously minimizing within-class variance.

Between-Class Scatter (S_B)

Measures the distance between the mean vectors of individual classes μ_c and the global dataset mean μ:

Formulation:
S_B = Sum c=1^C N_c (μ_c - μ)(μ_c - μ)^T

Within-Class Scatter (S_W)

Measures the internal dispersion and variance of samples within their respective class centroids:

Formulation:
S_W = Sum c=1^C Sum x in C_c (x - μ_c)(x - μ_c)^T

Fisher's Criterion & Generalized Eigensystem

Fisher's criterion maximizes the Rayleigh quotient:

Formulation: Formulation: J(w) = (w^T S_B w / w^T S_W w)

Taking the gradient with respect to w and setting it to zero yields the Generalized Eigenvalue Problem:

Formulation: Formulation: S_W-1 S_B w = λ w
The Rank Constraint on LDA Components
Because S_B is formed by the sum of C rank-1 outer product matrices of class centroids constrained by the global mean (Sum N_c (μ_c - μ) = 0), its rank is at most C - 1. Consequently, LDA can produce at most C - 1 linear discriminants. For binary classification (C=2), data can only be projected onto a 1-dimensional line.
06

Non-Linear Manifold Learning: t-SNE & UMAP

Linear methods (PCA, LDA) project data onto flat hyperplanes. When datasets inhabit curved, non-linear manifolds (e.g., Swiss rolls or high-dimensional single-cell RNA clusters), linear projections cause distant folds to overlap catastrophically. Non-linear manifold learning preserves local geometric neighborhoods.

1. t-SNE (t-Distributed Stochastic Neighbor Embedding)

Developed by van der Maaten and Hinton (2008), t-SNE converts Euclidean distances between data points into conditional probabilities that represent affinities:

2. UMAP (Uniform Manifold Approximation & Projection)

Introduced by McInnes et al. (2018), UMAP is grounded in Riemannian geometry and algebraic topology:

Theoretical Foundations

UMAP assumes the data lies on a connected Riemannian manifold with locally constant metric. It constructs a fuzzy simplicial set representation of the high-dimensional data, enforcing local connectivity by setting distance to nearest neighbors to zero.

Engineering Advantages Over t-SNE

  • Global Topology Preservation: Preserves global cluster-to-cluster macro-distances significantly better than t-SNE.
  • Scalability: Scales as O(N log N) or O(N) using nearest-neighbor descent, orders of magnitude faster than standard t-SNE (O(N^2)).
  • Inference Projection: Learns a non-parametric mapping that supports transforming new unseen out-of-sample data points.
Dimension Reduction Algorithm Learning Paradigm Geometric Nature Preservation Target Supports Inference on New Test Points?
PCA Unsupervised Linear Orthogonal Maximum Global Variance Yes (z = x W)
LDA Supervised Linear Discriminant Between-Class Separability Yes (z = x WLDA)
t-SNE Unsupervised Non-linear Manifold Local Probabilistic Neighborhoods No (transductive only)
UMAP Unsupervised / Semi-Supervised Non-linear Fuzzy Simplex Local & Macro-Global Topology Yes (approximate embedding projection)
07

Verified Python Production Reduction Pipeline

The following self-contained script synthesizes a high-dimensional multiclass dataset (N=1,200, D=30) and benchmarks PCA variance decomposition, supervised LDA class compression, and t-SNE non-linear 2D projection.

dimensionality_reduction_pipeline.py
# =====================================================================
# DevAscent Academy: Dimensionality Reduction & Manifold Learning Pipeline
# Requires: numpy, pandas, scikit-learn
# =====================================================================

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.manifold import TSNE
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

def execute_reduction_benchmark():
    # -----------------------------------------------------------------
    # 1. Synthesize High-Dimensional Multiclass Data (N=1200, D=30, C=3)
    # -----------------------------------------------------------------
    X_raw, y = make_classification(
        n_samples=1200,
        n_features=30,
        n_informative=12,
        n_redundant=10,
        n_repeated=0,
        n_classes=3,
        n_clusters_per_class=2,
        random_state=42
    )

    X_train, X_test, y_train, y_test = train_test_split(
        X_raw, y, test_size=0.25, random_state=42, stratify=y
    )

    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)

    print(f"[Dataset] Features: {X_train.shape[1]} | Samples: {X_train.shape[0]} train, {X_test.shape[0]} test")

    # Baseline Classifier on Raw 30 Dimensions
    clf_baseline = LogisticRegression(max_iter=1000, random_state=42)
    clf_baseline.fit(X_train_scaled, y_train)
    acc_baseline = accuracy_score(y_test, clf_baseline.predict(X_test_scaled))
    print(f"[Baseline] 30-D Raw Feature Space Accuracy: {acc_baseline * 100:.2f}%")

    # -----------------------------------------------------------------
    # 2. Principal Component Analysis (Spectral Variance Decomposition)
    # -----------------------------------------------------------------
    print("\n--- [Phase 1] Principal Component Analysis (PCA) ---")
    pca_full = PCA().fit(X_train_scaled)
    evr = pca_full.explained_variance_ratio_
    cev = np.cumsum(evr)

    # Determine dimensions for 85% and 95% variance
    d_85 = int(np.argmax(cev >= 0.85) + 1)
    d_95 = int(np.argmax(cev >= 0.95) + 1)

    print(f"Top 5 Individual Component Variances: {[round(float(v), 4) for v in evr[:5]]}")
    print(f"Components required for 85% Variance: {d_85} of 30")
    print(f"Components required for 95% Variance: {d_95} of 30")

    # Fit Optimal PCA (Retaining 85% variance)
    pca_optimal = PCA(n_components=d_85, random_state=42)
    X_train_pca = pca_optimal.fit_transform(X_train_scaled)
    X_test_pca = pca_optimal.transform(X_test_scaled)

    clf_pca = LogisticRegression(max_iter=1000, random_state=42)
    clf_pca.fit(X_train_pca, y_train)
    acc_pca = accuracy_score(y_test, clf_pca.predict(X_test_pca))
    print(f"PCA ({d_85}-D Subspace) Downstream Accuracy: {acc_pca * 100:.2f}%")

    # -----------------------------------------------------------------
    # 3. Linear Discriminant Analysis (Supervised Separation)
    # -----------------------------------------------------------------
    print("\n--- [Phase 2] Linear Discriminant Analysis (LDA) ---")
    # For C=3 classes, max components = C - 1 = 2
    lda = LDA(n_components=2)
    X_train_lda = lda.fit_transform(X_train_scaled, y_train)
    X_test_lda = lda.transform(X_test_scaled)

    clf_lda = LogisticRegression(max_iter=1000, random_state=42)
    clf_lda.fit(X_train_lda, y_train)
    acc_lda = accuracy_score(y_test, clf_lda.predict(X_test_lda))
    print(f"LDA (2-D Projection) Downstream Accuracy: {acc_lda * 100:.2f}%")
    print(f"LDA Explained Variance Ratio (C-1=2): {[round(float(v), 4) for v in lda.explained_variance_ratio_]}")

    # -----------------------------------------------------------------
    # 4. t-SNE Non-Linear Manifold Embedding (Visualization Subspace)
    # -----------------------------------------------------------------
    print("\n--- [Phase 3] t-SNE Manifold Visualization Embedding ---")
    tsne = TSNE(n_components=2, perplexity=35, random_state=42, max_iter=1000)
    X_tsne_2d = tsne.fit_transform(X_train_scaled[:400])
    print(f"Successfully projected 400 high-D points to 2D manifold embedding.")
    print(f"t-SNE Divergence Loss (Kullback-Leibler): {round(float(tsne.kl_divergence_), 4)}")

    # -----------------------------------------------------------------
    # 5. Reduction Summary Matrix
    # -----------------------------------------------------------------
    summary_df = pd.DataFrame([
        {'Method': 'Raw Uncompressed', 'Dimensions': 30, 'Test_Accuracy': f"{acc_baseline*100:.2f}%", 'Type': 'Baseline'},
        {'Method': f'PCA (85% Var)', 'Dimensions': d_85, 'Test_Accuracy': f"{acc_pca*100:.2f}%", 'Type': 'Unsupervised Linear'},
        {'Method': 'LDA (C - 1)', 'Dimensions': 2, 'Test_Accuracy': f"{acc_lda*100:.2f}%", 'Type': 'Supervised Linear'},
        {'Method': 't-SNE (2D)', 'Dimensions': 2, 'Test_Accuracy': 'Visual Only', 'Type': 'Non-linear Manifold'}
    ])
    print("\n" + summary_df.to_string(index=False))

if __name__ == '__main__':
    execute_reduction_benchmark()
08

Engineering Viva Voce & Technical Interviews

Q1 • Data Scaling Why is feature standardization (μ=0, σ=1) mathematically mandatory before computing PCA?
PCA maximizes variance along orthogonal directions (max w^T Σ w). If features are measured on different numerical scales (e.g., Annual Income in dollars [20,000--200,000] vs. Age in years [18--80]), the variable with the larger numerical spread will artificially exhibit thousands of times more variance purely due to unit choice. Without standardization, the first principal component will align almost exclusively with the high-magnitude variable, completely ignoring correlated variations in smaller-magnitude features.
Q2 • PCA Orthogonality Prove that the principal components derived from PCA are mutually uncorrelated.
Let Z = X W be the projected coordinates, where W = [v_1, dots, v_D] is the matrix of eigenvectors of covariance matrix Σ. The covariance matrix of the transformed data is:
Formulation: Σ_Z = (1 / N - 1) Z^T Z = (1 / N - 1) (X W)^T (X W) = W^T ( (X^T X / N - 1) right) W = W^T Σ W
Because Σ is a real symmetric matrix, its eigenvectors are orthonormal (W^T W = I), and spectral decomposition yields Σ = W Lambda W^T. Substituting this gives:
Formulation: Σ_Z = W^T (W Lambda W^T) W = (W^T W) Lambda (W^T W) = I Lambda I = Lambda
Because Lambda is a purely diagonal matrix of eigenvalues, all off-diagonal covariances are exactly zero: Cov(z_i, z_j) = 0 for all i ≠ j.
Q3 • PCA vs LDA Under what circumstances does PCA preserve features that hinder downstream classification, while LDA successfully separates them?
PCA identifies axes of maximum total variance regardless of class membership. If the variance between classes is smaller than the internal variance within classes (e.g., two elongated parallel cigar-shaped clusters), PCA will project data along the direction of the elongated cigars (maximizing spread), causing the two classes to completely overlap. LDA directly maximizes between-class variance relative to within-class variance ((w^T S_B w / w^T S_W w)), choosing an axis perpendicular to the cigars that cleanly separates the class distributions.
Q4 • LDA Dimension Limit Why is Linear Discriminant Analysis mathematically limited to producing at most C - 1 dimensions?
The transformation directions in LDA are eigenvectors of the matrix S_W-1 S_B. The between-class scatter matrix is defined as S_B = Sum c=1^C N_c (μ_c - μ)(μ_c - μ)^T. This is a sum of C vectors (μ_c - μ). Because the global mean is a linear combination of class means (μ = Sum (N_c / N) μ_c), these C vectors are linearly dependent, spanning at most a (C - 1)-dimensional subspace. Therefore, rank(S_B) ≤ C - 1, meaning there are at most C - 1 non-zero eigenvalues and corresponding discriminants.
Q5 • Crowding Problem in t-SNE What is the "crowding problem" in high-to-low dimensional projection, and how does t-SNE mathematically resolve it?
In a high-dimensional space R^D, the volume of a sphere scales as r^D. Ten equidistant points can easily reside in a 10D space around a central point. However, in a 2D projection space R^2, the available area scales only as r^2. Moderate distances cannot be faithfully accommodated without crowding all moderately distant points onto the cluster perimeter. t-SNE resolves this by using an asymmetric distribution pairing: a Gaussian distribution in the high-dimensional space (pij) and a heavy-tailed Student-t distribution with 1 degree of freedom (Cauchy distribution) in the low-dimensional space (qij propto (1 + y_i - y_j^2)-1). The heavy tails allow moderate-distance points to be pushed much farther apart in 2D space without incurring massive penalty.
Q6 • t-SNE Non-Inference Why can't you use t-SNE directly inside an inference pipeline to transform new incoming user feature vectors (i.e., why is there no `transform()` method)?
PCA and LDA learn explicit parametric projection matrices W such that new inference points can be transformed via matrix multiplication (znew = xnew W). In contrast, t-SNE is a transductive, non-parametric optimization algorithm. It optimizes the positions of points Y directly via gradient descent on the KL divergence over the entire dataset batch simultaneously. There is no mathematical functional mapping f: R^D → R^d generated. To embed a new test point, one would have to re-run the entire iterative optimization over the combined dataset.
Q7 • UMAP vs t-SNE What are the mathematical and computational reasons UMAP preserves global structure better and runs faster than t-SNE?
Computationally, t-SNE evaluates normalization terms across all pairwise point combinations (O(N^2)), whereas UMAP utilizes Approximate k-Nearest Neighbors (Nearest Neighbor Descent) and negative sampling, scaling at O(N log N). Mathematically, t-SNE minimizes KL divergence, which heavily penalizes placing nearby high-dimensional points far apart in low dimensions (pij large, qij small), but places almost zero penalty on placing distant points close together (pij ≈ 0). UMAP optimizes a fuzzy set cross-entropy loss that contains terms for both preservation of local neighbors and preservation of global non-neighbors, retaining macroscopic inter-cluster relationships.
Q8 • Feature Selection vs Extraction Under what regulatory or operational conditions must an engineer select Feature Selection over PCA?
Feature Selection is mandatory when: (1) Regulatory Auditing & Model Explainability (e.g., GDPR, Fair Lending, HIPAA): Regulators require knowing the exact impact of identifiable inputs (e.g., Debt-to-Income ratio). A PCA component z_1 = 0.4x_1 - 0.7x_2 + 0.1x_3 obfuscates causality. (2) Sensor/Data Ingestion Costs: In IoT and medical diagnostics, acquiring features costs money or battery power. Feature selection allows discarding unused sensors entirely, whereas PCA requires measuring all D original inputs to compute the linear projection.