Clustering

Introduction K-means Clustering Vector Quantization (VQ) Spectral Clustering Demo

Introduction

Clustering is one of the core tasks in unsupervised learning. Unlike supervised learning, where models learn from labeled data, unsupervised learning aims to uncover hidden patterns or structures in data without any predefined labels. Among these tasks, clustering is particularly important. It groups data points into clusters based on their similarity, revealing the underlying structure of the data.

In our treatment of Principal Component Analysis (PCA) and autoencoders, we explored techniques that reduce the dimensionality of high-dimensional data while preserving as much of the information needed to reconstruct the data as possible. These methods produce compact representations of data, often referred to as latent features.

Now that we have the tools to represent complex data in a lower-dimensional space, we turn to the next natural question: Can we identify meaningful groupings within this reduced space? This is the goal of clustering, which allows us to segment data into coherent groups. Examples include grouping similar images, organizing unlabeled documents, and detecting communities in social networks.

K-means Clustering

We begin with K-means clustering, a simple and widely used algorithm.

We assume that there are \(K\) cluster centers \(\mu_k \in \mathbb{R}^D\), for \(k = 1, \ldots, K\). Each data point \(x_n \in \mathbb{R}^D\) is assigned to its nearest center: \[ z_n^* = \arg \min_k \| x_n - \mu_k \|_2^2. \]

Given the assignments, the center of each nonempty cluster is updated as the mean of its points: \[ \mu_k = \frac{1}{N_k} \sum_{n : z_n =k} x_n, \,\text{where } N_k = \sum_{n=1}^N \mathbb{I}[z_n = k]. \] A cluster that receives no points has no mean, so its center must be re-seeded. The demo below moves it to the data point farthest from its own center.

These two steps, assignment and update, are repeated until convergence. This process can be viewed as minimizing a cost function known as the distortion, which is equivalent to the squared Frobenius norm of the reconstruction error: \[ \begin{align*} J(M, Z) &= \sum_{n = 1}^N \| x_n - \mu_{z_n} \|_2^2 \\\\ &= \| X - ZM^\top \|_F^2 \end{align*} \] where \(X \in \mathbb{R}^{N \times D}\), \(Z \in \{0, 1\} ^{N \times K}\), and \(M \in \mathbb{R}^{D \times K}\) contains the cluster centers \(\mu_k\) in its columns.
Note. The matrix \(Z\) is the one-hot encoding (or dummy encoding) matrix whose entries are \[ Z_{nk} = \begin{cases} 1, &\text{ if \(x_n\) is assigned to cluster \(k\) } \\\\ 0, &\text{ otherwise}. \end{cases} \]

Neither step can increase \(J\). The assignment step minimizes \(J\) over \(Z\) for fixed centers. The update step minimizes it over the centers for fixed assignments. For points \(x_1, \ldots, x_m\) with mean \(\bar{x}\) and any \(c\), we have \(\sum_{i} \|x_i - c\|^2 = \sum_{i} \|x_i - \bar{x}\|^2 + m \|\bar{x} - c\|^2\), so the mean is the best center, and a re-seeded empty cluster contributes nothing to \(J\). Suppose a point changes center only when some center is strictly closer. Then every assignment step that changes \(Z\) strictly decreases \(J\), so no assignment can recur. Since there are at most \(K^N\) assignments, the iteration reaches an assignment that the next assignment step reproduces, and this assignment is a fixed point.

Vector Quantization (VQ)

A key idea of vector quantization is to compress data by replacing each high-dimensional vector \(x_n \in \mathbb{R}^D\) with a discrete symbol \(z_n \in \{1, \ldots, K\}\). That symbol is an index into a codebook of \(K\) prototype vectors, \(\mu_k \in \mathbb{R}^D\).

Each data point is encoded by finding the index of the closest prototype using Euclidean distance: \[ z_n := f_e (x_n) = \arg \min_k \| x_n - \mu_k \|^2. \]

The corresponding decoder simply maps the index back to the prototype: \[ f_d(k) = \mu_k. \] The reconstruction of each data point is therefore \(\hat{x}_n = f_d(z_n) = \mu_{z_n}\).

The quality of a codebook is measured using the reconstruction error (also called distortion): \[ \begin{align*} J &= \frac{1}{N} \sum_{n =1}^N \| x_n - f_d (f_e (x_n))\|^2 \\\\ &= \frac{1}{N} \sum_{n=1}^N \|x_n - \mu_{z_n} \|^2. \end{align*} \] Up to the factor \(\frac{1}{N}\), this is the distortion that the K-means algorithm decreases until the iteration reaches a fixed point. The algorithm can be interpreted as a special case of vector quantization where the codebook is learned by iteratively reducing the distortion. VQ is more focused on signal compression and encoding, whereas K-means is usually employed for data analysis and clustering tasks.

Spectral Clustering

K-means assigns each point to its nearest center, so its clusters are the cells of a Voronoi partition. These cells are convex, and any two of them are separated by a hyperplane, so K-means works best on compact, roughly spherical clusters. However, many real-world datasets exhibit complex, non-convex structures that are not well-captured by distance alone. Spectral clustering addresses this limitation by transforming the data into a new space that reflects the connectivity structure of the data, often represented as a graph.

The idea is to build a similarity graph where each data point is a node, and edges encode pairwise similarities. Let \(\mathbf{W} \in \mathbb{R}^{N \times N}\) be a symmetric weight matrix for a graph such that \(w_{ij} = w_{ji} \geq 0\) measures the similarity between points \(i\) and \(j\), with \(w_{ii} = 0\) (no self-loops). Nodes \(i\) and \(j\) are adjacent when \(w_{ij} \gt 0\). The degree of node \(i\) is defined as: \[ d_i = \sum_{j=1}^N w_{ij}, \] and we define the degree matrix \(\mathbf{D} \in \mathbb{R}^{N \times N}\) as a diagonal matrix with entries \(D_{ii} = d_i\).

The fundamental object in spectral clustering is the graph Laplacian, \(\mathbf{L} = \mathbf{D} - \mathbf{W}\), where \(\mathbf{D}\) is the diagonal degree matrix and \(\mathbf{W}\) is the weight (similarity) matrix. The entries of \(\mathbf{L}\) are \[ L_{ij} = \begin{cases} d_i & \text{if } i = j \\\\ -w_{ij} & \text{if } i \neq j \end{cases}. \] The Laplacian is real symmetric and positive semi-definite, with associated quadratic form \[ \boldsymbol{f}^\top \mathbf{L} \boldsymbol{f} = \frac{1}{2} \sum_{i,j} w_{ij}(f_i - f_j)^2, \] known as the Dirichlet energy. It measures the smoothness of \(\boldsymbol{f}\) on the graph: small when adjacent nodes have similar values.

The basic result behind spectral clustering is the connection between the Laplacian's nullspace and the graph's component structure:

Spectral Connectivity (Result Used Below)

For a graph \(G\) with \(K\) connected components \(S_1, \ldots, S_K\), \[ \ker \mathbf{L} = \operatorname{span}\{\mathbf{1}_{S_1}, \ldots, \mathbf{1}_{S_K}\}, \] so the multiplicity of the eigenvalue \(0\) equals the number of connected components. The full statement and proof are developed in our graph Laplacian page in the linear algebra section, following the standard Dirichlet-energy argument.

The intuition for spectral clustering is now immediate. If a graph has \(K\) well-separated clusters joined by weak inter-cluster edges, and each cluster is itself well connected, the graph is approximately a union of \(K\) connected components. The eigenvectors for the \(K\) smallest eigenvalues of \(\mathbf{L}\) then span a subspace close to the span of the indicator vectors of those clusters. Spectral clustering exploits this by embedding nodes via these eigenvectors and applying K-means in the embedded space.

Since \(\mathbf{L}\) is symmetric and positive semi-definite, it admits a spectral decomposition: \[ \mathbf{L} = \mathbf{V}\boldsymbol{\Lambda}\mathbf{V}^\top, \quad 0 = \lambda_1 \le \lambda_2 \le \cdots \le \lambda_N, \] where \(\boldsymbol{\Lambda}\) contains the real, non-negative eigenvalues, and the columns of \(\mathbf{V}\) form an orthonormal eigenbasis. The smallest eigenvalues correspond to the smoothest variations of a function on the graph. In the cluster setting, they correspond to the indicator structure described above.

In practice, graphs often exhibit irregular structure. Nodes may have highly varying degrees, and clusters are not perfectly block-separated. The raw Laplacian \(\mathbf{L} = \mathbf{D} - \mathbf{W}\) can then be dominated by high-degree nodes, leading to unbalanced or misleading spectral embeddings. To address this, we assume that no node is isolated, so that every \(d_i \gt 0\) and \(\mathbf{D}\) is invertible, and use the symmetric normalized Laplacian: \[ \begin{align*} \mathbf{L}_{\text{sym}} &= \mathbf{D}^{-\frac{1}{2}} \mathbf{L} \mathbf{D}^{-\frac{1}{2}} \\\\ &= \mathbf{I} - \mathbf{D}^{-\frac{1}{2}} \mathbf{W} \mathbf{D}^{-\frac{1}{2}} \end{align*} \] For \(\mathbf{L}_{\text{sym}}\) the analogous nullspace characterization is that the eigenspace of zero eigenvalue is spanned by \(\mathbf{D}^{1/2} \mathbf{1}_{S_k}\) for \(k = 1, \ldots, K\), where \(\mathbf{1}_{S_k}\) are again the indicator vectors of the connected components. Indeed, since \(\mathbf{D}^{-1/2}\) is invertible, \(\mathbf{L}_{\text{sym}}\mathbf{x} = \mathbf{0}\) holds if and only if \(\mathbf{D}^{-1/2}\mathbf{x} \in \ker \mathbf{L}\).

The spectral clustering algorithm proceeds as follows:

Algorithm: Spectral Clustering
  1. Compute the symmetric normalized Laplacian \(\mathbf{L}_{\text{sym}} = \mathbf{I} - \mathbf{D}^{-\frac{1}{2}} \mathbf{W} \mathbf{D}^{-\frac{1}{2}}\).
  2. Find orthonormal eigenvectors for the \(K\) smallest eigenvalues of \(\mathbf{L}_{\text{sym}}\) and stack them column-wise into a matrix \(\mathbf{U} \in \mathbb{R}^{N \times K}\).
  3. Normalize each nonzero row of \(\mathbf{U}\) to have unit norm, leaving any zero row unchanged, to form a matrix \(\mathbf{T} \in \mathbb{R}^{N \times K}\): \[ t_{ij} = \frac{u_{ij}}{\sqrt{\sum_{l=1}^K u_{il}^2}}. \]
  4. Apply K-means clustering to the rows of \(\mathbf{T}\).
  5. Assign the original data point \(x_i\) to cluster \(k\) if row \(i\) of \(\mathbf{T}\) is assigned to cluster \(k\).

Looking Ahead: From Spectral Clustering to Geometric Deep Learning

Spectral clustering uses a small number of low-frequency Laplacian eigenvectors to partition a graph. Two threads connect to this idea:

  • The Cheeger inequality links the second-smallest eigenvalue of the normalized Laplacian \(\mathbf{L}_{\text{sym}}\) to the graph's conductance. That eigenvalue is the spectral gap of \(\mathbf{L}_{\text{sym}}\), written \(\lambda_1^{\mathrm{norm}}\) on that page because its eigenvalues are indexed from 0. A small spectral gap guarantees a sparse two-way cut (a bottleneck).
  • The Laplacian eigenbasis defines a graph Fourier transform, extending classical Fourier analysis to functions on graphs. This is the starting point of spectral graph neural networks (GNNs), where Laplacian-based filters become learnable signal-processing operators rather than fixed spectral cuts.

The second thread leads into Geometric Deep Learning, the framework in which neural-network architectures are designed to respect the symmetries and geometric structure of the data they operate on.

Demo: The Three Algorithms, Live

The K-means and Spectral tabs run on one shared dataset, and the Vector Quantization tab runs K-means on a synthetic image. The generating classes of the shared dataset are never given to K-means or spectral clustering, and for \(K \leq 3\) the metrics panels of those two tabs report how well the discovered clusters happen to match them.

The K-means Tab

The Step button executes the K-means iteration, known as Lloyd's algorithm, one half-step at a time: an assignment step (each point moves to its nearest center) or an update step (each center moves to the mean of its points). The distortion \(J(M, Z)\) defined above is recorded after every half-step, and the curve never rises. Neither half-step can increase \(J\), which is the core of the convergence argument in the K-means section. Convergence is declared by the exact criterion. An assignment step that reproduces the previous assignment is a fixed point of the iteration, after which nothing can change. Stopping a run midway keeps the intermediate state on screen but labels it explicitly as a non-converged Lloyd iterate.

Note. In random initialization, we simply pick \(K\) data points uniformly at random to serve as the initial cluster centers. While this method is fast, it can place several initial centers in the same cluster, often leading to poor local optima or slow convergence.

To address this, the K-means++ initialization strategy is widely used in practice. It selects initial centers more carefully by favoring points that are far apart from already chosen centers. This significantly improves the stability and performance of K-means clustering and often leads to better local optima. In expectation, the K-means++ centers alone already achieve a distortion within a factor of order \(\log K\) of the optimum.

Algorithm: K-means++ Initialization
  1. Choose the first center \(\mu_1\) uniformly at random from the dataset \(\{x_1, \ldots, x_N\}\).
  2. Suppose \(m\) centers \(\mu_1, \ldots, \mu_m\) have been chosen. For each data point \(x_i\), compute its squared distance to the nearest of them: \[ D(x_i) = \min_{1 \leq j \leq m} \|x_i - \mu_j\|_2^2 \] Points already chosen have \(D(x_i) = 0\) and cannot be drawn again.
  3. Choose the next center \(\mu_{m+1}\) from the data points with probability proportional to \(D(x_i)\): \[ \Pr(x_i \text{ is chosen}) = \frac{D(x_i)}{\sum_j D(x_j)} \] The sampling rule requires \(\sum_j D(x_j) \gt 0\), which holds while fewer centers have been chosen than there are distinct data points.
  4. Repeat steps 2-3 until \(K\) centers have been selected.
  5. Proceed with the standard K-means algorithm using these \(K\) initial centers.

The Compare inits button makes this concrete. It runs ten restarts with each initialization and reports the mean, best, and worst final distortion. On the blob dataset with \(K = 3\) at low noise, a typical outcome is that every K-means++ restart ends at the same distortion while random initialization averages noticeably worse. The worst random restart can end at several times the best distortion, stuck with two centers inside one cloud. At higher noise the gap between the two initializations narrows.

The Spectral Tab

The pipeline is the spectral clustering algorithm box above, executed literally apart from one safeguard for isolated nodes. The similarity graph uses \(w_{ij} = \exp(-\|x_i - x_j\|^2 / (2\sigma^2))\) with no self-loops, shown in the first panel, where edge opacity increases with the weight. Edges with \(w_{ij} \lt 0.02\) are not drawn. At very small \(\sigma\) the computed degree of a node can be numerically zero, and the demo then sets the corresponding entry of \(\mathbf{D}^{-1/2}\) to zero.

The bottom \(K\) eigenvectors of \(\mathbf{L}_{\text{sym}}\) are computed by subspace iteration on the flipped operator \(\mathbf{M} = 2\mathbf{I} - \mathbf{L}_{\text{sym}}\). Its eigenvalues are \(2 - \lambda\) for the eigenvalues \(\lambda\) of \(\mathbf{L}_{\text{sym}}\), so its largest eigenvalues correspond to the smallest of \(\mathbf{L}_{\text{sym}}\). The spectrum of \(\mathbf{L}_{\text{sym}}\) lies in \([0, 2]\), so \(\mathbf{M}\) is positive semidefinite and no sign tricks are needed. The solver declares convergence only on a certificate: the residual \(\|(\mathbf{I} - \mathbf{V}\mathbf{V}^\top)\mathbf{M}\mathbf{V}\|\) of the computed invariant subspace. A run that reaches 2000 iterations without the certificate is reported as NOT certified. The subspace, not the individual eigenvectors, is the right object to certify, because the K-means step that follows sees only the rows of \(\mathbf{T}\), and those are unchanged (up to rotation) by any orthogonal mixing of the eigenvectors. When the eigenvalue \(0\) has multiplicity larger than \(K\), the certificate can pass although the bottom \(K\)-dimensional invariant subspace is not unique.

The embedding panel plots the rows of \(\mathbf{T}\) (their first two coordinates when \(K \geq 3\)). When the graph has \(K\) well-separated groups, these rows collapse onto \(K\) tight clumps that K-means separates trivially. That is the nullspace picture from the connectivity result above, made visible.

The width \(\sigma\) is a genuine modeling choice, and the demo does not hide its failure modes. At \(\sigma = 0.05\) and the default sample size, the graph shatters into many near-components, and many eigenvalues of \(\mathbf{L}_{\text{sym}}\) crowd near \(0\). At the other extreme, a very large \(\sigma\) connects everything to everything, and spectral clustering degrades to roughly K-means performance. The sweet spot in between is where the connectivity structure lives.

The Vector Quantization Tab

Here K-means acts as an image codec, exactly as in the vector quantization section. Each pixel is a point in RGB space, the codebook is the set of cluster centers, and every pixel is replaced by its nearest codebook color. The metrics panel reports the normalized distortion \(\frac{1}{N} \sum_n \|x_n - \mu_{z_n}\|^2\). The four-color band image makes the codebook idea exact. With \(K = 4\), the learned codebook is precisely the four colors and the distortion is exactly zero. That is lossless compression, because the image truly lives on four prototypes. The sweep button plots distortion against \(K\). The optimal distortion cannot increase with \(K\), since a codebook of size \(K\) is also available at size \(K + 1\) with one prototype repeated. The computed curve, built from local optima, does not increase in practice. When \(K\) exceeds the number of distinct colors, the seeding falls back to uniform draws and the codebook repeats colors.

Experiment Suggestions

  1. The headline contrast. On concentric circles, run K-means. Even with restarts it stays near 50-60% agreement with the generating rings, since no placement of two centers can separate concentric shapes. Then run spectral clustering at \(\sigma = 0.2\) and watch it recover the rings, exactly for most samples.
  2. Watch \(J\) at every half-step. On blobs, press Step repeatedly and check that neither the assignment nor the update half-step raises the distortion curve.
  3. Initialization traps. Set \(K = 3\), set the noise on blobs to zero, and use Compare inits. The gap between the worst random restart and the K-means++ runs is the page's claim about better local optima, in numbers.
  4. Break the graph on purpose. Keep the default dataset, \(K\), and sample size, set \(\sigma = 0.05\), and run spectral clustering to see the certificate fail. The graph has fragmented into many near-components, and the iteration cap is reached before a \(K\)-dimensional bottom eigenspace is isolated. Then try \(\sigma = 1\) and compare with plain K-means.
  5. Lossless at \(K = 4\). Quantize the band image with \(K = 4\) and confirm the distortion is exactly zero. Then sweep \(K\) on the gradient image, where no codebook with \(K \leq 8\) is exact and the distortion decays smoothly instead.