Spectral Clustering

Machine Learning
Introduced by
Ng, A. Y.; Jordan, M. I.; Weiss, Y.
Year
2002
Type
Graph-based clustering (spectral method)

What does it do?

Spectral Clustering is a graph-based unsupervised learning algorithm, formalized in the form described here by Ng, Jordan, and Weiss in 2002, that maps data points into a low-dimensional eigenspace derived from the Laplacian of a similarity graph and then applies k-means.

When the similarity scale and graph construction suit the data, the spectral embedding can separate clusters with non-convex shapes, such as rings, crescents, or interleaved spirals, which k-means applied directly to the original coordinates typically does not separate. With a poorly chosen scale or graph, it can fail to do so.

The intuition behind the method

Standard k-means partitions space by straight-line distance, so it finds convex, roughly spherical groups. Spectral Clustering first treats the data as a network: each point is a node, and edges carry weights that reflect how similar two points are. Clusters correspond to regions of the network that are densely connected internally and loosely connected to the rest. The graph Laplacian encodes this connectivity, and its smallest eigenvectors give a new coordinate system in which well-connected points lie close together, even when they were interleaved in the original space. A k-means step in that coordinate system then yields the partition.

History

Shi and Malik (2000) applied a spectral graph partitioning criterion, the normalized cut, to image segmentation. Ng, Jordan, and Weiss (2002) presented a general-purpose algorithm in the form described on this page, together with an analysis of when the method works. Von Luxburg's 2007 tutorial in Statistics and Computing reviewed the spectral formulations and the role of Laplacian normalization. The spectral-graph background, including Fiedler's work on algebraic connectivity, is the mathematical basis of these developments.

When to use it

Choose Spectral Clustering when clusters are expected to be non-convex or not separable by straight-line boundaries, for example ring-shaped groups, interleaved spirals, or image segments, and when a meaningful pairwise similarity can be defined, either by a kernel on the features or by a supplied affinity matrix. It also suits graph-structured data, where connectivity rather than feature coordinates defines the groups. The number of clusters k should be known or estimable, for example with the eigengap heuristic. Avoid the full formulation when clusters are expected to be compact and roughly convex, where k-means is simpler and cheaper, when no sensible similarity measure exists for the data, or when the dataset is too large for the full affinity matrix to be held in memory. The full method needs O(n^2) memory and O(n^3) time, so approximate variants are required in that case. A full Gaussian kernel is a reasonable default for small datasets with a well-chosen sigma; a k-nearest-neighbour graph gives a sparser matrix and is preferable for larger datasets or when densities vary. In either case, check that the graph is not split into many isolated components before computing eigenvectors.

Limitations and considerations

  • Forming the full n-by-n affinity matrix needs O(n^2) memory, and the eigendecomposition needs O(n^3) time, so the direct algorithm is impractical for large n without approximation.
  • The result depends on sigma and on how the graph is built; a poor choice can merge distinct clusters or split one cluster into fragments.
  • The k-means step on the embedding is randomly initialized, so different runs may produce different partitions.
  • Returns cluster labels only: it has no generative model, and it does not provide a natural out-of-sample extension for assigning new points.
  • In high-dimensional feature spaces, Euclidean distances become less informative, so Gaussian kernel weights can lose contrast unless the feature representation or bandwidth is handled carefully.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Recovers clusters of arbitrary shape, including non-convex configurations that k-means and Gaussian mixture models do not separate when applied to the raw coordinates.
  • Needs only pairwise similarities, so it can be applied to graphs or structured objects whenever an affinity between them can be defined.
  • The eigenvalue spectrum of the Laplacian gives a data-driven diagnostic, the eigengap, for choosing k.
  • Makes no distributional assumption about cluster shape and fits no parametric density model.
  • Each stage is an explicit matrix operation, so the algorithm can be implemented directly with standard linear-algebra routines.

Applications

  • Image segmentation: partitioning pixels or superpixels into regions using the similarity of their features, as in the normalized-cut approach of Shi and Malik.
  • Community detection in social and biological networks, where the affinity is defined by connections rather than by feature vectors.
  • Bioinformatics: grouping genes or proteins by expression-profile similarity, where the groups need not be convex in the original feature space.
  • Natural language processing: clustering documents or sentences using a similarity kernel on their representations.
  • Computer vision: motion segmentation and point-cloud partitioning, where cluster boundaries are irregular.
  • Exploratory analysis of cluster structure before applying a confirmatory method.

How it works

How it works

1

A pairwise affinity matrix W is built from the data. In the Ng-Jordan-Weiss algorithm the Gaussian (RBF) kernel is used for pairs i != j, and the diagonal is set to zero (W_ii = 0), so the graph has no self-loops. The kernel assigns high weight to nearby pairs and weight close to zero to distant ones. The bandwidth sigma controls how quickly similarity decays with distance, and its value strongly affects the result. A k-nearest-neighbour graph is an alternative that gives a sparser W, which can matter for larger datasets.

Formula
W_{ij} = \exp\!\left(-\frac{\|x_i - x_j\|^2}{2\sigma^2}\right)\ (i \neq j), \qquad W_{ii} = 0
2

The degree matrix D is diagonal, with each entry equal to the sum of the corresponding row of W. From W and D the symmetric normalized Laplacian L_sym is formed as in the mechanics formula. Its eigenvalue spectrum carries the information used to judge how many clusters the graph contains: several near-zero eigenvalues indicate weakly connected groups.

Formula
L_{\mathrm{sym}} = D^{-1/2}(D - W)D^{-1/2} = I - D^{-1/2}W D^{-1/2}
3

The k eigenvectors of L_sym that correspond to its k smallest eigenvalues are computed. Equivalently, they are the k largest eigenvectors of A = D^{-1/2} W D^{-1/2}, which is the form used by Ng, Jordan, and Weiss. They form the columns of the embedding matrix U, which has one row per data point. In this k-dimensional spectral space, points that belong to the same cluster are drawn close together even if they were interleaved in the original feature space.

Formula
L_{\mathrm{sym}}\, u = \lambda u \quad \Rightarrow \quad U = [u_1,\, u_2,\, \ldots,\, u_k]
4

Each row of U is divided by its Euclidean norm, giving the matrix T of the mechanics formula, so each embedded point lies on the unit sphere. Ng, Jordan, and Weiss introduced this step, and their analysis argues that after it the points of each cluster concentrate around distinct directions, so that the subsequent k-means step responds to the direction of each point's embedding rather than its magnitude.

Formula
T_{ij} = U_{ij} \Big/ \left(\sum_{j'} U_{ij'}^2\right)^{1/2}
5

Standard k-means is run on the rows of T: points are assigned to the nearest centroid, and centroids are recomputed as the mean of their assigned rows, until assignments stop changing. Because the embedding has already reorganized the cluster geometry, k-means can recover partitions that it could not find in the original coordinates. Row i of T carries the label of original data point i. Because k-means is randomly initialized, use several random restarts and keep the solution with the lowest within-cluster sum of squares; otherwise repeated runs may return different partitions.

Common pitfalls

  • Setting sigma without validation. If it is too small, the graph splinters into disconnected pieces and the Laplacian gains several near-zero eigenvalues that do not reflect real clusters; if it is too large, distinct clusters merge. Check the connectivity of the affinity graph (for example, count its connected components) before trusting the labels; if many points are isolated, increase sigma or the number of neighbours.
  • Normalizing the rows of the affinity matrix W instead of the eigenvector matrix U. The row-normalization step in the algorithm acts on the embedding T computed from U, so normalizing W's rows is a different operation and does not replace it.
  • Using a fixed k without inspecting the eigenvalue spectrum, which can lead to under- or over-segmentation.
  • Applying the full algorithm to very large datasets without switching to a sparse or approximate variant.
  • Replacing L_sym with the unnormalized Laplacian L = D - W, or with a random-walk variant. This changes the eigenvectors and therefore the partition. The algorithm on this page is defined with L_sym, and its row-normalization step is designed for that embedding, so any change requires rechecking the whole pipeline.
  • Leaving the diagonal of W at 1 (the kernel value for i = j). The Ng-Jordan-Weiss algorithm sets W_ii = 0; omitting this adds self-loops and changes the eigenvectors.

Frequently asked questions

How do I choose the number of clusters k?

The eigengap heuristic is the usual guide: compute the eigenvalues of the normalized Laplacian in ascending order and look for a large gap between consecutive values. The position of the gap suggests the natural number of clusters. If the gap is ambiguous, run the algorithm for several values of k and check whether the assignments remain stable under small perturbations of the data or parameters.

How should I set the Gaussian kernel bandwidth sigma?

The kernel on this page uses a single global bandwidth, and no single rule sets it reliably. Common starting points are a scale derived from the typical pairwise distances in the dataset, or a local scale for each point (self-tuning). Whichever is used, inspect the resulting affinity graph: each point should have some high-weight neighbours, and the graph should not split into isolated components.

Why is the row-normalization step necessary?

It is a design choice of the Ng-Jordan-Weiss algorithm, justified by their analysis. Normalizing each row of the embedding matrix to unit length maps all points onto the unit sphere, where, under their analysis, points of the same cluster lie near a common direction and different clusters lie in roughly orthogonal directions. The k-means step then responds to the angular geometry of the embedding rather than to row magnitude.

Can spectral clustering handle very large datasets?

Not in its naive form, which needs O(n^2) memory and O(n^3) time for the eigendecomposition. Common remedies are a sparse k-nearest-neighbour graph instead of a full affinity matrix, the Nystrom approximation to estimate eigenvectors from a subsample, or randomized SVD. These approximations reduce cost but can change the result, so it is worth comparing their output with the exact method on a subset where that is feasible.

Related methods

Sources

  1. Ng, A. Y., Jordan, M. I., & Weiss, Y. (2002). On Spectral Clustering: Analysis and an Algorithm. Advances in Neural Information Processing Systems, 14, 849–856.

    Open publication reference
  2. von Luxburg, U. (2007). A Tutorial on Spectral Clustering. Statistics and Computing, 17, 395–416.

    Open DOI reference
  3. Shi, J., & Malik, J. (2000). Normalized Cuts and Image Segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(8), 888–905.

    Open DOI reference