Mathematical foundations, spectral variance decomposition, supervised discriminant projections, and non-linear manifold embeddings: PCA, LDA, t-SNE, and UMAP.
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):
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.
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:
limD → infty (D max - D min / D min) → 0
All points become essentially equidistant from one another.
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.
D gg 100)O(N D^2), extreme variance, and model overfitting.D dimensions onto intrinsic subspace d ll D preserving variance, class margins, or topological neighborhoods.d)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. |
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).
Formulation: Xstd = (X - μ / σ) quad such that quad E[X] = 0, quad Var(x_j) = 1Σ in RD × D, capturing all pairwise linear relationships:
Formulation: Σ = (1 / N - 1) Xstd^T Xstdλ_i and corresponding eigenvectors v_i satisfying the characteristic equation:
Formulation: Σ v_i = λ_i v_i quad ⇔ quad (Σ - λ_i I) v_i = 0v_i in R^D represents an orthogonal principal direction; its eigenvalue λ_i equals the exact variance of the data projected onto that axis.
λ_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.
N × D data matrix onto the d-dimensional subspace:
Formulation: Z = Xstd W_d in RN × dX^T X due to numerical instability and floating-point round-off errors. Instead, it utilizes Singular Value Decomposition (SVD) directly on centered matrix X:
X = U S V^TV are the eigenvectors of X^T X, and singular values relate to eigenvalues via λ_i = (s_i^2 / N - 1).
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.
The proportion of total system variance captured by the i-th principal component:
EVR_i = (λ_i / Sum j=1^D λ_j)
The cumulative fraction of information retained by retaining the first d components:
CEV_d = (Sum i=1^d λ_i / Sum j=1^D λ_j)
d such that CEV_d ≥ 0.90 or 0.95 (retaining 90--95 % of total system information).λ_i against component index i. Locate the point of inflection ("elbow") where the curve levels off into trivial random noise.Var=1), retain only components with λ_i > 1.0 (components that explain more variance than a single original variable).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.
S_B)
Measures the distance between the mean vectors of individual classes μ_c and the global dataset mean μ:
S_B = Sum c=1^C N_c (μ_c - μ)(μ_c - μ)^T
S_W)Measures the internal dispersion and variance of samples within their respective class centroids:
S_W = Sum c=1^C Sum x in C_c (x - μ_c)(x - μ_c)^T
Fisher's criterion maximizes the Rayleigh quotient:
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: S_W-1 S_B w = λ wS_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.
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.
Developed by van der Maaten and Hinton (2008), t-SNE converts Euclidean distances between data points into conditional probabilities that represent affinities:
pji = ( exp(-x_i - x_j^2 / 2σ_i^2) / Sum k ≠ i exp(-x_i - x_k^2 / 2σ_i^2)), quad pij = (pji + pij / 2N)
σ_i is determined dynamically via binary search to match a user-defined Perplexity (effective neighborhood size, typically 30--50).
d=2), points are mapped to y_i, y_j. To prevent moderate-distance points from crowding together into an indistinguishable clump, t-SNE uses a heavy-tailed Cauchy (Student-t with 1 DOF) distribution:
qij = ((1 + y_i - y_j^2)-1 / Sum k Sum l ≠ k (1 + y_k - y_l^2)-1)
y_i are positioned by minimizing the Kullback-Leibler divergence between high-dimensional distribution P and low-dimensional distribution Q via gradient descent:
Lt-SNE = DKL(P parallel Q) = Sum _i Sum _j pij log ( (pij / qij) right)
Introduced by McInnes et al. (2018), UMAP is grounded in Riemannian geometry and algebraic topology:
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.
O(N log N) or O(N) using nearest-neighbor descent, orders of magnitude faster than standard t-SNE (O(N^2)).| 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) |
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.
# =====================================================================
# 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()
μ=0, σ=1) mathematically mandatory before computing PCA?
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.
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:
Σ_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Σ is a real symmetric matrix, its eigenvectors are orthonormal (W^T W = I), and spectral decomposition yields Σ = W Lambda W^T. Substituting this gives:
Σ_Z = W^T (W Lambda W^T) W = (W^T W) Lambda (W^T W) = I Lambda I = LambdaLambda is a purely diagonal matrix of eigenvalues, all off-diagonal covariances are exactly zero: Cov(z_i, z_j) = 0 for all i ≠ j.
(w^T S_B w / w^T S_W w)), choosing an axis perpendicular to the cigars that cleanly separates the class distributions.
C - 1 dimensions?
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.
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.
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.
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.
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.