Spectral Clustering
Graph Laplacians, cuts and eigenvectors.
Two interleaved half-moons defeat k-means, yet a few eigenvectors can pull them apart. Spectral clustering builds a graph that joins nearby points, then uses the bottom eigenvectors of the graph's Laplacian to embed the points so that the clusters become easy to separate. This lesson proves why it works: the Laplacian counts connected components, its eigenvectors solve relaxations of the NP-hard RatioCut and normalized cut, Cheeger's inequality controls the cuts they produce, and in random graphs with two planted communities the limits of community detection are known exactly.
What you’ll learn
- Build -neighborhood, -nearest-neighbor and Gaussian similarity graphs, and prove the basic properties of the graph Laplacian and its two normalized versions.
- Derive spectral clustering as a relaxation of RatioCut and of normalized cut, and implement the Ng–Jordan–Weiss algorithm.
- State Cheeger's inequality, prove its easy direction, and state its higher-order version and a gap condition under which spectral clustering provably recovers clusters.
- Summarize when spectral clustering is statistically consistent, and the thresholds for detecting and exactly recovering communities in the stochastic block model.
Similarity graphs and their Laplacians
Spectral clustering starts from a weighted graph on the points, with symmetric weights that are large for similar points. Three constructions are standard: the -neighborhood graph joins points within distance ; the -nearest-neighbor graph joins and if either is among the other's nearest neighbors (or, in the mutual version, if both are); and the fully connected graph uses Gaussian weights , the RBF kernel. Write for the degree of vertex , , and .
Expand the quadratic form with and symmetrize. Every term is nonnegative, so is positive semidefinite, and :
If , the sum is zero, so whenever : is constant on each connected component. Conversely, the indicator of a component satisfies , because a vertex of has all its weight inside and other vertices have none there:
So the multiplicity of the eigenvalue 0 is the number of connected components. The indicators are also the 0-eigenvectors of , while those of are the rescaled vectors , by the equivalences above.
Think first The smallest eigenvalues of a graph's normalized Laplacian are . How many clusters does the graph suggest?
Four. Two zero eigenvalues mean exactly two connected components. Two more eigenvalues close to 0 mean that the components can be cut further, into four groups in all with few edges between them. The jump from to is the eigengap, and the eigengap heuristic chooses just before it. Step 4 makes "close to 0" precise with Cheeger's inequality.
Spectral clustering relaxes graph cuts
For vertex sets let . The minimum cut usually just splits off one weakly attached vertex, so useful objectives balance the sizes. For a partition with complements :
Hagen & Kahng (1992) gave the spectral relaxation of the ratio cut, a balanced objective from circuit partitioning, and Shi & Malik (2000) introduced normalized cut for image segmentation. Adding the balance terms makes exact minimization NP-hard (von Luxburg, 2007, refers to Wagner & Wagner, 1993, for a discussion), and spectral clustering solves a relaxation instead.
Encode a split by for and for . In only the pairs that cross the cut contribute, each unordered pair once:
The vector also satisfies two constraints that do not depend on the split:
Drop the requirement that take two values. Minimizing over with is a Rayleigh-quotient problem whose solution is , the eigenvector of the second-smallest eigenvalue of (the Fiedler vector). Every split is feasible, so the relaxation also gives a lower bound:
For clusters, put for : then and , and the relaxed problem is solved by the bottom eigenvectors of (Ky Fan). With instead, and ; substituting turns it into the bottom eigenvectors of , or equivalently the generalized problem of Shi & Malik.
The relaxed solution is not a partition, so it is rounded, usually by running k-means on the rows of the eigenvector matrix. Nothing in the relaxation guarantees that the rounded cut is near-optimal, and on specially constructed graphs it is far from it (Guattery & Miller, 1998). Step 4 shows what can be guaranteed, and the next step shows why the rows of the eigenvector matrix are good points to cluster.
The algorithms, and why they work
| Algorithm | Eigenvectors of | Then |
|---|---|---|
| Unnormalized (RatioCut) | , the smallest | k-means on the rows of |
| Shi & Malik (2000), normalized cut | , i.e. | k-means on the rows (originally: recursive two-way splits by thresholding) |
| Ng, Jordan & Weiss (2002) | , the smallest | rescale every row of to unit length, then k-means |
import numpy as np
from scipy.linalg import eigh
from sklearn.cluster import KMeans
def njw_spectral_clustering(X, k, sigma):
sq = ((X[:, None, :] - X[None, :, :]) ** 2).sum(axis=-1) # pairwise squared distances
W = np.exp(-sq / (2 * sigma ** 2))
np.fill_diagonal(W, 0.0)
d = W.sum(axis=1)
M = W / np.sqrt(np.outer(d, d)) # D^{-1/2} W D^{-1/2} = I - L_sym
vals, vecs = eigh(M) # eigenvalues in ascending order
U = vecs[:, -k:] # top k of M = bottom k of L_sym
U = U / np.linalg.norm(U, axis=1, keepdims=True)
return KMeans(n_clusters=k, n_init=10).fit_predict(U)A dense version for a few thousand points: memory and time for the eigendecomposition. At scale, use a sparse -nearest-neighbor graph and an iterative eigensolver that computes only the vectors needed, or Nyström approximations of .
Why it works: the ideal case and its perturbation. Suppose the graph has exactly connected components. Then the bottom eigenspace of is spanned by the component indicators, so all rows of belonging to one cluster are identical (any orthonormal basis of the eigenspace is a rotation of the indicators), and k-means recovers the clusters perfectly. For the eigenvectors are , so rows of one cluster point in the same direction but have lengths proportional to ; rescaling each row to unit length sends every cluster to a single point on the sphere, which is the Ng–Jordan–Weiss step. Real graphs have a few edges between clusters, a small perturbation of the ideal Laplacian. By the Davis–Kahan theorem (the Convergence lesson Linear Algebra for ML: Eigenvectors & the SVD), the bottom- eigenspace rotates by an angle of order , where the gap separates from , so the rows stay close to well-separated points. This is the matrix-perturbation argument Ng, Jordan & Weiss used, and it is why a large eigengap is the signal to trust.
Kernel k-means, again. With weights and a kernel built from , the weighted kernel k-means objective is equivalent to normalized cut (Dhillon, Guan & Kulis, 2004, 2007): the eigenvectors solve its relaxation, and k-means-style iterations attack the same objective directly.
Think first On two interleaved half-moons, why does k-means on the rows of the eigenvector matrix succeed where k-means on the original points fails?
Distances in the embedding reflect connectivity in the graph, not straight-line distance. A -nearest-neighbor graph links each moon into a chain of close points with almost no edges between the moons, so the graph is nearly two components; the embedding maps each moon close to its own point, and k-means separates the two compact groups. In the original plane, the moons are not convex and their tips are closer to the other moon's middle than to their own far end, which is what defeats k-means.
Cheeger's inequality and provable recovery
For a vertex set , the conductance measures how weakly is attached to the rest, and . Small conductance means a good two-way cluster, and up to a factor of 2 it is the two-way normalized cut.
The bottom eigenvector of is . Substituting in the Courant–Fischer characterization of the second eigenvalue gives:
For any set , test , which satisfies . Only crossing pairs contribute to :
The ratio is at most twice the conductance, because the larger of the two reciprocals is . Minimizing over gives :
A graph's normalized Laplacian has . The sweep cut along the second eigenvector is guaranteed to have conductance at most what?
Show the answer
0.2
. The lower bound says no cut does better than . The gap between and is the quadratic loss of Cheeger's inequality, and each end is nearly tight on some graphs: on a long cycle the conductance is of order , far above , while for two dense cliques joined by a single edge it is close to .
The inequality extends to clusters. Measure a set's expansion by , and let be the smallest possible value of the largest expansion among disjoint nonempty vertex sets. Lee, Oveis Gharan & Trevisan (2014) proved
so a graph has eigenvalues near zero exactly when it has disjoint sparsely connected pieces, which is the mathematical content of the eigengap heuristic. Peng, Sun & Zanetti (2017) turned it into a guarantee for the algorithm itself: if , the ratio of the -st eigenvalue to the same expansion quantity minimized over -way partitions, is , then running any k-means algorithm with approximation ratio on the spectral embedding returns clusters with , after matching them to an optimal partition .
Consistency and community detection
Consistency. As more points are drawn from a fixed distribution and the graph is built with a fixed similarity function, do the clusters converge? Von Luxburg, Belkin & Bousquet (2008) showed that the eigenvectors converge to those of limit operators, and that normalized spectral clustering converges under very general conditions, while unnormalized spectral clustering is consistent only under strong additional assumptions that real data can violate. That is a statistical reason to prefer or .
Community detection. In networks the graph is the data. The stochastic block model (Holland, Laskey & Leinhardt, 1983) generates one: each vertex gets a hidden community label, and edges appear independently, with probability inside a community and across. For the symmetric two-community model the limits of recovery are known exactly.
| Regime | Goal | Possible if and only if | Established by |
|---|---|---|---|
| , (bounded average degree) | detection: agree with the truth better than chance | , the Kesten–Stigum threshold | conjectured by Decelle, Krzakala, Moore & Zdeborová (2011); impossibility below it: Mossel, Neeman & Sly (2015); algorithms above it: Massoulié (2014) and Mossel, Neeman & Sly (2018) |
| , | exact recovery: every vertex labeled correctly | Abbe, Bandeira & Hall (2016) and Mossel, Neeman & Sly (2016), both with efficient algorithms; a semidefinite program also reaches the threshold (Hajek, Wu & Xu, 2016) |
In a two-community stochastic block model with and , can communities be detected better than chance as ?
- No: the graph is so sparse that nothing can be detected
- Yes: exceeds
- Yes, but only by exhaustive search over all partitions
- No: detection needs to be at least twice times
Show the answer
B. Yes: exceeds
The Kesten–Stigum condition holds, , so efficient algorithms achieve better-than-chance agreement. Exact recovery is out of reach at this sparsity: with bounded average degree, a constant fraction of vertices have no edges at all.
In this sparse regime, plain spectral clustering of the adjacency matrix or a Laplacian fails: the eigenvectors it uses localize on a few vertices (for the adjacency matrix, the highest-degree ones) or on small, loosely attached pieces of the graph, and they hide the community signal. Krzakala, Moore, Mossel, Neeman, Sly, Zdeborová & Zhang (2013) proposed the non-backtracking matrix, which walks along directed edges without immediately reversing; its spectrum keeps the community eigenvalues separated from the bulk. They argued that it reaches the threshold, partly conjecturally, and Bordenave, Lelarge & Massoulié (2018) proved it.
Key takeaways
- Spectral clustering builds a similarity graph (, -nearest-neighbor or Gaussian), computes the bottom eigenvectors of a graph Laplacian, and runs k-means on their rows. is positive semidefinite with , and its zero eigenvalues count connected components.
- Its eigenvectors solve relaxations of NP-hard balanced cuts: RatioCut leads to (the Fiedler vector for two clusters), normalized cut to or ; the relaxed value lower-bounds the cut.
- It works when the graph is close to disconnected pieces: Davis–Kahan perturbation explains the eigengap heuristic, Cheeger's inequality and its higher-order version tie small eigenvalues to sparse cuts, and a large gap makes recovery provable.
- Normalized spectral clustering is statistically consistent under general conditions, unnormalized only under strong ones. In two-community stochastic block models, detection is possible exactly when and exact recovery exactly when ; sparse graphs need non-backtracking operators.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
The unnormalized Laplacian of a graph has eigenvalue with multiplicity . What does that tell you?
- The graph has exactly 3 isolated vertices
- The graph has exactly 3 connected components
- The best clustering has 3 clusters of equal size
- has rank 3
Show the answer
B. The graph has exactly 3 connected components
vanishes exactly for vectors constant on each connected component, so the null space is spanned by the component indicators and its dimension counts the components.
Relaxing the two-way RatioCut problem leads to which vector?
- The eigenvector of the largest eigenvalue of
- The constant vector , the eigenvector of the smallest eigenvalue
- The eigenvector of the second-smallest eigenvalue of , the Fiedler vector
- The top eigenvector of
Show the answer
C. The eigenvector of the second-smallest eigenvalue of , the Fiedler vector
The encoding vector satisfies and , and . Minimizing the Rayleigh quotient under gives the eigenvector of ; its signs suggest the split.
Why does the Ng–Jordan–Weiss algorithm rescale each row of the eigenvector matrix to unit length before running k-means?
- Because the eigenvectors of for a cluster are proportional to , so rows of one cluster share a direction but not a length
- To make the algorithm independent of
- Because k-means requires inputs of unit norm
- To remove the constant eigenvector
Show the answer
A. Because the eigenvectors of for a cluster are proportional to , so rows of one cluster share a direction but not a length
In the ideal case the bottom eigenvectors of are , so vertices of different degree in the same cluster sit at different distances from the origin along one direction. Normalizing collapses each cluster to a single point on the unit sphere, and different clusters to orthogonal points, which k-means then separates easily.
A two-community stochastic block model has and . Is exact recovery of every label possible as ?
- No: is below
- Only partial recovery is possible, because some vertex always has more neighbors in the other community
- Yes: exceeds 2
- No: exact recovery requires
Show the answer
C. Yes: exceeds 2
The exact-recovery threshold is , here . Above it, with high probability every vertex has more neighbors inside its own community, and efficient algorithms recover all the labels.
Further reading
- U. von Luxburg, "A tutorial on spectral clustering," Statistics and Computing 17(4), 395–416 (2007).
- J. Shi & J. Malik, "Normalized cuts and image segmentation," IEEE Transactions on Pattern Analysis and Machine Intelligence 22(8), 888–905 (2000).
- A. Y. Ng, M. I. Jordan & Y. Weiss, "On spectral clustering: analysis and an algorithm," Advances in Neural Information Processing Systems 14 (NIPS 2001) (MIT Press, 2002).
- U. von Luxburg, M. Belkin & O. Bousquet, "Consistency of spectral clustering," Annals of Statistics 36(2), 555–586 (2008).
- E. Abbe, "Community detection and stochastic block models: recent developments," Journal of Machine Learning Research 18(177), 1–86 (2018).