Spectral clustering
Spectral clustering as graph cuts relaxed to Laplacian eigenvectors, and its connections to spectral embeddings.
After this lesson you can
- Construct similarity graphs and reason about connectivity.
- Derive spectral relaxations of RatioCut and Ncut.
- Implement Ng–Jordan–Weiss spectral clustering with sparse eigenvectors.
- Use eigengaps and perturbation theory to understand cluster selection and robustness.
- Interpret spectral clustering as a random walk that rarely crosses clusters.
Before you start
Motivation: what k-means cannot separate
k-means assigns each point to its nearest centroid, so clusters are Voronoi cells: convex regions separated by hyperplanes. Two interleaved moons or concentric rings do not fit that mold. No pair of centroids has a bisector separating one moon from the other, and however many times you restart Lloyd’s algorithm, minimum inertia cuts the moons in half. The issue is not optimization: the criterion measures the wrong thing. What distinguishes the groups is not distance to a center, but connectivity: you can travel between points on one moon in short steps, while crossing to the other takes a long jump.
Spectral clustering turns that intuition into three steps. Construct a graph joining nearby points; formulate grouping as cutting few graph edges; and, because that combinatorial problem is NP-hard, relax it to an eigenvalue problem for the graph Laplacian, whose solution is computed in polynomial time and, for sparse graphs, near-linear time. Eigenvectors move points to a new space where moons are two compact clouds and k-means works.
import numpy as np, warnings
from sklearn.datasets import make_moons, make_circles
from sklearn.cluster import KMeans, SpectralClustering
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
datos = {
"lunas": make_moons(n_samples=400, noise=0.06, random_state=0),
"anillos": make_circles(n_samples=400, noise=0.05, factor=0.45, random_state=0),
}
for nombre, (X, y) in datos.items():
km = KMeans(2, n_init=10, random_state=0).fit_predict(X)
sc = SpectralClustering(2, affinity="nearest_neighbors", n_neighbors=10, random_state=0).fit_predict(X)
print(f"{nombre:8s} ARI de k-means = {ARI(y, km):6.3f} ARI espectral = {ARI(y, sc):.3f}")Adjusted Rand index (ARI, studied in detail in clustering evaluation) is 1 if the partition matches truth and around 0 if it relates to truth no better than random assignment. k-means reaches 0.274 on moons and −0.002 on rings: on rings its partition is literally random relative to truth. Spectral clustering succeeds on both.
This lesson also opens a thread running through the rest of the module: the same Laplacian eigenvectors underlie Laplacian eigenmaps and diffusion maps, and reappear at the end in the spectral interpretation of contrastive learning.
Before definitions, see the result. In the interactive, the left panel draws data and their neighbor graph, coloring each point by a Laplacian eigenvector value; the right places each point at coordinates from the second and third eigenvectors. You need not yet understand their origin: note that is nearly constant on each moon (orange on one, blue on the other), and on the right the moons have become two clouds separated by a line.
Similarity graphs
The method depends entirely on an object you construct before calculating anything: the graph.
The relation “ is one of my neighbors” is not symmetric: an isolated point has distant neighbors but is a neighbor of none of them. Thus two ways to make the graph undirected: “or” and “and.” The “or” version has more edges and connects regions of different densities; mutual is stricter, does not join differently dense zones and therefore breaks into more components (von Luxburg, 2007, section 8.1, recommends it precisely when seeking groups of different densities, with a larger ). Never pass the directed, asymmetric matrix to an algorithm assuming symmetry: eigsh assumes and returns a result without warning. Scikit-learn symmetrizes with , where is directed connectivity: mutual edges weigh 1 and one-way edges 0.5.
Connectivity. If the graph has more connected components than desired groups, the method finds components, not groups (proved shortly). Asymptotic theory says that for points from a density in , -neighbor graphs are connected with probability tending to 1 if grows as , and von Luxburg suggests that order of magnitude as a first approximation for large graphs. For radius , the smallest value making the graph connected is the longest edge of the minimum spanning tree (the same tree as single linkage), though with outliers or widely separated groups that value is too large.
Scale . The Gaussian kernel converts distances into weights, and decides what “near” means. With far below typical neighbor distance, almost all weights are zero and the graph breaks apart; with far above data diameter, all weights approach 1, the graph is almost complete and uniform and no structure remains to cut. Practical rules tie to local scale: order of mean distance to the th neighbor, with (von Luxburg, 2007, section 8.1). Zelnik-Manor and Perona (2004) propose a per-point local scale, with distance from to its seventh neighbor, adapting the graph to differently dense regions.
import numpy as np
import scipy.sparse as sp
from scipy.sparse.csgraph import connected_components
from scipy.spatial.distance import pdist, squareform
from sklearn.neighbors import NearestNeighbors
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=400, noise=0.06, random_state=0)
n = len(X)
def knn_dirigido(X, k):
ind = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X, return_distance=False)[:, 1:]
return sp.csr_matrix((np.ones(n * k), (np.repeat(np.arange(n), k), ind.ravel())), shape=(n, n))
print(" k aristas dirigidas sin la inversa componentes «o» componentes «y»")
for k in [2, 3, 5, 8, 12]:
C = knn_dirigido(X, k)
asim = (C != C.T).nnz // 2 # pares con arista en un solo sentido
print(f"{k:2d} {asim / (n * k):31.1%} {connected_components(C.maximum(C.T))[0]:15d} {connected_components(C.minimum(C.T))[0]:15d}")
print(f"log(n) = {np.log(n):.1f}")
D = squareform(pdist(X))
for eps in [0.05, 0.10, 0.15, 0.30]:
G = sp.csr_matrix((D <= eps) & (D > 0))
aislados = (np.asarray(G.sum(1)).ravel() == 0).sum()
print(f"eps = {eps:.2f}: componentes = {connected_components(G)[0]:3d}, vértices aislados = {aislados}")
print(f"mediana de la distancia al 8.º vecino = {np.median(np.sort(D, axis=1)[:, 8]):.3f};"
f" mediana de todas las distancias = {np.median(pdist(X)):.3f}")
for sigma in [0.02, 0.1, 1.0, 10.0]:
W = np.exp(-D**2 / (2 * sigma**2)); np.fill_diagonal(W, 0)
entre = W[y[:, None] != y[None, :]].mean() / W[(y[:, None] == y[None, :]) & ~np.eye(n, dtype=bool)].mean()
print(f"sigma = {sigma:5.2f}: grado mínimo = {W.sum(1).min():.1e}, peso medio entre lunas / dentro = {entre:.3f}")Three readings. With , one in five directed edges (20.4%) has no reverse: asymmetry is not a detail. The “or” graph has 2 components from (and 1 at , once edges between moons sneak in), while mutual needs to fall to 2: at it has 87. And has a window: at , below typical neighbor distance (0.097 to the eighth neighbor), some points have degree of order , practically isolated; at , average between-moon weight is 99.2% of within-moon weight, and the graph distinguishes nothing.
Review: the three Laplacians
Graph Laplacians and their spectral theory are studied deeply in the graphs module (combinatorial Laplacian, normalized Laplacians); here is what you need. Let be degree of vertex , and, for , its vertex count and its volume. Assume positive degrees (no isolated vertices) when appears.
Proof
(1) . Since (by symmetry), write . Since , the sum is nonnegative.
(2) ; with , this is equivalent to . is symmetric and .
(3) If , every term vanishes: is constant along each edge and hence on each connected component. Thus , of dimension because indicators have disjoint supports. For the kernel is the same ( is invertible), and for it is its image under by (2). Since all three matrices are diagonalizable (the two symmetric ones by the spectral theorem, and is similar to ), algebraic and geometric multiplicity agree.
(4) By the same argument as (1), , so generalized quotient lies in , and eigenvalues of are values of that quotient.
∎Point (3) is the method’s heart: if the graph had exactly one component per group, computing the Laplacian kernel would reveal groups. Note the nuance for : its kernel vectors are not constant per component, but proportional to . This affects the Ng, Jordan and Weiss algorithm.
import numpy as np
rng = np.random.default_rng(0)
tam = [5, 7, 4]
n = sum(tam)
W = np.zeros((n, n)); ini = 0
for t in tam: # tres bloques conexos con pesos aleatorios
B = np.triu(rng.uniform(0.2, 1.0, (t, t)) * (rng.random((t, t)) < 0.7), 1)
for i in range(t - 1):
B[i, i + 1] = max(B[i, i + 1], 0.5) # un camino garantiza que el bloque es conexo
W[ini:ini + t, ini:ini + t] = B + B.T; ini += t
d = W.sum(1); L = np.diag(d) - W
L_sym = np.eye(n) - W / np.sqrt(np.outer(d, d))
L_rw = np.eye(n) - W / d[:, None]
f = rng.normal(size=n)
print(f"f'Lf = {f @ L @ f:.6f} (1/2) sum w_ij (f_i - f_j)^2 = {0.5 * (W * (f[:, None] - f[None, :])**2).sum():.6f}")
for nombre, M in [("L", L), ("L_sym", L_sym), ("L_rw", L_rw)]:
ev = np.sort(np.linalg.eigvals(M).real)
print(f"{nombre:6s} autovalores nulos: {(np.abs(ev) < 1e-10).sum()} mayor: {ev[-1]:.3f}")
uno_A = np.zeros(n); uno_A[:5] = 1 # indicadora de la primera componente
print(f"|L_rw 1_A| = {np.abs(L_rw @ uno_A).max():.1e} |L_sym 1_A| = {np.abs(L_sym @ uno_A).max():.3f}"
f" |L_sym D^(1/2) 1_A| = {np.abs(L_sym @ (np.sqrt(d) * uno_A)).max():.1e}")Three components, three zero eigenvalues in all three Laplacians; the largest normalized eigenvalue (1.818) lies in , while has no such bound. A component indicator is a zero eigenvector of but not , whose zero vector is .
Graph cuts: MinCut, RatioCut and Ncut
Clustering partitions vertices into so edges between parts have low weight. For disjoint , let , and for a part , and .
Why minimum cut isolates vertices. With , minimum cut is polynomial-time solvable (Stoer and Wagner, 1997), but gives useless partitions: separating a single vertex costs exactly its degree , and a neighbor graph almost always has a peripheral vertex of low degree, much less than the total weight of edges crossing any true group boundary. Minimum cut has no incentive for large parts. RatioCut and Ncut add one by dividing by each part’s size, measured in vertices () or edge weight (). Since is minimized at , both reward balance. The cost: with that restriction the problem becomes NP-hard (Wagner and Wagner, 1993; Shi and Malik, 2000, prove NP-completeness of exactly minimizing Ncut).
Which one? RatioCut measures size in points and Ncut in volume: a dense group with many internal edges has high volume even with few points. Ncut favors groups with high internal weight relative to outgoing weight, our notion of cohesion; RatioCut only counts vertices. The difference matters with highly heterogeneous degrees, as the game shows.
import numpy as np
from scipy.linalg import eigh
# nodos 0 a 11 en el código; en el texto y en la figura, 1 a 12
aristas = [(0,1,1), (1,2,1), (2,3,1), (3,4,1), (4,5,1), (5,0,1), (0,2,1), (1,3,1), (2,4,1), (3,5,1), (4,0,1), (5,1,1),
(6,7,1), (7,8,1), (8,6,1), (8,9,.6), (9,10,.5), (10,11,.4), (2,6,.3), (3,7,.3)]
n = 12
W = np.zeros((n, n))
for a, b, w in aristas:
W[a, b] = W[b, a] = w
d = W.sum(1); L = np.diag(d) - W; vol = d.sum()
# las 2^11 - 1 = 2047 biparticiones (el nodo 12 fijo en un lado para no repetir)
M = ((np.arange(1, 2**(n - 1))[:, None] >> np.arange(n)) & 1).astype(bool)
a, b, w = np.array(aristas).T
a, b = a.astype(int), b.astype(int)
corte = (M[:, a] != M[:, b]) @ w
tam, vA = M.sum(1), M @ d
objetivos = {"MinCut": corte, "RatioCut": corte / tam + corte / (n - tam), "Ncut": corte / vA + corte / (vol - vA)}
lado = lambda m: (np.flatnonzero(m if m.sum() <= n / 2 else ~m) + 1).tolist()
for nombre, c in objetivos.items():
i = c.argmin()
print(f"{nombre:8s} óptimo = {c[i]:.4f} lado menor = {lado(M[i])}")
def evalua(m):
c = W[m][:, ~m].sum()
return c / m.sum() + c / (~m).sum(), c / d[m].sum() + c / d[~m].sum()
lam, U = eigh(L) # L u = lambda u
lam_rw, V = eigh(L, np.diag(d)) # L u = lambda D u, es decir, L_rw
for nombre, v, l2, j in [("L", U[:, 1], lam[1], 0), ("L_rw", V[:, 1], lam_rw[1], 1)]:
m = v > 0
orden = np.argsort(v)
barrido = min(evalua(np.isin(np.arange(n), orden[:t]))[j] for t in range(1, n))
rc, nc = evalua(m)
print(f"{nombre:5s} lambda_2 = {l2:.4f} signo: lado {lado(m)}, RatioCut = {rc:.4f}, Ncut = {nc:.4f}"
f" mejor umbral ({['RatioCut', 'Ncut'][j]}) = {barrido:.4f}")
print("vector de Fiedler de L:", np.round(U[:, 1] * np.sign(U[11, 1]), 3))Minimum cut (0.4) isolates node 12 at the end of the tail. RatioCut and Ncut agree on the optimum: the octahedron versus the rest, with 0.2 and 0.0869. The next section explains the other lines: values are lower bounds for these optima (0.0930 ≤ 0.2 and 0.0675 ≤ 0.0869), and the Fiedler vector of has values at nodes 7 and 8, just below zero, so its sign splits the triangle: 7 and 8 join the octahedron and 9 joins the tail.
Spectral relaxation
The trick is to write cut objectives as Laplacian quadratic forms evaluated on very particular vectors, then forget those vectors were particular.
Two groups and RatioCut
For nonempty proper , define the scaled indicator vector
Using identity (1) of the theorem, , only crossing edges contribute. For them , and each edge appears twice in the ordered-pair sum, canceling :
(You will prove this step by step in the first exercise.) Minimizing RatioCut therefore means minimizing over vectors of that form, orthogonal to and with norm . There are only such vectors; allowing any with both constraints makes the problem
a Rayleigh quotient restricted to the orthogonal complement of the first eigenvector. By the Courant–Fischer theorem, the minimum is and is attained at the second eigenvector, the Fiedler vector (after Fiedler, 1973, who related graph bipartitions to it). Since the relaxation’s feasible set contains the original,
which is what the cell showed: .
groups
For parts, define with if and 0 otherwise. Its columns are orthonormal, , and each column satisfies (the same calculation with only one nonzero side). Summing,
The relaxation permits any with , and the minimum of under that constraint is , attained by the first eigenvectors (Ky Fan’s theorem, a consequence of Courant–Fischer). The solution is determined only up to rotation: , with orthogonal , is equally good. Rounding therefore cannot read the partition column by column; use k-means on rows of : ideally all rows in a group are equal (the perturbation section makes this precise).
Ncut and the generalized problem
For Ncut with two groups, the scaled indicator uses volumes:
and the same calculation gives , and . Relaxing gives
whose solution is the second vector of generalized problem , namely the second eigenvector of . Substituting converts it to the Rayleigh quotient of restricted to (derived in the second exercise). The analogous bound is : in the cell, . For groups, the version yields the first generalized eigenvectors.
# continúa con el grafo de 12 nodos de la celda anterior
m = np.zeros(n, bool); m[:6] = True # A = el octaedro (nodos 1 a 6)
a_, c = m.sum(), W[m][:, ~m].sum()
f = np.where(m, np.sqrt((n - a_) / a_), -np.sqrt(a_ / (n - a_)))
print(f"RatioCut: f'Lf = {f @ L @ f:.4f} n·RatioCut = {n * (c / a_ + c / (n - a_)):.4f}"
f" suma de f = {f.sum():.1e} |f|^2 = {f @ f:.1f}")
vA, vB = d[m].sum(), d[~m].sum()
g = np.where(m, np.sqrt(vB / vA), -np.sqrt(vA / vB))
print(f"Ncut: g'Lg = {g @ L @ g:.4f} vol(V)·Ncut = {vol * (c / vA + c / vB):.4f}"
f" (Dg)'1 = {g @ d:.1e} g'Dg = {g @ (d * g):.1f} = vol(V) = {vol:.1f}")What relaxation does not guarantee. Relaxation gives a lower bound, but no guarantee on the rounded partition’s quality. Guattery and Miller (1998) constructed “roach” graphs, ladders of vertices missing some rungs, where optimal RatioCut cuts 2 edges and is , while unnormalized spectral clustering always cuts horizontally, edges, with RatioCut 1: a factor worse, order (von Luxburg, 2007, section 5.4). Approximating balanced cuts within a constant factor is also NP-hard in general. The game above is a small example: the sign of the Fiedler vector of gives 3.75 times optimal. Practice compensates with better rounding (threshold sweep found it) and the appropriate Laplacian.
Shi–Malik and Ng–Jordan–Weiss algorithms
With the relaxation established, the algorithm nearly follows: build the graph, calculate a few eigenvectors and round.
Why normalize rows. Ideally the zero eigenvectors of are (up to rotation): each point’s row is proportional to . A low-degree, typically peripheral, point lies near the origin, where k-means misassigns it or groups become confused. Dividing the row by its norm removes this factor and maps all rows in a group to one unit-sphere point. A curious consequence: since eigenvectors of are times those of , their rows differ only by factor , and after row normalization both embeddings are identical. The difference between Shi–Malik and NJW lies precisely in this step.
Which Laplacian to use. If degrees are similar, all three give nearly the same result. If widely distributed, von Luxburg (2007, section 8.5) favors normalized forms for two reasons. First, the objective: Ncut asks for low between-group weight and high within-group weight (volume is in the denominator), while RatioCut only counts vertices. Second, statistical: von Luxburg, Belkin and Bousquet (2008) prove normalized spectral clustering is consistent as under general conditions, whereas unnormalized may not be. Among normalized forms she favors , whose ideal eigenvectors are indicators independent of ; is equally good with normalization, which becomes delicate only with near-zero-degree vertices.
What scikit-learn does. In version 1.9, SpectralClustering builds the graph (with affinity="nearest_neighbors", the earlier symmetrization ; with "rbf", the complete Gaussian kernel with gamma and gamma=1.0 by default), computes eigenvectors of using ARPACK, multiplies them by (converts to vectors), and applies k-means without row normalization. Thus it is the Shi–Malik variant with k-means. Default gamma=1.0 means in your data units without checking scale: standardization or setting gamma is your responsibility.
Lab: Ng, Jordan and Weiss from scratch
The lab constructs a sparse -neighbor graph with Gaussian weights ( equal to median distance to the tenth neighbor), converts to the normalized matrix, computes the eigenvectors using scipy.sparse.linalg.eigsh (Lanczos, covered at the end), normalizes rows and clusters with k-means. It compares scikit-learn and k-means on points across three datasets: moons, rings and a mixture of three Gaussian clouds with standard deviations 1.5, 0.6 and 0.3 and sizes 300, 200 and 100.
import numpy as np, warnings
import scipy.sparse as sp
from scipy.sparse.linalg import eigsh
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import KMeans, SpectralClustering
from sklearn.datasets import make_moons, make_circles, make_blobs
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
def grafo_knn(X, k=10):
"""Grafo de k vecinos simétrico («o») con pesos gaussianos; sigma = mediana de la distancia al k-ésimo vecino."""
dist, ind = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X)
dist, ind = dist[:, 1:], ind[:, 1:] # fuera el propio punto
sigma = np.median(dist[:, -1])
n = len(X)
W = sp.csr_matrix((np.exp(-dist.ravel()**2 / (2 * sigma**2)), (np.repeat(np.arange(n), k), ind.ravel())), shape=(n, n))
return W.maximum(W.T) # simétrico: max(w_ij, w_ji)
def njw(W, k, seed=0):
"""Ng, Jordan y Weiss: k autovectores de L_sym, filas a norma 1 y k-means. Devuelve etiquetas y lambda_1..k."""
d = np.asarray(W.sum(axis=1)).ravel()
Dh = sp.diags(1 / np.sqrt(d))
M = Dh @ W @ Dh # M = I - L_sym
mu, U = eigsh(M, k=k, which="LA") # los k mayores de M son los k menores de L_sym
Y = U / np.linalg.norm(U, axis=1, keepdims=True)
return KMeans(k, n_init=10, random_state=seed).fit_predict(Y), np.sort(1 - mu)
X1, y1 = make_moons(n_samples=600, noise=0.1, random_state=1)
X2, y2 = make_circles(n_samples=600, noise=0.05, factor=0.45, random_state=1)
X3, y3 = make_blobs(n_samples=[300, 200, 100], centers=[[0, 0], [5, 0], [2.5, 4]],
cluster_std=[1.5, 0.6, 0.3], random_state=1)
print(f"{'datos':8s} {'k':>2s} {'desde cero':>11s} {'sklearn':>8s} {'k-means':>8s} lambda_1..k+1 de L_sym")
for nombre, X, y in [("lunas", X1, y1), ("anillos", X2, y2), ("mezcla", X3, y3)]:
k = len(np.unique(y))
W = grafo_knn(X)
_, lam = njw(W, k + 1)
et, _ = njw(W, k)
sk = SpectralClustering(k, affinity="nearest_neighbors", n_neighbors=10, random_state=0).fit_predict(X)
km = KMeans(k, n_init=10, random_state=0).fit_predict(X)
print(f"{nombre:8s} {k:2d} {ARI(y, et):11.3f} {ARI(y, sk):8.3f} {ARI(y, km):8.3f} {np.round(lam, 4)}")
tabla = np.zeros((3, 3), int)
np.add.at(tabla, (y, et), 1) # et es la partición de la mezcla, la última del bucle
print("mezcla: grupo verdadero (filas, desviaciones 1.5, 0.6, 0.3) frente a cluster (columnas)")
print(tabla)The from-scratch implementation matches scikit-learn on all three datasets and handily beats k-means on moons and rings. Look at the last column: on rings (the graph has two components, the ideal case), and on moons is small but nonzero with a gap to . On the mixture k-means also works reasonably (groups are convex, ARI 0.801), and the table shows spectral clustering’s failure: its five errors are points from the wide cloud (standard deviation 1.5), whose tail reaches the other two; compact clouds are recovered intact.
Random walks and conductance
Ncut has an interpretation needing no relaxation. Define a random walk on the graph: from vertex , jump to with probability . Its transition matrix is , so : eigenvectors of with small eigenvalues are right eigenvectors of with eigenvalues near 1, functions the walk barely changes in one step. If the graph is connected, the chain has a unique stationary distribution : check in one line, since (the walk is a Markov chain, whose convergence is studied in the stochastic-processes module).
Proof
, and . The ratio is ; the other term is symmetric and their sum is Ncut.
∎Minimizing Ncut seeks a partition the equilibrium walk rarely escapes in one step. The smaller that probability, the longer the walker stays in its group before mixing with the rest, and eigenvectors of with eigenvalues near 1 are precisely functions remaining almost constant during that wait. The same idea with for several underlies diffusion maps.
import numpy as np, warnings
import scipy.sparse as sp
from sklearn.neighbors import NearestNeighbors
from sklearn.datasets import make_moons
warnings.filterwarnings("ignore")
X, y = make_moons(n_samples=600, noise=0.1, random_state=1) # las lunas del laboratorio
dist, ind = NearestNeighbors(n_neighbors=11).fit(X).kneighbors(X)
dist, ind = dist[:, 1:], ind[:, 1:]
s = np.median(dist[:, -1])
W = sp.csr_matrix((np.exp(-dist.ravel()**2 / (2 * s**2)), (np.repeat(np.arange(600), 10), ind.ravel())), shape=(600, 600))
W = W.maximum(W.T).toarray()
d = W.sum(1); P = W / d[:, None]; pi = d / d.sum()
print(f"pi es estacionaria: |pi P - pi| = {np.abs(pi @ P - pi).max():.1e}")
A = y == 0
corte = W[A][:, ~A].sum()
ncut = corte / d[A].sum() + corte / d[~A].sum()
p_AB = (pi[A, None] * P[A][:, ~A]).sum() / pi[A].sum()
p_BA = (pi[~A, None] * P[~A][:, A]).sum() / pi[~A].sum()
print(f"Ncut = {ncut:.5f} P(sale de A) + P(sale de B) = {p_AB:.5f} + {p_BA:.5f} = {p_AB + p_BA:.5f}")In the lab moons, an equilibrium walker crosses from one moon to the other in one step with probability 0.0001, once every ten thousand steps, and Ncut is the sum of both probabilities, 0.00021.
Conductance. Conductance of a set is , and of a graph, . Since , : Ncut and conductance measure the same up to factor 2. Cheeger’s inequality connects conductance with the second normalized-Laplacian eigenvalue of a connected graph, : small guarantees a low-conductance cut, and the upper-bound proof is constructive, a threshold sweep on the Fiedler vector like the game. This is spectral rounding’s only worst-case guarantee, for two groups.
Perturbation theory: why it works and when it stops
Relaxation guarantees nothing in general, but one regime makes spectral clustering exact and another around it makes it robust.
The ideal case
Proof
By property (3), the zero eigenspace is generated by , orthogonal (disjoint supports) with norm ; columns of are an orthonormal basis of that eigenspace, and any other is . Row is , a positive multiple of ; normalization leaves . Rows of an orthogonal matrix are orthonormal.
∎Ideally, k-means on normalized rows receives repeated mutually orthogonal points and separates them without error. The theorem does not depend on : the solver may return any eigenspace basis (if eigenvalue 0 is multiple, any rotation is equally valid), and rows still form orthogonal points, merely rotated.
Perturbation: the Davis–Kahan theorem
Real data do not give disconnected components: they give affinity , with block-diagonal . The question is how far eigenvectors move. Comparing individual eigenvectors makes no sense (in the ideal case they are not even defined), so compare the subspace they span, via principal angles between two -dimensional subspaces: if and have orthonormal columns and are singular values of , then and . It is 0 for identical subspaces and for orthogonal ones.
The original Davis and Kahan (1970) theorem requires separation between eigenvalues of one matrix and the other’s; Yu, Wang and Samworth’s variant (Biometrika, 2015) requires only gap of the unperturbed matrix, allowing direct application. For spectral clustering apply it to and with the smallest eigenvalues, and gap of the ideal matrix (with eigenvalues in increasing order, there is a gap on only one side). The second inequality matters: a rotation exists placing the perturbed eigenvector matrix within of ideal, so most rows are near the ideal case’s orthogonal rows (if many were far, Frobenius norm would be large). Ng, Jordan and Weiss (2001) analyze this kind of setup under assumptions about between- and within-group edge weights, giving conditions under which normalized rows cluster near orthogonal points.
The interactive quantifies this with an explicit model: , with block-diagonal (20, 15 and 10 nodes, weights uniform on within blocks) and symmetric uniform noise on . At affinity is ideal and at pure noise.
import numpy as np, warnings
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
rng = np.random.default_rng(0)
grupo = np.repeat([0, 1, 2], [20, 15, 10]); n = len(grupo)
W0 = np.triu(rng.uniform(0.5, 1.0, (n, n)) * (grupo[:, None] == grupo[None, :]), 1); W0 = W0 + W0.T
E = np.triu(rng.uniform(0, 1, (n, n)), 1); E = E + E.T
def lsym(W):
d = W.sum(1)
return np.eye(n) - W / np.sqrt(np.outer(d, d))
L0 = lsym(W0)
lam0, V0 = np.linalg.eigh(L0)
U0 = V0[:, :3]
delta = lam0[3] - lam0[2]
Y0 = U0 / np.linalg.norm(U0, axis=1, keepdims=True)
filas = np.unique(np.round(Y0, 8), axis=0)
print("lambda_1..5 de L_sym(0):", np.round(lam0[:5], 4), " hueco delta =", round(delta, 4))
print("filas normalizadas distintas:", len(filas), " Gram de esas filas:", np.round(filas @ filas.T, 6).ravel().tolist())
print(" t hueco(t) ||Delta||_op ||sin Theta||_F cota ARI")
for t in [0.05, 0.1, 0.2, 0.4, 0.6, 0.7, 0.75, 0.8, 0.9]:
L = lsym((1 - t) * W0 + t * E)
lam, V = np.linalg.eigh(L)
U = V[:, :3]
Dl = L - L0
op, fro = np.linalg.norm(Dl, 2), np.linalg.norm(Dl)
s = np.sqrt(max(0.0, 3 - np.linalg.norm(U0.T @ U)**2))
cota = 2 * min(np.sqrt(3) * op, fro) / delta
Y = U / np.linalg.norm(U, axis=1, keepdims=True)
et = KMeans(3, n_init=10, random_state=0).fit_predict(Y)
print(f"{t:5.2f} {lam[3] - lam[2]:7.4f} {op:10.4f} {s:15.4f} {cota:6.3f} {ARI(grupo, et):.3f}")Ideally there are three zero eigenvalues, a gap of 0.9867 to , and all 45 normalized rows reduce to 3 orthonormal vectors (their Gram matrix is identity), as the theorem states. Under perturbation actual subspace rotation grows slowly (0.0676 at ) and ARI stays at 1 until , though the bound is already 1.191 at , about 18 times actual rotation. Partition quality degrades between and , just as the perturbed-matrix gap falls from 0.06 to 0.012. Davis–Kahan is a worst-case bound: valid for any perturbation of that norm, including the worst aligned with the subspace, while random noise barely pushes in that direction. The theorem does explain the phenomenon’s shape: rotation is controlled by perturbation size divided by the gap, and when the gap disappears nothing protects the subspace.
The eigengap heuristic
The ideal case also suggests how to choose : with clear groups, are nearly zero, followed by a jump.
von Luxburg (2007, section 8.3) illustrates it with mixtures of increasing variance and concludes it works well for strongly defined groups and gives ambiguous results otherwise, like nearly any method for choosing . Range matters: beyond the first eigenvalues, a neighbor graph’s within-group gaps can compete with the one sought.
import numpy as np, warnings
from scipy.spatial.distance import pdist, squareform
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
z = np.random.default_rng(3).normal(size=(150, 2))
g = np.repeat([0, 1, 2], 50)
ang = np.pi / 2 + 2 * np.pi * np.arange(3) / 3
print(" s lambda_1..5 de L_sym k_hat (k <= 6) ARI con k = 3")
for s in [1, 2, 3, 4, 5, 6, 8]:
X = (s / np.sqrt(3)) * np.c_[np.cos(ang), np.sin(ang)][g] + z
W = np.exp(-squareform(pdist(X))**2 / 2); np.fill_diagonal(W, 0) # completo, sigma = 1
d = W.sum(1)
lam, V = np.linalg.eigh(np.eye(150) - W / np.sqrt(np.outer(d, d)))
k_hat = 1 + np.argmax(np.diff(lam[:7]))
Y = V[:, :3] / np.linalg.norm(V[:, :3], axis=1, keepdims=True)
et = KMeans(3, n_init=10, random_state=0).fit_predict(Y)
print(f"{s:2d} {np.round(lam[:5], 3)} {k_hat:14d} {ARI(g, et):.3f}")With the heuristic gives ; with it gives 1. But getting the count right does not imply a good partition: with , and ARI for three groups is only 0.542, because clouds overlap and no method recovers common-region points well. Choosing and clustering well are different problems; clustering evaluation covers the first with more tools.
Scale: sparse eigenvectors and Nyström
The eigenvalue step is expensive. Dense eigendecomposition of an matrix costs time and memory, computing eigenvectors when are needed. With a -neighbor graph the matrix has nonzero entries, and Krylov subspace methods (Lanczos, implicitly restarted in ARPACK behind eigsh) need only matrix–vector products, each costing . Iterations depend on the requested eigenvalues’ relative separation from the rest. Thus work with largest eigenvalues of (which="LA") or shift-invert on , factoring once and converting eigenvalues near to the inverse’s largest. Scikit-learn uses the latter with (negative shift avoids factoring a singular matrix, since 0 is an exact eigenvalue).
import numpy as np, time, warnings
import scipy.sparse as sp
from scipy.sparse.linalg import eigsh
from sklearn.neighbors import NearestNeighbors
from sklearn.datasets import make_moons
warnings.filterwarnings("ignore")
X, y = make_moons(n_samples=600, noise=0.1, random_state=2)
n = len(X)
dist, ind = NearestNeighbors(n_neighbors=11).fit(X).kneighbors(X)
s = np.median(dist[:, -1])
W = sp.csr_matrix((np.exp(-dist[:, 1:].ravel()**2 / (2 * s**2)), (np.repeat(np.arange(n), 10), ind[:, 1:].ravel())), shape=(n, n))
W = W.maximum(W.T)
d = np.asarray(W.sum(1)).ravel(); Dh = sp.diags(1 / np.sqrt(d))
M = (Dh @ W @ Dh).tocsr()
print(f"n = {n}: entradas no nulas = {W.nnz} ({W.nnz / n**2:.2%} de n^2), unas {W.nnz / n:.1f} por fila")
t0 = time.perf_counter(); mu, U = eigsh(M, k=3, which="LA"); t_disp = time.perf_counter() - t0
Md = M.toarray()
t0 = time.perf_counter(); mu_d, U_d = np.linalg.eigh(Md); t_dens = time.perf_counter() - t0
print(f"eigsh, 3 autovectores de la dispersa: {1e3 * t_disp:.0f} ms eigh, los {n} de la densa: {1e3 * t_dens:.0f} ms")
print("mismos autovalores:", np.allclose(np.sort(mu), mu_d[-3:]),
" |coseno| entre los segundos autovectores:", round(abs(U[:, -2] @ U_d[:, -2]), 6))
for N in [10**4, 10**5, 10**6]:
print(f"n = {N:>9,d}: densa {8 * N**2 / 1e9:8.1f} GB dispersa (unos 12 bytes por entrada no nula) {12 * W.nnz / n * N / 1e6:6.1f} MB")Both methods give the same eigenvalues and eigenvector (cosine 1), but sparse computes only 3 and in this cell takes a fraction of dense time. Memory decides: with points the dense matrix occupies 80 GB and sparse about 15 MB.
Nyström. If you want the full Gaussian graph (for example to avoid fixing ), you cannot even write . Fowlkes, Belongie, Chung and Malik (2004) apply the Nyström approximation to spectral clustering: choose landmark points, compute only affinities among them and between them and the rest, and approximate the missing block by . They use this to estimate degrees, normalize and obtain approximate orthonormal eigenvectors from eigendecomposition of an matrix: time and memory.
import numpy as np, warnings
from sklearn.datasets import make_circles
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
X, y = make_circles(n_samples=3000, noise=0.05, factor=0.45, random_state=3)
n, m, sigma = len(X), 100, 0.1
p = np.random.default_rng(0).permutation(n); X, y = X[p], y[p] # los m primeros son las referencias
def nucleo(P, Q):
return np.exp(-((P[:, None, :] - Q[None, :, :])**2).sum(-1) / (2 * sigma**2))
def potencia_simetrica(S, e):
"""S^e para S simétrica, descartando los autovalores casi nulos (pseudoinversa si e < 0)."""
l, V = np.linalg.eigh(S); ok = l > 1e-8 * l.max()
return (V[:, ok] * l[ok]**e) @ V[:, ok].T
A, B = nucleo(X[:m], X[:m]), nucleo(X[:m], X[m:])
br = B.sum(1)
d = np.r_[A.sum(1) + br, B.sum(0) + B.T @ (potencia_simetrica(A, -1) @ br)] # grados aproximados
sA, sB = np.sqrt(d[:m]), np.sqrt(d[m:])
A, B = A / np.outer(sA, sA), B / np.outer(sA, sB) # normalización D^-1/2 W D^-1/2
Ais = potencia_simetrica(A, -0.5)
S = A + Ais @ B @ B.T @ Ais # matriz m x m
lS, US = np.linalg.eigh(S); lS, US = lS[::-1], US[:, ::-1]
V = np.r_[A, B.T] @ Ais @ US[:, :2] / np.sqrt(lS[:2]) # n x 2, columnas ortonormales
Y = V / np.linalg.norm(V, axis=1, keepdims=True)
et = KMeans(2, n_init=10, random_state=0).fit_predict(Y)
print(f"m = {m} referencias para n = {n} puntos: autovalores aproximados {np.round(lS[:3], 4)}")
print(f"ortonormalidad: |V'V - I| = {np.abs(V.T @ V - np.eye(2)).max():.1e} ARI = {ARI(y, et):.3f}")
print(f"memoria: A y B ocupan {(A.nbytes + B.nbytes) / 1e6:.1f} MB; la W completa ocuparía {8 * n * n / 1e6:.0f} MB")With 100 landmarks for 3000 points, both approximate eigenvalues of the normalized matrix are practically 1 (two nearly disconnected groups), columns of are orthonormal and ARI is 1, using 2.4 MB instead of 72 MB. Accuracy depends on landmarks covering all groups: with too few, a small group may lack representatives and disappear.
Lab: scale sensitivity and image segmentation
Spectral clustering has few parameters, but they decide everything. The first cell sweeps of the complete Gaussian graph and the second of the neighbor graph, on 300-point moons and rings using NJW and dense eigenvectors (at this is fast and avoids iterative convergence problems when the graph is nearly disconnected and requested eigenvalues crowd near 0). Alongside ARI it prints the number of effective components, counting only weights above as edges.
import numpy as np, warnings
from scipy.linalg import eigh
from scipy.spatial.distance import pdist, squareform
from scipy.sparse.csgraph import connected_components
from sklearn.cluster import KMeans
from sklearn.datasets import make_moons, make_circles
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
def njw_denso(W, k=2):
d = np.maximum(W.sum(1), 1e-300)
M = W / np.sqrt(np.outer(d, d))
_, U = eigh(M, subset_by_index=[len(W) - k, len(W) - 1]) # solo los k mayores
Y = U / np.maximum(np.linalg.norm(U, axis=1, keepdims=True), 1e-300)
return KMeans(k, n_init=4, random_state=0).fit_predict(Y)
datos = {"lunas": make_moons(n_samples=300, noise=0.08, random_state=4),
"anillos": make_circles(n_samples=300, noise=0.05, factor=0.45, random_state=4)}
sigmas = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 3.0]
print("sigma " + "".join(f"{s:7.2f}" for s in sigmas))
for nombre, (X, y) in datos.items():
D2 = squareform(pdist(X))**2
ari, comp = [], []
for s in sigmas:
W = np.exp(-D2 / (2 * s**2)); np.fill_diagonal(W, 0)
ari.append(ARI(y, njw_denso(W))); comp.append(connected_components(W > 1e-10)[0])
print(f"{nombre:8s} ARI " + "".join(f"{a:7.3f}" for a in ari))
print(f"{'':8s} comp. " + "".join(f"{c:7d}" for c in comp))from sklearn.neighbors import kneighbors_graph
ks = [2, 3, 5, 10, 20, 40, 80]
print("k " + "".join(f"{k:7d}" for k in ks))
for nombre, (X, y) in datos.items():
ari, comp = [], []
for k in ks:
C = kneighbors_graph(X, k, include_self=False)
W = C.maximum(C.T).toarray()
ari.append(ARI(y, njw_denso(W))); comp.append(connected_components(W)[0])
print(f"{nombre:8s} ARI " + "".join(f"{a:7.3f}" for a in ari))
print(f"{'':8s} comp. " + "".join(f"{c:7d}" for c in comp))Both tables show the same window. At the low end, or break the graph into dozens of components (93 and 76 at , 21 and 30 at ) and the method returns pieces: ARI at most 0.152. With there are still 8 and 11 components, and ARI (0.693 and 0.366) depends on which pieces fall together. At the high end, or join groups: on rings ARI falls to 0 and on moons gradually degrades. The good window is narrow for both parameters: 0.02 to 0.1 for (these data have typical neighbor distance of order 0.1), and for , 5 to 10 on moons and 10 to 20 on rings, with the sole value good for both. The case deserves a note: the graph has several effective components yet ARI is 1 because weights below still exist and the first two eigenvectors still follow the two groups. This is a fragile balance, not something to rely on.
Segmenting a small image
Shi and Malik (2000) presented Ncut for image segmentation: each pixel is a vertex, and pixels less than apart are joined with weight
where is intensity (or a color or texture vector) and position. The graph is sparse by construction and encodes an idea intensity clustering cannot express: similarly intense but distant pixels need not go together, while nearby pixels with a smooth intensity change can. The test image is explicit and synthetic: pixels, a background with a horizontal gradient from 0.10 to 0.65, a disk of intensity 0.95 at upper right and one of 0.55 at lower left, plus Gaussian noise of standard deviation 0.04. The gradient gives the right-hand background the same intensity as the second disk.
import numpy as np, warnings
import scipy.sparse as sp
from scipy.sparse.linalg import eigsh
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score as ARI
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
lado = 32
fil, col = np.mgrid[0:lado, 0:lado]
verdad = np.zeros((lado, lado), int)
verdad[(fil - 9)**2 + (col - 22)**2 <= 36] = 1
verdad[(fil - 21)**2 + (col - 8)**2 <= 36] = 2
img = np.where(verdad == 1, 0.95, np.where(verdad == 2, 0.55, 0.1 + 0.55 * col / (lado - 1)))
img = img + np.random.default_rng(5).normal(0, 0.04, img.shape)
def grafo_pixeles(img, r=3, sigma_I=0.08, sigma_X=3.0):
h, w = img.shape
F, fi, co = img.ravel(), fil.ravel(), col.ravel()
filas, cols, pesos = [], [], []
for di in range(-r, r + 1):
for dj in range(-r, r + 1):
if (di, dj) == (0, 0) or di * di + dj * dj > r * r:
continue
ok = (fi + di >= 0) & (fi + di < h) & (co + dj >= 0) & (co + dj < w)
i = np.flatnonzero(ok); j = i + di * w + dj
filas.append(i); cols.append(j)
pesos.append(np.exp(-(F[i] - F[j])**2 / sigma_I**2) * np.exp(-(di * di + dj * dj) / sigma_X**2))
n = h * w
return sp.csr_matrix((np.concatenate(pesos), (np.concatenate(filas), np.concatenate(cols))), shape=(n, n))
def segmenta(W, k=3):
d = np.asarray(W.sum(1)).ravel(); Dh = sp.diags(1 / np.sqrt(d))
_, U = eigsh(Dh @ W @ Dh, k=k, which="LA")
Y = U / np.linalg.norm(U, axis=1, keepdims=True)
return KMeans(k, n_init=10, random_state=0).fit_predict(Y)
for sI in [0.03, 0.05, 0.08, 0.1, 0.15]:
print(f"sigma_I = {sI:.2f}: ARI espectral = {ARI(verdad.ravel(), segmenta(grafo_pixeles(img, sigma_I=sI))):.3f}")
W = grafo_pixeles(img)
print(f"{W.shape[0]} píxeles, {W.nnz} aristas dirigidas en la matriz ({W.nnz / W.shape[0]:.0f} por píxel)")
esp = segmenta(W).reshape(lado, lado)
km = KMeans(3, n_init=10, random_state=0).fit_predict(img.reshape(-1, 1)).reshape(lado, lado)
print(f"ARI de k-means sobre la intensidad = {ARI(verdad.ravel(), km.ravel()):.3f}")
fig, ax = plt.subplots(1, 4, figsize=(10, 2.8))
for a, im, t in zip(ax, [img, verdad, esp, km], ["imagen", "verdad", "espectral, sigma_I = 0.08", "k-means de intensidades"]):
a.imshow(im, cmap="gray" if t == "imagen" else "viridis"); a.set_title(t, fontsize=9); a.axis("off")
plt.tight_layout(); plt.show()With between 0.03 and 0.08, spectral clustering recovers all three segments exactly (ARI 1); k-means on intensity reaches 0.255 because the gradient distributes the background among three intensity groups. Scale matters again: with , the right edge of the second disk, where background already has similar intensity, stops being a cheap cut and segmentation breaks (ARI 0.25 with ). must be below local contrast of edges to preserve and above noise, here 0.04 per pixel.
Common mistakes
Exercises
Step 1 of 4. How do you go from to the sum of squares?
Step 1 of 3. What is ?
spectral_embedding(W, k): take a dense affinity matrix W of shape (n, n) (symmetric, nonnegative, zero diagonal, no isolated vertices) and return an (n, k) array whose rows are normalized to unit norm from the k lowest-eigenvalue eigenvectors of . Tests check shape and norms, agreement up to rotation with rather than another Laplacian, and separation of hidden data.import numpy as np
def spectral_embedding(W, k):
"""Filas normalizadas de los k autovectores de L_sym con menor autovalor. Devuelve un array (n, k)."""
W = np.asarray(W, dtype=float)
n = W.shape[0]
# tu código: grados, L_sym, autovectores (np.linalg.eigh los da en orden creciente), normalización por filas
return np.zeros((n, k))Summary
- Graph choice is the modeling decision: -neighborhood, neighbors (‘or’ or mutual), or complete Gaussian. -neighbor relations are asymmetric and must be symmetrized; of order and of order distance to the th neighbor are starting points, not rules.
- : the number of zero eigenvalues is the number of components, with indicators (, ) or times indicators () as eigenvectors.
- MinCut isolates vertices; RatioCut and Ncut seek balance and are NP-hard. With scaled indicators, and ; relaxation gives and , with as a lower bound on optimum and no rounding guarantee.
- Shi–Malik uses ; Ng–Jordan–Weiss uses with row normalization (after which both embeddings coincide); scikit-learn uses the former with k-means. With heterogeneous degrees, use a normalized form.
- for the equilibrium random walk, and Ncut and conductance differ by at most factor 2; Cheeger connects conductance with .
- Ideally normalized rows are orthonormal vectors; Davis–Kahan bounds subspace rotation by , a worst-case guarantee often pessimistic in practice. Eigengap chooses when groups are clear and is ambiguous otherwise.
- At scale: sparse graphs and Lanczos (
eigsh) for a few eigenvectors, or Nyström with landmarks. Never the full dense matrix.