1. The Core Problem: Learning Without Labels in High-Dimensional Space #
Across Parts 2 through 6, every algorithm we built—from Logistic Regression and Kernel SVMs to Random Forests and XGBoost—depended on explicit ground-truth labels $y_i$. In real-world engineering and scientific pipelines, however, raw data usually arrives unlabeled and high-dimensional: millions of multi-channel sensor logs, gene expression profiles across 20,000 transcripts, or dense neural embeddings spanning thousands of dimensions.
Operating directly on raw, unlabeled, high-dimensional vectors introduces two severe bottlenecks:
- Structural Blindness: Without labels $y_i$, Empirical Risk Minimization cannot optimize prediction accuracy directly. Instead, the algorithm must discover latent geometry directly from the marginal distribution $P(X)$—grouping coherent subpopulations (clustering) or compressing redundant coordinates (dimensionality reduction).
- Geometric Collapse in High Dimensions: Intuitive 2D and 3D Euclidean geometry breaks down as feature count $d$ grows. Volumes concentrate in thin outer shells, pairwise distances become nearly indistinguishable, and sample requirements explode exponentially—a phenomenon Richard Bellman (1961) termed the Curse of Dimensionality.
To extract signal from high-dimensional unlabeled data, machine learning relies on three progressively richer families of methods:
- Probabilistic & Geometric Clustering: Partitioning data into discrete or overlapping latent groups (K-Means vs. Gaussian Mixture Models trained via the EM Algorithm).
- Linear Spectral Projections: Compressing correlated dimensions onto orthogonal variance-maximizing axes via PCA and Singular Value Decomposition (SVD)—the exact linear-algebraic foundation behind modern LLM parameter-efficient fine-tuning methods such as LoRA.
- Non-Linear Manifold Learning: Unfolding curved low-dimensional structures embedded inside high-dimensional spaces using neighborhood topology (t-SNE and UMAP).
2. Conceptual Intuition: Empty Hypercubes, Soft Ellipses, and Unrolling a Swiss Roll #
The Empty Hypercube (Curse of Dimensionality) #
Imagine placing 100 marbles evenly along a 1-meter line ($d = 1$): the spacing between neighboring marbles is just $1\,\text{cm}$. Now spread those exact same 100 marbles across a $1\,\text{m} \times 1\,\text{m}$ square ($d = 2$): they form a sparse $10 \times 10$ grid spaced $10\,\text{cm}$ apart. Spread them inside a $1\,\text{m}^3$ cube ($d = 3$): spacing jumps to $21.5\,\text{cm}$. By the time you reach $d = 100$ dimensions, a unit hypercube has $2^{100} \approx 1.27 \times 10^{30}$ corners—meaning even billions of data points sit virtually isolated in vast empty space.
Hard Voronoi Tiles vs. Soft Gaussian Ellipses (K-Means vs. GMM) #
Suppose two populations of points form elongated, tilted ellipses that partially overlap. K-Means assigns every point strictly to its nearest centroid using unweighted Euclidean distance, carving the space into rigid, straight-edged Voronoi cells that assume every cluster is a round sphere of identical radius. Gaussian Mixture Models (GMMs) replace hard walls with overlapping, tilted probabilistic bell curves—allowing each cluster to have its own elliptical covariance shape and assigning smooth posterior probabilities to ambiguous boundary points.
Unrolling a Swiss Roll (Linear vs. Non-Linear Reduction) #
Picture a 2D sheet of paper rolled tightly into a 3D spiral—a classic Swiss Roll. Two points sitting on adjacent layers of the spiral may be only millimeters apart in straight-line 3D Euclidean distance, yet centimeters apart if you walk along the surface of the paper. PCA acts like shining a flashlight onto a flat wall: it projects the 3D spiral linearly onto a 2D shadow, squashing different spiral layers right on top of each other. Manifold learning (t-SNE and UMAP) acts like carefully unrolling the paper flat onto a table—preserving local walking distances along the surface rather than straight-line shortcuts through empty ambient space.
3. The Curse of Dimensionality: Why Euclidean Geometry Collapses #
Before applying distance-based clustering or nearest-neighbor search in $\mathbb{R}^d$, three mathematical pathologies must be accounted for:
1. Volume Concentration in Outer Shells #
Consider a unit hypersphere of radius $r = 1$ inside a hypercube $[-1, 1]^d$ of side length $2$ in $\mathbb{R}^d$. The volume of the hypercube is $V_{\text{cube}}(d) = 2^d$, while the volume of the unit hypersphere is:
$$V_{\text{sphere}}(d) = \frac{\pi^{d/2}}{\Gamma\!\left(\frac{d}{2} + 1\right)}$$Because the Gamma function $\Gamma(d/2 + 1)$ grows factorially faster than $\pi^{d/2}$, the ratio $V_{\text{sphere}}(d) / V_{\text{cube}}(d) \to 0$ rapidly as $d$ increases—meaning almost all volume of a high-dimensional hypercube resides in its extreme corners.
Even inside the hypersphere itself, compute the fraction of volume contained within a thin outer crust of thickness $\epsilon \in (0, 1)$ near the surface ($1 - \epsilon \le \Vert{}x\Vert{}_2 \le 1$):
$$\frac{V_{\text{sphere}}(1) - V_{\text{sphere}}(1 - \epsilon)}{V_{\text{sphere}}(1)} = 1 - (1 - \epsilon)^d$$For $\epsilon = 0.05$ (the outer 5% of the radius), in $d = 2$ dimensions this shell holds $9.75\%$ of the area; in $d = 100$ dimensions, $1 - 0.95^{100} \approx 99.4\%$ of the entire volume sits compressed inside that thin outer skin.
2. Distance Concentration #
Beyer et al. (1999) proved a sobering theorem for high-dimensional nearest-neighbor search: under broad conditions on i.i.d. coordinates, the relative contrast between the farthest neighbor distance $D_{\max}(d)$ and nearest neighbor distance $D_{\min}(d)$ from any query point collapses to zero as dimensionality grows:
$$\lim_{d \to \infty} \mathbb{E}\!\left[ \frac{D_{\max}(d) - D_{\min}(d)}{D_{\min}(d)} \right] = 0$$When every point looks almost equidistant from every other point, raw Euclidean similarity loses discriminative power—making dimensionality reduction essential before downstream modeling.
4. Clustering: From Hard Voronoi Cells (K-Means) to Soft Gaussian Mixtures (EM) #
4.1 K-Means & Lloyd’s Algorithm #
Given unlabeled points $\{x_1, \dots, x_n\} \subset \mathbb{R}^d$ and a target cluster count $K$, K-Means partitions the dataset into $K$ disjoint sets $C_1, \dots, C_K$ with centroids $\mu_1, \dots, \mu_K$ by minimizing the Within-Cluster Sum of Squares (WCSS):
$$\min_{\{C_k\}, \{\mu_k\}} \; J_{\text{KMeans}} = \sum_{k=1}^{K} \sum_{x_i \in C_k} \Vert{}x_i - \mu_k\Vert{}_2^2$$Jointly optimizing discrete cluster assignments and continuous centroids is NP-hard. Lloyd’s Algorithm (1982) solves it via alternating coordinate descent:
- Assignment Step (E-like): Fix centroids $\{\mu_k\}$ and assign each point $x_i$ to its closest Euclidean centroid:
- Update Step (M-like): Fix assignments $\{z_i\}$ and recompute each centroid as the arithmetic mean of its assigned points:
Because both steps monotonically decrease (or maintain) $J_{\text{KMeans}} \ge 0$, Lloyd’s algorithm converges in a finite number of steps to a local minimum. Poor random centroid initialization can trap K-Means in bad local minima—which k-means++ (Arthur & Vassilvitskii, 2007) mitigates by sampling initial centroids sequentially with probability proportional to squared distance $D(x)^2$ from already chosen centers.
4.2 Gaussian Mixture Models (GMM) & The EM Algorithm #
K-Means implicitly assumes isotropic spherical clusters of equal variance and enforces hard $0/1$ assignments. Gaussian Mixture Models model the data density as a convex combination of $K$ multivariate Gaussian components:
$$p(x \mid \theta) = \sum_{k=1}^{K} \pi_k \, \mathcal{N}(x \mid \mu_k, \Sigma_k), \qquad \sum_{k=1}^{K} \pi_k = 1, \quad \pi_k \ge 0$$where $\theta = \{\pi_k, \mu_k, \Sigma_k\}_{k=1}^K$ collects the mixing weights, mean vectors, and full $d \times d$ covariance matrices.
Maximizing the log-likelihood directly hits a mathematical wall because the summation sits inside the logarithm:
$$\ln p(X \mid \theta) = \sum_{i=1}^{n} \ln \left( \sum_{k=1}^{K} \pi_k \, \mathcal{N}(x_i \mid \mu_k, \Sigma_k) \right)$$Setting derivatives to zero couples all parameters nonlinearly with no closed-form solution. Dempster, Laird, and Rubin (1977) solved this class of latent-variable problems with the Expectation–Maximization (EM) Algorithm:
-
E-Step (Posterior Responsibilities): Holding $\theta^{(t)}$ fixed, use Bayes’ Theorem to compute the soft posterior probability (“responsibility”) $\gamma_{ik} = P(z_i = k \mid x_i, \theta^{(t)})$ that component $k$ generated sample $x_i$:
$$\gamma_{ik} = \frac{\pi_k \, \mathcal{N}(x_i \mid \mu_k, \Sigma_k)}{\sum_{j=1}^{K} \pi_j \, \mathcal{N}(x_i \mid \mu_j, \Sigma_j)}$$ -
M-Step (Expected Complete-Data MLE): Holding responsibilities $\gamma_{ik}$ fixed, update every parameter using responsibility-weighted sufficient statistics (letting $N_k = \sum_{i=1}^n \gamma_{ik}$ be the effective number of points assigned to cluster $k$):
$$\mu_k^{(t+1)} = \frac{1}{N_k} \sum_{i=1}^{n} \gamma_{ik} x_i$$
By Jensen’s Inequality, each EM cycle maximizes a tight lower bound (the Evidence Lower Bound / ELBO) on $\ln p(X \mid \theta)$, ensuring that the true log-likelihood increases monotonically at every iteration until reaching a stationary point. (Notice that K-Means emerges as the degenerate limit of GMM when $\Sigma_k = \sigma^2 I$, $\pi_k = 1/K$, and $\sigma^2 \to 0$.)
5. Linear Dimensionality Reduction: PCA, SVD & The Bridge to LoRA #
5.1 Principal Component Analysis (PCA) #
Introduced by Karl Pearson (1901) and formalized algebraically by Harold Hotelling (1933), Principal Component Analysis (PCA) finds an orthogonal linear projection from $\mathbb{R}^d$ onto a lower-dimensional subspace $\mathbb{R}^r$ ($r \lt d$) that retains the maximum possible signal variance.
Assume the data matrix $X \in \mathbb{R}^{n \times d}$ is zero-centered ($\frac{1}{n}\sum_{i=1}^n x_i = 0$), with sample covariance matrix $S = \frac{1}{n} X^\top X$. Projecting samples onto a unit direction $u_1 \in \mathbb{R}^d$ ($\Vert{}u_1\Vert{}_2 = 1$) yields projected variance:
$$\operatorname{Var}(X u_1) = \frac{1}{n} \Vert{}X u_1\Vert{}_2^2 = u_1^\top S u_1$$Forming the Lagrangian $\mathcal{L}(u_1, \lambda_1) = u_1^\top S u_1 - \lambda_1(u_1^\top u_1 - 1)$ and setting $\nabla_{u_1}\mathcal{L} = 0$ yields the classic eigenvalue problem:
$$S u_1 = \lambda_1 u_1$$Because $S$ is symmetric and positive semi-definite, its eigenvectors $u_1, \dots, u_d$ form an orthonormal basis sorted by descending eigenvalues $\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d \ge 0$. Projecting onto the top-$r$ eigenvectors $W_r = [u_1, \dots, u_r] \in \mathbb{R}^{d \times r}$ simultaneously maximizes retained variance and minimizes squared reconstruction error $\Vert{}X - X W_r W_r^\top\Vert{}_F^2$.
5.2 Singular Value Decomposition (SVD) & Eckart–Young–Mirsky Theorem #
In numerical computing, forming $X^\top X$ explicitly squares the condition number $\kappa(X)$ and loses floating-point precision. Instead, PCA is computed directly via the Singular Value Decomposition (SVD) of the centered matrix $X$:
$$X = U \Sigma V^\top$$where $U \in \mathbb{R}^{n \times n}$ and $V \in \mathbb{R}^{d \times d}$ are orthogonal matrices ($U^\top U = I$, $V^\top V = I$), and $\Sigma = \operatorname{diag}(\sigma_1, \dots, \sigma_p)$ holds the non-negative singular values $\sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_p \ge 0$ ($p = \min(n, d)$).
Substituting $X = U \Sigma V^\top$ into the covariance matrix reveals the exact bridge between SVD and PCA:
$$S = \frac{1}{n} X^\top X = \frac{1}{n} V \Sigma^\top U^\top U \Sigma V^\top = V \left(\frac{\Sigma^2}{n}\right) V^\top$$- The right singular vectors $v_k$ (columns of $V$) are the exact principal component directions $u_k$.
- The eigenvalues of covariance are $\lambda_k = \sigma_k^2 / n$.
- The principal component scores are $Z = X V = U \Sigma$.
Furthermore, the Eckart–Young–Mirsky Theorem (1936) establishes a fundamental optimality result in linear algebra: among all matrices $B$ of rank at most $r$, the truncated SVD $X_r = \sum_{k=1}^{r} \sigma_k u_k v_k^\top = U_r \Sigma_r V_r^\top$ achieves the globally minimal reconstruction error in both Frobenius and spectral norms:
$$\min_{\operatorname{rank}(B) \le r} \Vert{}X - B\Vert{}_F = \Vert{}X - X_r\Vert{}_F = \sqrt{\sum_{k=r+1}^{p} \sigma_k^2}$$5.3 From Truncated SVD to LoRA in Large Language Models #
This low-rank spectral property directly underpins LoRA (Low-Rank Adaptation), introduced by Hu et al. (2021) for fine-tuning Large Language Models.
Fine-tuning a pre-trained weight matrix $W_0 \in \mathbb{R}^{d \times k}$ normally updates a full dense matrix $\Delta W \in \mathbb{R}^{d \times k}$ containing $d \times k$ trainable parameters—requiring massive GPU memory for optimizer states (such as AdamW’s $m_t$ and $v_t$ from Part 3). Building on findings by Aghajanyan et al. (2021) that task-specific adaptation updates reside in a remarkably low intrinsic dimension, Hu et al. (2021) constrained the weight update $\Delta W$ to a low-rank factorization:
$$W = W_0 + \Delta W = W_0 + \frac{\alpha}{r} B A, \qquad B \in \mathbb{R}^{d \times r}, \quad A \in \mathbb{R}^{r \times k}, \quad r \ll \min(d, k)$$The connection to Truncated SVD is direct:
- By Eckart–Young–Mirsky, any matrix $\Delta W$ whose singular value spectrum decays rapidly can be approximated accurately by a rank-$r$ outer-product sum $\sum_{i=1}^{r} \sigma_i u_i v_i^\top = B A$ (absorbing $\Sigma_r^{1/2}$ into $B$ and $A$).
- Rather than computing a full dense $\Delta W$ first and then compressing it via SVD, LoRA freezes $W_0$ and learns the low-rank basis matrices $A$ and $B$ directly via backpropagation—cutting trainable parameter counts and optimizer memory by up to 100×–1,000× while introducing zero extra inference latency (since $B A$ merges algebraically back into $W_0$ after training).

Figure 7. Left: PCA finds orthogonal axes of maximal variance. Right: Gaussian Mixture Models capture stretched clusters with full covariance ellipses where K-Means would assume spheres.
6. Non-Linear Manifold Learning: t-SNE and UMAP #
6.1 The Manifold Hypothesis #
Linear projections like PCA fail whenever data curves non-linearly—such as a folded Swiss roll or high-dimensional image/text representations. The Manifold Hypothesis posits that natural high-dimensional datasets do not fill $\mathbb{R}^d$ uniformly; instead, they lie concentrated near a smooth, curved low-dimensional manifold $\mathcal{M}$ of intrinsic dimension $m \ll d$.
To visualize or embed $\mathcal{M}$ in 2D or 3D without folding distant regions onto each other, non-linear manifold methods build a weighted nearest-neighbor graph in high-D space and optimize low-dimensional coordinates $\{y_1, \dots, y_n\}$ to preserve local neighborhood affinities.
6.2 t-SNE & Solving the Crowding Problem #
Proposed by Laurens van der Maaten and Geoffrey Hinton (2008), t-SNE (t-Distributed Stochastic Neighbor Embedding) models pairwise similarities as probability distributions:
-
High-Dimensional Gaussian Affinities: For each point $x_i$, measure conditional similarity to neighbor $x_j$ under a local Gaussian kernel whose bandwidth $\sigma_i$ is tuned via binary search to match a user-specified perplexity (effective number of local neighbors, typically 5 to 50), then symmetrize:
$$p_{j \mid i} = \frac{\exp\!\left(-\Vert{}x_i - x_j\Vert{}_2^2 / 2\sigma_i^2\right)}{\sum_{k \neq i} \exp\!\left(-\Vert{}x_i - x_k\Vert{}_2^2 / 2\sigma_i^2\right)}, \qquad p_{ij} = \frac{p_{j \mid i} + p_{i \mid j}}{2n}$$ -
The Crowding Problem & Heavy-Tailed Student-$t$ Kernel: Suppose a 10-dimensional ball contains many moderately distant neighbors. A 2D plane simply does not have enough surface area to place all of them at moderate distances without either crushing them together or pushing them absurdly far away. If low-dimensional similarities $q_{ij}$ also used a Gaussian kernel, moderately distant points in high-D would be pushed far apart in 2D, crushing tight clusters together at the center. t-SNE solves this by using a heavy-tailed Student-$t$ distribution with 1 degree of freedom (a Cauchy kernel) in the low-dimensional map:
$$q_{ij} = \frac{\big(1 + \Vert{}y_i - y_j\Vert{}_2^2\big)^{-1}}{\sum_{k \neq l} \big(1 + \Vert{}y_k - y_l\Vert{}_2^2\big)^{-1}}$$
Because $(1 + d^2)^{-1}$ decays algebraically rather than exponentially, moderately distant points in high-D can sit much farther apart in 2D while still matching $p_{ij}$, freeing space in the center for fine local structure. 3. Asymmetric KL Objective: t-SNE optimizes $\{y_i\}$ via gradient descent to minimize $D_{\text{KL}}(P \Vert{} Q) = \sum_{i \neq j} p_{ij} \ln \frac{p_{ij}}{q_{ij}}$. Notice the asymmetry: when $p_{ij}$ is large (true local neighbors) but $q_{ij}$ is small, the penalty is huge—forcing local neighbors together. When $p_{ij}$ is tiny (distant points), the penalty is negligible—meaning t-SNE does not reliably preserve global distances between separate clusters or relative cluster sizes (Wattenberg et al., 2016).
6.3 UMAP & Fuzzy Topological Representations #
Introduced by Leland McInnes, John Healy, and James Melville (2018), UMAP (Uniform Manifold Approximation and Projection) grounds manifold learning in Riemannian geometry and algebraic topology (fuzzy simplicial sets):
- Local Metric Normalization: Around each point $x_i$, UMAP subtracts the distance $\rho_i$ to its single nearest neighbor so every point connects to at least one neighbor with full weight $1$, then scales local distances by $\sigma_i$:
- Fuzzy Set Union: Instead of normalizing globally by $2n$, UMAP combines directed edge weights using probabilistic fuzzy set union:
- Fuzzy Cross-Entropy Loss: In low dimensions, UMAP parameterizes similarity via $v_{ij} = \big(1 + a \Vert{}y_i - y_j\Vert{}_2^{2b}\big)^{-1}$ (fitted to a
min_disthyperparameter) and minimizes fuzzy set cross-entropy using negative sampling: $$\mathcal{L}_{\text{UMAP}} = \sum_{i \neq j} \left[ w_{ij} \ln \frac{w_{ij}}{v_{ij}} + (1 - w_{ij}) \ln \frac{1 - w_{ij}}{1 - v_{ij}} \right]$$
Unlike t-SNE’s one-sided KL divergence, the second term $(1 - w_{ij})\ln\frac{1 - w_{ij}}{1 - v_{ij}}$ explicitly penalizes placing disconnected points close together—helping UMAP preserve more global topological relationships while scaling far faster via stochastic negative sampling.
6.4 Dimensionality Reduction Methods Compared #
| Method | Transformation Type | Objective / Mathematical Core | Preserves Global Structure? | Out-of-Sample Transform? | Primary Use Case |
|---|---|---|---|---|---|
| PCA / Truncated SVD | Linear orthogonal projection | Maximize variance / minimize Frobenius reconstruction error | Yes (exact linear variance hierarchy) | Yes ($z = x V_r$) | Feature compression, denoising, whitening, low-rank weight approximations (LoRA) |
| t-SNE | Non-linear probabilistic embedding | Minimize $D_{\text{KL}}(P_{\text{Gaussian}} \Vert{} Q_{\text{Student-}t})$ | Weakly (cluster spacing & sizes can mislead) | Not natively (non-parametric) | 2D/3D exploratory visualization of local cluster structure |
| UMAP | Non-linear topological embedding | Minimize fuzzy simplicial set cross-entropy via negative sampling | Moderately (stronger inter-cluster topology than t-SNE) | Yes (via nearest-neighbor graph projection) | Fast large-scale visualization & non-linear pre-embedding |
7. Minimal Implementation: GMM (EM) vs. K-Means & Low-Rank SVD in NumPy #
The NumPy script below verifies two central mechanisms from this article directly from scratch:
- Part A (K-Means vs. GMM via EM): Generating three elongated, tilted, overlapping 2D Gaussian clusters and contrasting spherical K-Means (k-means++) against a full-covariance Gaussian Mixture Model trained with the Expectation–Maximization algorithm (using Cholesky decomposition and log-sum-exp for numerical stability).
- Part B (Truncated SVD & Low-Rank Spectral Energy): Simulating a $64 \times 64$ weight update matrix $\Delta W$ dominated by an intrinsic rank-$4$ subspace plus background noise, then auditing exact Frobenius reconstruction error and captured spectral energy across ranks $r \in \{1, 2, 4, 8, 16\}$—illustrating the exact linear-algebraic foundation behind LoRA.
import numpy as np
# =====================================================================
# PART A: K-Means (k-means++) vs. Full-Covariance GMM (EM Algorithm)
# =====================================================================
class KMeansScratch:
def __init__(self, k: int = 3, max_iter: int = 100):
self.k = k
self.max_iter = max_iter
self.centroids = None
def fit(self, X: np.ndarray, seed: int = 42):
rng = np.random.default_rng(seed)
n, d = X.shape
# k-means++ initialization (Arthur & Vassilvitskii, 2007)
centroids = np.empty((self.k, d), dtype=float)
centroids[0] = X[rng.integers(0, n)]
for c in range(1, self.k):
dist_sq = np.min(
np.sum((X[:, None, :] - centroids[None, :c, :]) ** 2, axis=2),
axis=1,
)
probs = dist_sq / np.sum(dist_sq)
centroids[c] = X[rng.choice(n, p=probs)]
for _ in range(self.max_iter):
dists = np.sum((X[:, None, :] - centroids[None, :, :]) ** 2, axis=2)
labels = np.argmin(dists, axis=1)
new_centroids = np.array([
X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(self.k)
])
if np.allclose(centroids, new_centroids, atol=1e-6):
break
centroids = new_centroids
self.centroids = centroids
return self
def predict(self, X: np.ndarray) -> np.ndarray:
dists = np.sum((X[:, None, :] - self.centroids[None, :, :]) ** 2, axis=2)
return np.argmin(dists, axis=1)
class GMMScratch:
"""Full-Covariance Gaussian Mixture Model via Expectation-Maximization."""
def __init__(self, k: int = 3, max_iter: int = 100, tol: float = 1e-5, reg_covar: float = 1e-6):
self.k = k
self.max_iter = max_iter
self.tol = tol
self.reg_covar = reg_covar
self.weights = None
self.means = None
self.covs = None
self.log_likelihood_history = []
def _log_gaussian_prob(self, X: np.ndarray, mean: np.ndarray, cov: np.ndarray) -> np.ndarray:
n, d = X.shape
cov_reg = cov + self.reg_covar * np.eye(d)
L = np.linalg.cholesky(cov_reg)
log_det = 2.0 * np.sum(np.log(np.diag(L)))
diff = (X - mean).T # shape: (d, n)
sol = np.linalg.solve(L, diff)
maha_sq = np.sum(sol ** 2, axis=0)
return -0.5 * (d * np.log(2.0 * np.pi) + log_det + maha_sq)
def fit(self, X: np.ndarray, seed: int = 42):
n, d = X.shape
# Initialize means warmly via K-Means++
km = KMeansScratch(k=self.k).fit(X, seed=seed)
self.means = km.centroids.copy()
self.weights = np.full(self.k, 1.0 / self.k)
self.covs = np.array([np.cov(X, rowvar=False) + self.reg_covar * np.eye(d) for _ in range(self.k)])
self.log_likelihood_history = []
prev_ll = -np.inf
for _ in range(self.max_iter):
# --- E-STEP: Compute log-responsibilities safely via Log-Sum-Exp ---
log_prob = np.empty((n, self.k), dtype=float)
for j in range(self.k):
log_prob[:, j] = np.log(self.weights[j] + 1e-16) + self._log_gaussian_prob(
X, self.means[j], self.covs[j]
)
max_lp = np.max(log_prob, axis=1, keepdims=True)
log_norm = max_lp + np.log(np.sum(np.exp(log_prob - max_lp), axis=1, keepdims=True))
log_resp = log_prob - log_norm
resp = np.exp(log_resp)
total_ll = float(np.sum(log_norm))
self.log_likelihood_history.append(total_ll)
if abs(total_ll - prev_ll) < self.tol:
break
prev_ll = total_ll
# --- M-STEP: Update mixing weights, means, and full covariances ---
nk = np.sum(resp, axis=0) + 1e-12
self.weights = nk / n
for j in range(self.k):
r_j = resp[:, j : j + 1]
self.means[j] = np.sum(r_j * X, axis=0) / nk[j]
diff = X - self.means[j]
self.covs[j] = (diff.T @ (r_j * diff)) / nk[j] + self.reg_covar * np.eye(d)
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
n = X.shape[0]
log_prob = np.empty((n, self.k), dtype=float)
for j in range(self.k):
log_prob[:, j] = np.log(self.weights[j] + 1e-16) + self._log_gaussian_prob(
X, self.means[j], self.covs[j]
)
max_lp = np.max(log_prob, axis=1, keepdims=True)
return np.exp(log_prob - (max_lp + np.log(np.sum(np.exp(log_prob - max_lp), axis=1, keepdims=True))))
def clustering_accuracy_up_to_perm(y_true: np.ndarray, y_pred: np.ndarray) -> float:
from itertools import permutations
best = 0.0
for perm in permutations(range(3)):
mapped = np.array([perm[c] for c in y_pred])
best = max(best, float(np.mean(mapped == y_true)))
return best * 100.0
# Generate 3 tilted, anisotropic, partially overlapping 2D Gaussian clusters
rng = np.random.default_rng(21)
n_per = 150
rot_a = np.array([[0.85, -0.52], [0.52, 0.85]])
cov_a = rot_a @ np.diag([2.8, 0.08]) @ rot_a.T
rot_b = np.array([[0.85, 0.52], [-0.52, 0.85]])
cov_b = rot_b @ np.diag([2.8, 0.08]) @ rot_b.T
cov_c = np.array([[0.35, 0.0], [0.0, 0.35]])
X_c0 = rng.multivariate_normal([0.0, 0.0], cov_a, size=n_per)
X_c1 = rng.multivariate_normal([0.0, 1.35], cov_b, size=n_per)
X_c2 = rng.multivariate_normal([2.2, 0.65], cov_c, size=n_per)
X_unsup = np.vstack([X_c0, X_c1, X_c2])
y_latent = np.repeat([0, 1, 2], n_per)
km_model = KMeansScratch(k=3).fit(X_unsup, seed=42)
gmm_model = GMMScratch(k=3).fit(X_unsup, seed=42)
km_acc = clustering_accuracy_up_to_perm(y_latent, km_model.predict(X_unsup))
gmm_probs = gmm_model.predict_proba(X_unsup)
gmm_acc = clustering_accuracy_up_to_perm(y_latent, np.argmax(gmm_probs, axis=1))
monotonic = all(
b >= a - 1e-9 for a, b in zip(gmm_model.log_likelihood_history, gmm_model.log_likelihood_history[1:])
)
print("=== PART A: Anisotropic Clustering — K-Means vs. GMM (EM) ===")
print(f"K-Means Latent Cluster Recovery : {km_acc:.1f}% (distorted by spherical Voronoi assumption)")
print(f"GMM (EM) Latent Cluster Recovery: {gmm_acc:.1f}% (adapts full elliptical covariances)")
print(f"EM Log-Likelihood Monotonic? : {monotonic} ({gmm_model.log_likelihood_history[0]:.1f} -> {gmm_model.log_likelihood_history[-1]:.1f})")
print(f"Sample Boundary Uncertainty : max posterior = {np.min(np.max(gmm_probs, axis=1)):.3f} (soft overlap awareness)\n")
# =====================================================================
# PART B: Truncated SVD & Low-Rank Spectral Energy (LoRA Foundation)
# =====================================================================
rng_svd = np.random.default_rng(99)
d_model = 64
true_intrinsic_rank = 4
# Construct a 64x64 weight update Delta_W with rank-4 signal + small background noise
B_true = rng_svd.normal(0.0, 1.0, size=(d_model, true_intrinsic_rank))
A_true = rng_svd.normal(0.0, 1.0, size=(true_intrinsic_rank, d_model))
Delta_W = (B_true @ A_true) + rng_svd.normal(0.0, 0.15, size=(d_model, d_model))
# Exact Singular Value Decomposition: Delta_W = U @ diag(S) @ Vt
U, S, Vt = np.linalg.svd(Delta_W, full_matrices=False)
total_energy = float(np.sum(S ** 2))
full_params = d_model * d_model
print("=== PART B: Truncated SVD & Low-Rank Approximation (Eckart-Young-Mirsky) ===")
print(f"Matrix shape: {d_model}x{d_model} ({full_params} parameters) | True signal rank: {true_intrinsic_rank}\n")
print(f"{'Rank r':<7} | {'Factor Params B+A':<18} | {'Compression':<12} | {'Spectral Energy':<16} | {'Rel. Frob Error'}")
print("-" * 78)
for r in [1, 2, 4, 8, 16]:
Delta_W_r = (U[:, :r] * S[:r]) @ Vt[:r, :]
energy_ratio = float(np.sum(S[:r] ** 2)) / total_energy * 100.0
rel_frob_err = float(np.linalg.norm(Delta_W - Delta_W_r, "fro") / np.linalg.norm(Delta_W, "fro"))
lora_params = 2 * d_model * r
compression = full_params / lora_params
print(
f"{r:<7} | {lora_params:<18} | {compression:>8.1f}x | "
f"{energy_ratio:>13.2f}% | {rel_frob_err:.4f}"
)Interpreting the Behavior #
Two structural insights show up clearly in the output:
- Elliptical Geometry vs. Voronoi Walls (Part A): Because clusters 0 and 1 form narrow, tilted ellipses crossing near the origin, K-Means slices through the middle of the elongated clouds and misassigns roughly a quarter of the points. GMM (EM) learns full $2 \times 2$ covariance matrices $\Sigma_k$, aligns its probability contours cleanly along the tilted axes, pushes recovery into the
90%+range, and maintains strict monotonic log-likelihood ascent throughout every EM step. - Low-Rank Spectral Compression (Part B): On the $64 \times 64$ weight update matrix (
4,096parameters), projecting onto just rank $r = 4$ (512factor parameters—an 8× compression, scaling to 100×+ on $4096 \times 4096$ Transformer layers) captures over 98% of total spectral energy (S^2), leaving behind only unstructured background noise.
8. Limitations & Bridge to Part 8 #
Notice a subtle danger hidden inside every preprocessing and dimensionality-reduction step we have covered so far: what happens if you fit PCA, a feature scaler, or a target encoder on your entire dataset before splitting into training and test sets? Even without touching labels $y$, test-set variance and feature distributions leak directly into your training representation—producing optimistically biased validation metrics that collapse in production.
Beyond evaluation discipline lies an even deeper structural boundary for all classical machine learning. Across Parts 1 through 7, every algorithm—Linear Models, Kernel SVMs, Random Forests, XGBoost, GMMs, and PCA—operates on fixed tabular feature vectors $x \in \mathbb{R}^d$ designed by humans. When confronted with raw pixels, audio waveforms, or natural language tokens, classical pipelines stall unless an engineer painstakingly hand-crafts domain features first.
In Part 8: Rigorous Evaluation, Data Leakage & The Limits of Feature Engineering—the finale of Series 1—we will dissect ROC-AUC vs. Precision–Recall (PR-AUC) on severely imbalanced data, audit probability calibration and data leakage traps, and examine how the ceiling of manual feature engineering catalyzed Representation Learning and Series 2: Deep Learning.
References #
- Pearson, K. (1901). “On Lines and Planes of Closest Fit to Systems of Points in Space.” The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science, 2(11), 559–572. (Original formulation of Principal Component Analysis).
- Eckart, C., & Young, G. (1936). “The Approximation of One Matrix by Another of Lower Rank.” Psychometrika, 1(3), 211–218. (Optimality of Truncated SVD for low-rank matrix approximation).
- Dempster, A. P., Laird, N. M., & Rubin, D. B. (1977). “Maximum Likelihood from Incomplete Data via the EM Algorithm.” Journal of the Royal Statistical Society: Series B (Methodological), 39(1), 1–38. (Foundational Expectation–Maximization framework).
- Lloyd, S. P. (1982). “Least Squares Quantization in PCM.” IEEE Transactions on Information Theory, 28(2), 129–137. (Iterative K-Means algorithm).
- Beyer, K., Goldstein, J., Ramakrishnan, R., & Shaft, U. (1999). “When Is ‘Nearest Neighbor’ Meaningful?” Database Theory — ICDT ‘99, 217–235. (Mathematical proof of distance concentration in high dimensions).
- Arthur, D., & Vassilvitskii, S. (2007). “k-means++: The Advantages of Careful Seeding.” Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA ‘07), 1027–1035.
- van der Maaten, L., & Hinton, G. (2008). “Visualizing Data using t-SNE.” Journal of Machine Learning Research (JMLR), 9(86), 2579–2605.
- McInnes, L., Healy, J., & Melville, J. (2018). “UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction.” Journal of Open Source Software, 3(29), 861. arXiv:1802.03426.
- Hu, E. J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., Wang, L., & Chen, W. (2021). “LoRA: Low-Rank Adaptation of Large Language Models.” International Conference on Learning Representations (ICLR 2022). arXiv:2106.09685.