k-Way Spectral Clustering
The Fiedler vector splits a graph in two. To find clusters, use eigenvectors: map every vertex to a point in (its row in the matrix of the bottom eigenvectors) and cluster those points with -means. This spectral clustering recipe, in the versions of Shi and Malik (2000) and Ng, Jordan and Weiss (2002), is one of the most widely used clustering methods, because the spectral embedding turns clusters of any shape (rings, spirals, communities in a network) into compact blobs that -means can separate. This lesson explains why, implements the algorithm with NumPy, and shows the eigengap heuristic for choosing .
From data to a graph
For points in , build a similarity graph first:
- Gaussian kernel: , a complete weighted graph with a scale ;
- -nearest neighbours: join and if either is among the other's nearest; sparse and less sensitive to scale;
- -neighbourhood: join points at distance below .
For network data the graph is given. Everything below works on any weighted graph.
The algorithms
spectral_clustering_njw(W, k) (Ng, Jordan and Weiss, 2002)
1 D ← diag(row sums of W); M ← D^(-1/2) W D^(-1/2)
2 U ← the k eigenvectors of M with the largest eigenvalues, as columns (n × k)
(equivalently: the bottom k eigenvectors of the normalized Laplacian N = I − M)
3 normalize every row of U to unit length
4 run k-means on the n rows of U; vertex i gets the cluster of row iShi and Malik (2000) derived the method from the normalized cut : minimizing it over partitions is NP-hard, but relaxing the cluster indicator vectors to real vectors turns it into the generalized eigenproblem , whose solutions are for eigenvectors of . They used the second eigenvector recursively (split, then split the parts); with eigenvectors at once (running -means on the rows of ) the method differs from NJW only in how the rows of are rescaled before -means. The unnormalized variant uses the bottom eigenvectors of and relaxes the RatioCut . Von Luxburg's tutorial (2007) recommends the normalized versions, whose relaxation is consistent as the sample grows.
Why it works
The ideal case. If the graph has exactly connected components , then by Eigenvalue Zero and Connected Components the eigenvalue of has multiplicity , and its eigenspace is spanned by . An eigensolver returns some orthonormal basis for an unknown rotation . Row of is times a row of that depends only on the component of ; after normalizing rows, all vertices of a component map to the same unit vector, and vectors of different components are orthogonal. -means then finds the components trivially.
The real case. Weak edges between clusters perturb slightly. By the Davis-Kahan theorem, the space of the bottom eigenvectors moves by an amount proportional to the size of the perturbation divided by the eigengap . As long as clusters are internally well connected (large ) and weakly connected to each other (small ), the embedded points stay close to orthogonal directions. Ng, Jordan and Weiss made this precise under conditions of this kind. The same reasoning gives the eigengap heuristic: choose where is large.
Clusters of any shape
Three concentric rings of noisy points defeat -means on the raw coordinates, because -means looks for compact, roughly spherical groups. In the 8-nearest-neighbour graph each ring is a long, well-connected cycle-like piece, nearly disconnected from the others, and the spectral embedding separates them.
import numpy as np
import matplotlib.pyplot as plt
def kmeans(X, k, rng, restarts=10, iters=100):
"""Lloyd's algorithm with k-means++ seeding; returns the labels of the best of several restarts."""
best, best_cost = None, np.inf
for _ in range(restarts):
C = [X[rng.integers(len(X))]]
for _ in range(k - 1):
d2 = np.min(((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1), axis=1)
C.append(X[rng.choice(len(X), p=d2 / d2.sum())])
C = np.array(C)
for _ in range(iters):
labels = ((X[:, None, :] - C[None]) ** 2).sum(-1).argmin(axis=1)
newC = np.array([X[labels == j].mean(axis=0) if np.any(labels == j) else C[j] for j in range(k)])
if np.allclose(newC, C):
break
C = newC
cost = ((X - C[labels]) ** 2).sum()
if cost < best_cost:
best, best_cost = labels, cost
return best
def accuracy(labels, truth, k):
"""Fraction of points correctly grouped, under the best matching of cluster names."""
import itertools
return max(np.mean(np.array(p)[labels] == truth) for p in itertools.permutations(range(k)))
rng = np.random.default_rng(0)
truth = np.repeat([0, 1, 2], [40, 80, 120]) # points proportional to the circumference
radius = np.array([1.0, 3.0, 5.0])[truth]
angle = rng.uniform(0, 2 * np.pi, len(truth))
X = np.c_[radius * np.cos(angle), radius * np.sin(angle)] + rng.normal(0, 0.1, (len(truth), 2))
# symmetric 8-nearest-neighbour graph
n = len(X)
dist = ((X[:, None, :] - X[None]) ** 2).sum(-1)
W = np.zeros((n, n))
nearest = np.argsort(dist, axis=1)[:, 1:9]
for i in range(n):
W[i, nearest[i]] = 1
W = np.maximum(W, W.T)
d = W.sum(axis=1)
M = W / np.sqrt(d)[:, None] / np.sqrt(d)[None, :]
vals, vecs = np.linalg.eigh(M)
U = vecs[:, -3:] # top 3 eigenvectors of M = bottom 3 of N
U = U / np.linalg.norm(U, axis=1, keepdims=True)
spectral = kmeans(U, 3, rng)
raw = kmeans(X, 3, rng)
nu = np.sort(1 - vals)[:5]
print("smallest normalized-Laplacian eigenvalues:", np.round(nu, 4) + 0.0)
print("edges between different rings:", int(sum(W[i, j] for i in range(n) for j in range(i) if truth[i] != truth[j])))
print(f"k-means on coordinates: accuracy {accuracy(raw, truth, 3):.3f}")
print(f"spectral clustering (NJW): accuracy {accuracy(spectral, truth, 3):.3f}")
fig, axes = plt.subplots(1, 2, figsize=(8, 3.8))
for ax, lab, title in [(axes[0], raw, "k-means on coordinates"), (axes[1], spectral, "spectral clustering")]:
ax.scatter(X[:, 0], X[:, 1], c=lab, cmap="viridis", s=12)
ax.set_title(title); ax.set_aspect("equal"); ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout()
plt.show()smallest normalized-Laplacian eigenvalues: [0. 0. 0.0013 0.0088 0.0102]
edges between different rings: 1
k-means on coordinates: accuracy 0.358
spectral clustering (NJW): accuracy 1.000
Two eigenvalues are exactly 0 and the third is tiny: a single stray edge joins two of the rings, so the graph has two components, one of which has a very sparse cut. The fourth eigenvalue is about 7 times the third, a clear but not dramatic gap. Long thin clusters like rings are cycle-like, so their own internal is small and the eigengap heuristic is less decisive than for compact clusters. Spectral clustering recovers the rings exactly, while -means on the coordinates cuts them into pie slices.
Communities in a network
The same algorithm on a graph with four planted communities of different sizes. The program prints the bottom eigenvalues (the eigengap after the fourth reveals ), runs NJW, and compares with the truth.
import itertools
import random
import numpy as np
def kmeans(X, k, rng, restarts=10, iters=100):
best, best_cost = None, np.inf
for _ in range(restarts):
C = [X[rng.integers(len(X))]]
for _ in range(k - 1):
d2 = np.min(((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1), axis=1)
C.append(X[rng.choice(len(X), p=d2 / d2.sum())])
C = np.array(C)
for _ in range(iters):
labels = ((X[:, None, :] - C[None]) ** 2).sum(-1).argmin(axis=1)
newC = np.array([X[labels == j].mean(axis=0) if np.any(labels == j) else C[j] for j in range(k)])
if np.allclose(newC, C):
break
C = newC
cost = ((X - C[labels]) ** 2).sum()
if cost < best_cost:
best, best_cost = labels, cost
return best
sizes = [30, 25, 20, 15]
truth = np.repeat(np.arange(4), sizes)
n = len(truth)
r = random.Random(2002)
W = np.zeros((n, n))
for u in range(n):
for v in range(u + 1, n):
if r.random() < (0.35 if truth[u] == truth[v] else 0.02):
W[u, v] = W[v, u] = 1
d = W.sum(axis=1)
M = W / np.sqrt(d)[:, None] / np.sqrt(d)[None, :]
vals, vecs = np.linalg.eigh(M)
nu = 1 - vals[::-1]
print("bottom 7 eigenvalues of N:", np.round(nu[:7], 4) + 0.0)
gaps = np.diff(nu[:8])
print("largest gap after eigenvalue number", int(np.argmax(gaps[1:]) + 2))
U = vecs[:, -4:]
U = U / np.linalg.norm(U, axis=1, keepdims=True)
labels = kmeans(U, 4, np.random.default_rng(1))
acc = max(np.mean(np.array(p)[labels] == truth) for p in itertools.permutations(range(4)))
print(f"edges: {int(W.sum() / 2)}, NJW accuracy: {acc:.3f}")
print("cluster sizes found:", sorted(np.bincount(labels).tolist(), reverse=True))bottom 7 eigenvalues of N: [0. 0.1163 0.156 0.2193 0.5525 0.5749 0.58 ]
largest gap after eigenvalue number 4
edges: 421, NJW accuracy: 1.000
cluster sizes found: [30, 25, 20, 15]
In practice
- Cost. A dense eigendecomposition costs ; for sparse graphs use Lanczos (
scipy.sparse.linalg.eigshwithwhich="SM"on , or shift-invert) to get eigenvectors in roughly time per iteration. scikit-learn'sSpectralClusteringimplements the NJW pipeline. - The graph matters more than the algorithm. The choice of or of the number of neighbours decides whether clusters are nearly disconnected. Too few neighbours fragment a cluster; too many merge clusters.
- Rounding alternatives. Instead of -means, one can rotate towards indicator vectors (Yu and Shi, 2003) or pick cluster centres by a QR decomposition with pivoting (Damle, Minden and Ying, 2019), which is deterministic.
- Guarantees. The higher-order Cheeger inequality gives a worst-case justification: a small certifies disjoint sets of small conductance. That lesson also shows when the method fails.
Test yourself
In the NJW algorithm, which vectors embed the vertices into ?
- The largest eigenvectors of
- The eigenvectors of with the largest eigenvalues (the bottom of ), with rows normalized
- Random projections
- The degree vector and its powers
If a graph has exactly connected components, what do the normalized rows of the bottom- eigenvector matrix of look like?
- All equal
- Equal within a component, orthogonal across components
- Random
- Zero for all vertices
Which relaxation leads to the generalized eigenproblem ?
- Minimum bisection
- Shi and Malik's normalized cut
- Maximum flow
- -center
What does the eigengap heuristic suggest?
- Choose with the smallest
- Choose where is large
- Always choose
- Choose