TExcelTAD
Home › Spectral Graph Theory & Modern Graph Algorithms › k-Way Spectral Clustering

k-Way Spectral Clustering

The Fiedler vector splits a graph in two. To find kk clusters, use kk eigenvectors: map every vertex to a point in Rk\mathbb{R}^k (its row in the matrix of the bottom kk eigenvectors) and cluster those points with kk-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 kk-means can separate. This lesson explains why, implements the algorithm with NumPy, and shows the eigengap heuristic for choosing kk.

From data to a graph

For points z1,…,znz_1, \ldots, z_n in Rp\mathbb{R}^p, build a similarity graph first:

  • Gaussian kernel: wij=exp⁡(−∥zi−zj∥2/(2σ2))w_{ij} = \exp(-\lVert z_i - z_j \rVert^2/(2\sigma^2)), a complete weighted graph with a scale σ\sigma;
  • kk-nearest neighbours: join ii and jj if either is among the other's kk nearest; sparse and less sensitive to scale;
  • ε\varepsilon-neighbourhood: join points at distance below ε\varepsilon.

For network data the graph is given. Everything below works on any weighted graph.

The algorithms

text
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 i

Shi and Malik (2000) derived the method from the normalized cut Ncut⁡(S1,…,Sk)=∑jw(∂Sj)vol⁡(Sj)\operatorname{Ncut}(S_1, \ldots, S_k) = \sum_j \frac{w(\partial S_j)}{\operatorname{vol}(S_j)}: minimizing it over partitions is NP-hard, but relaxing the cluster indicator vectors to real vectors turns it into the generalized eigenproblem Lx=νDxLx = \nu Dx, whose solutions are x=D−1/2yx = D^{-1/2}y for eigenvectors yy of NN. They used the second eigenvector recursively (split, then split the parts); with kk eigenvectors at once (running kk-means on the rows of D−1/2UD^{-1/2}U) the method differs from NJW only in how the rows of UU are rescaled before kk-means. The unnormalized variant uses the bottom kk eigenvectors of LL and relaxes the RatioCut ∑jw(∂Sj)/∣Sj∣\sum_j w(\partial S_j)/\lvert S_j \rvert. 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 kk connected components C1,…,CkC_1, \ldots, C_k, then by Eigenvalue Zero and Connected Components the eigenvalue ν=0\nu = 0 of NN has multiplicity kk, and its eigenspace is spanned by D1/21CjD^{1/2}\mathbf{1}_{C_j}. An eigensolver returns some orthonormal basis U=[D1/21Cj/vol⁡Cj]j⋅QU = [D^{1/2}\mathbf{1}_{C_j}/\sqrt{\operatorname{vol}C_j}]_j \cdot Q for an unknown rotation QQ. Row ii of UU is di\sqrt{d_i} times a row of QQ that depends only on the component of ii; after normalizing rows, all vertices of a component map to the same unit vector, and vectors of different components are orthogonal. kk-means then finds the components trivially.

The real case. Weak edges between clusters perturb NN slightly. By the Davis-Kahan theorem, the space of the bottom kk eigenvectors moves by an amount proportional to the size of the perturbation divided by the eigengap νk+1−νk\nu_{k+1} - \nu_k. As long as clusters are internally well connected (large νk+1\nu_{k+1}) and weakly connected to each other (small νk\nu_k), the embedded points stay close to kk orthogonal directions. Ng, Jordan and Weiss made this precise under conditions of this kind. The same reasoning gives the eigengap heuristic: choose kk where νk+1−νk\nu_{k+1} - \nu_k is large.

Clusters of any shape

Three concentric rings of noisy points defeat kk-means on the raw coordinates, because kk-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.

python · try it yourself
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 ν2\nu_2 is small and the eigengap heuristic is less decisive than for compact clusters. Spectral clustering recovers the rings exactly, while kk-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 k=4k = 4), runs NJW, and compares with the truth.

python · try it yourself
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 O(n3)O(n^3); for sparse graphs use Lanczos (scipy.sparse.linalg.eigsh with which="SM" on NN, or shift-invert) to get kk eigenvectors in roughly O(km)O(km) time per iteration. scikit-learn's SpectralClustering implements the NJW pipeline.
  • The graph matters more than the algorithm. The choice of σ\sigma 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 kk-means, one can rotate UU 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 νk\nu_k certifies kk 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 Rk\mathbb{R}^k?

  1. The kk largest eigenvectors of LL
  2. The kk eigenvectors of D−1/2WD−1/2D^{-1/2} W D^{-1/2} with the largest eigenvalues (the bottom kk of NN), with rows normalized
  3. Random projections
  4. The degree vector and its powers

If a graph has exactly kk connected components, what do the normalized rows of the bottom-kk eigenvector matrix of NN look like?

  1. All equal
  2. Equal within a component, orthogonal across components
  3. Random
  4. Zero for all vertices

Which relaxation leads to the generalized eigenproblem Lx=νDxLx = \nu D x?

  1. Minimum bisection
  2. Shi and Malik's normalized cut
  3. Maximum flow
  4. kk-center

What does the eigengap heuristic suggest?

  1. Choose kk with the smallest νk\nu_k
  2. Choose kk where νk+1−νk\nu_{k+1} - \nu_k is large
  3. Always choose k=2k = 2
  4. Choose k=nk = \sqrt n