Module contents
Lesson 6 of 24Advanced 105 min

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.

[ ]k-means versus spectral clustering on moons and ringsBrowser
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 v2v_2 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.

InteractiveFrom moons to separable clouds
Points and graph; color: value of v2v_2
Spectral embedding (v2,v3)(v_2, v_3); color: spectral clusters
v₂ →↑ v₃
  • positive value of v2v_2
  • negative value of v2v_2 (intensity: magnitude)
  • graph edge (opacity: weight)
Data
Similarity graph
Construction
8
0.300
Point color
Edges / connected components933 / 1
λ2\lambda_2 of LsymL_{\mathrm{sym}}0.0008
λ3\lambda_3 and λ4\lambda_40.0035 0.0055
Spectral ARI (NJW, k=2k = 2)1.000
k-means ARI on the points0.256
Connected graph, but inter-group edges are few or weak: λ2\lambda_2 is small and v2v_2 is almost constant in each group. In the embedding, groups form separate clouds.
Data (left) with similarity graph and spectral embedding (right). Initially the moons' 8-neighbor graph is connected, but λ2\lambda_2 is nearly zero: v2v_2 has one sign on each moon and the embedding separates the clouds, with ARI 1 versus k-means' low ARI. Try three things. Lower kk to 3: the graph breaks into many components, several zero eigenvalues appear and eigenvectors mark pieces rather than moons. Switch to 'complete' and increase σ\sigma: all edges weigh nearly the same, v2v_2 stops following shape and clustering fails. With rings and the neighbor graph there are exactly two components: the ideal case.

Similarity graphs

The method depends entirely on an object you construct before calculating anything: the graph.

The relation “jj is one of my kk neighbors” is not symmetric: an isolated point has kk 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 kk). Never pass the directed, asymmetric matrix to an algorithm assuming symmetry: eigsh assumes W=W⊤\mat{W} = \mat{W}\T and returns a result without warning. Scikit-learn symmetrizes with 12(C+C⊤)\tfrac12(\mat{C} + \mat{C}\T), where C\mat{C} 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 Rd\R^d, kk-neighbor graphs are connected with probability tending to 1 if kk grows as log⁡n\log n, and von Luxburg suggests that order of magnitude as a first approximation for large graphs. For radius ε\varepsilon, 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 σ\sigma. The Gaussian kernel converts distances into weights, and σ\sigma decides what “near” means. With σ\sigma far below typical neighbor distance, almost all weights are zero and the graph breaks apart; with σ\sigma far above data diameter, all weights approach 1, the graph is almost complete and uniform and no structure remains to cut. Practical rules tie σ\sigma to local scale: order of mean distance to the kkth neighbor, with k≈log⁡n+1k \approx \log n + 1 (von Luxburg, 2007, section 8.1). Zelnik-Manor and Perona (2004) propose a per-point local scale, wij=exp⁡ ⁣(−∥xi−xj∥2/(σiσj))w_{ij} = \exp\!\big(-\norm{\vb{x}_i - \vb{x}_j}^2 / (\sigma_i \sigma_j)\big) with σi\sigma_i distance from xi\vb{x}_i to its seventh neighbor, adapting the graph to differently dense regions.

[ ]Symmetry, connectivity and graph scale on moonsBrowser
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 k=8k = 8, one in five directed edges (20.4%) has no reverse: asymmetry is not a detail. The “or” graph has 2 components from k=5k = 5 (and 1 at k=12k = 12, once edges between moons sneak in), while mutual needs k=12k = 12 to fall to 2: at k=3k = 3 it has 87. And σ\sigma has a window: at σ=0.02\sigma = 0.02, below typical neighbor distance (0.097 to the eighth neighbor), some points have degree of order 10−1010^{-10}, practically isolated; at σ=10\sigma = 10, 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 di=∑jwijd_i = \sum_j w_{ij} be degree of vertex ii, D=diag⁡(d1,…,dn)\mat{D} = \diag(d_1, \dots, d_n) and, for A⊆VA \subseteq V, ∣A∣\abs{A} its vertex count and vol⁡(A)=∑i∈Adi\operatorname{vol}(A) = \sum_{i \in A} d_i its volume. Assume positive degrees (no isolated vertices) when D−1/2\mat{D}^{-1/2} appears.

L=D−W,Lsym=D−1/2L D−1/2=I−D−1/2WD−1/2,Lrw=D−1L=I−D−1W.\mat{L} = \mat{D} - \mat{W}, \qquad \mat{L}_{\mathrm{sym}} = \mat{D}^{-1/2}\mat{L}\,\mat{D}^{-1/2} = \mat{I} - \mat{D}^{-1/2}\mat{W}\mat{D}^{-1/2}, \qquad \mat{L}_{\mathrm{rw}} = \mat{D}^{-1}\mat{L} = \mat{I} - \mat{D}^{-1}\mat{W}.
Proof

(1) f⊤Lf=∑idifi2−∑i,jwijfifj\vb{f}\T\mat{L}\vb{f} = \sum_i d_i f_i^2 - \sum_{i,j} w_{ij} f_i f_j. Since ∑idifi2=∑i,jwijfi2=∑i,jwijfj2\sum_i d_i f_i^2 = \sum_{i,j} w_{ij} f_i^2 = \sum_{i,j} w_{ij} f_j^2 (by symmetry), write 12∑i,jwij(fi2−2fifj+fj2)\tfrac12 \sum_{i,j} w_{ij}(f_i^2 - 2 f_i f_j + f_j^2). Since wij≥0w_{ij} \ge 0, the sum is nonnegative.

(2) D−1Lu=λu  ⟺  Lu=λDu\mat{D}^{-1}\mat{L}\vb{u} = \lambda\vb{u} \iff \mat{L}\vb{u} = \lambda\mat{D}\vb{u}; with g=D1/2u\vb{g} = \mat{D}^{1/2}\vb{u}, this is equivalent to D−1/2LD−1/2g=λg\mat{D}^{-1/2}\mat{L}\mat{D}^{-1/2}\vb{g} = \lambda\vb{g}. Lsym\mat{L}_{\mathrm{sym}} is symmetric and g⊤Lsymg=u⊤Lu≥0\vb{g}\T\mat{L}_{\mathrm{sym}}\vb{g} = \vb{u}\T\mat{L}\vb{u} \ge 0.

(3) If f⊤Lf=0\vb{f}\T\mat{L}\vb{f} = 0, every term wij(fi−fj)2w_{ij}(f_i - f_j)^2 vanishes: ff is constant along each edge and hence on each connected component. Thus null⁡(L)=span⁡{1A1,…,1Ac}\nullsp(\mat{L}) = \spn\{\vb{1}_{A_1}, \dots, \vb{1}_{A_c}\}, of dimension cc because indicators have disjoint supports. For Lrw\mat{L}_{\mathrm{rw}} the kernel is the same (D−1\mat{D}^{-1} is invertible), and for Lsym\mat{L}_{\mathrm{sym}} it is its image under D1/2\mat{D}^{1/2} by (2). Since all three matrices are diagonalizable (the two symmetric ones by the spectral theorem, and Lrw\mat{L}_{\mathrm{rw}} is similar to Lsym\mat{L}_{\mathrm{sym}}), algebraic and geometric multiplicity agree.

(4) By the same argument as (1), 2u⊤Du−u⊤Lu=u⊤(D+W)u=12∑i,jwij(ui+uj)2≥02\vb{u}\T\mat{D}\vb{u} - \vb{u}\T\mat{L}\vb{u} = \vb{u}\T(\mat{D} + \mat{W})\vb{u} = \tfrac12\sum_{i,j} w_{ij}(u_i + u_j)^2 \ge 0, so generalized quotient u⊤Lu/u⊤Du\vb{u}\T\mat{L}\vb{u} / \vb{u}\T\mat{D}\vb{u} lies in [0,2][0, 2], and eigenvalues of Lu=λDu\mat{L}\vb{u} = \lambda\mat{D}\vb{u} 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 Lsym\mat{L}_{\mathrm{sym}}: its kernel vectors are not constant per component, but proportional to di\sqrt{d_i}. This affects the Ng, Jordan and Weiss algorithm.

[ ]Laplacian properties checked on a three-component graphBrowser
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 [0,2][0, 2], while L\mat{L} has no such bound. A component indicator is a zero eigenvector of Lrw\mat{L}_{\mathrm{rw}} but not Lsym\mat{L}_{\mathrm{sym}}, whose zero vector is D1/21A\mat{D}^{1/2}\vb{1}_A.

Graph cuts: MinCut, RatioCut and Ncut

Clustering partitions vertices into A1,…,AkA_1, \dots, A_k so edges between parts have low weight. For disjoint A,B⊆VA, B \subseteq V, let W(A,B)=∑i∈A,j∈BwijW(A, B) = \sum_{i \in A, j \in B} w_{ij}, and for a part AA, Aˉ=V∖A\bar A = V \setminus A and cut(A,Aˉ)=W(A,Aˉ)\mathrm{cut}(A, \bar A) = W(A, \bar A).

Why minimum cut isolates vertices. With k=2k = 2, minimum cut is polynomial-time solvable (Stoer and Wagner, 1997), but gives useless partitions: separating a single vertex ii costs exactly its degree did_i, 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 (∣A∣\abs{A}) or edge weight (vol⁡(A)\operatorname{vol}(A)). Since 1a+1n−a\frac1a + \frac1{n-a} is minimized at a=n/2a = n/2, 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.

InteractiveCut game
12-node graph; edge thickness: weight. Side A in orange, side Aˉ\bar A in blue
0.60.50.40.30.3123456789101112
  • cut edge
  • side AA
  • side Aˉ\bar A
Show
Sizes ∣A∣|A|, ∣Aˉ∣|\bar A|1, 11
cut(A,Aˉ)\mathrm{cut}(A, \bar A)0.400
RatioCut0.4364
Ncut1.0118
This is the graph’s minimum cut, cut=0.40\mathrm{cut} = 0.40: it isolates a low-degree vertex. RatioCut and Ncut penalize it because one side has only one node. Find a better partition under these criteria.
A 12-node graph: an octahedron (nodes 1 through 6, degree 4), a triangle (7, 8 and 9) joined by two edges of weight 0.3, and a 9-10-11-12 tail with weights 0.6, 0.5 and 0.4. The initial state is minimum cut, 0.4: it isolates node 12, penalized by RatioCut and Ncut. Click nodes to change sides and seek the best partition. Then reveal the Fiedler vector: that of LL (unnormalized) cuts nodes 9 through 12 by sign, with RatioCut 0.75, 3.75 times optimal (0.2), because nodes 7 and 8 are near zero; threshold sweeping on that vector finds the optimum. The LrwL_{\mathrm{rw}} vector gives optimal Ncut directly by sign.
[ ]Brute-force cuts and Fiedler vectors on the 12-node graphBrowser
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: λ2\lambda_2 values are lower bounds for these optima (0.0930 ≤ 0.2 and 0.0675 ≤ 0.0869), and the Fiedler vector of L\mat{L} has values −0.006-0.006 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 A⊂VA \subset V, define the scaled indicator vector

fi={∣Aˉ∣/∣A∣i∈A,−∣A∣/∣Aˉ∣i∈Aˉ.f_i = \begin{cases} \sqrt{\abs{\bar A} / \abs{A}} & i \in A, \\ -\sqrt{\abs{A} / \abs{\bar A}} & i \in \bar A. \end{cases}

Using identity (1) of the theorem, f⊤Lf=12∑i,jwij(fi−fj)2\vb{f}\T\mat{L}\vb{f} = \tfrac12\sum_{i,j} w_{ij}(f_i - f_j)^2, only crossing edges contribute. For them (fi−fj)2=∣Aˉ∣∣A∣+∣A∣∣Aˉ∣+2=n(1∣A∣+1∣Aˉ∣)(f_i - f_j)^2 = \frac{\abs{\bar A}}{\abs{A}} + \frac{\abs{A}}{\abs{\bar A}} + 2 = n\left(\frac{1}{\abs{A}} + \frac{1}{\abs{\bar A}}\right), and each edge appears twice in the ordered-pair sum, canceling 12\tfrac12:

f⊤Lf=n⋅RatioCut(A,Aˉ),∑ifi=0,∥f∥2=n.\vb{f}\T\mat{L}\vb{f} = n \cdot \mathrm{RatioCut}(A, \bar A), \qquad \sum_i f_i = 0, \qquad \norm{\vb{f}}^2 = n.

(You will prove this step by step in the first exercise.) Minimizing RatioCut therefore means minimizing f⊤Lf\vb{f}\T\mat{L}\vb{f} over vectors of that form, orthogonal to 1\vb{1} and with norm n\sqrt n. There are only 2n−1−12^{n-1} - 1 such vectors; allowing any f∈Rn\vb{f} \in \R^n with both constraints makes the problem

min⁡f∈Rnf⊤Lfsujeto af⊥1, ∥f∥2=n,\min_{\vb{f} \in \R^n} \vb{f}\T\mat{L}\vb{f} \quad \text{sujeto a} \quad \vb{f} \perp \vb{1},\ \norm{\vb{f}}^2 = n,

a Rayleigh quotient restricted to the orthogonal complement of the first eigenvector. By the Courant–Fischer theorem, the minimum is nλ2(L)n\lambda_2(\mat{L}) 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,

λ2(L)≤min⁡ARatioCut(A,Aˉ),\lambda_2(\mat{L}) \le \min_A \mathrm{RatioCut}(A, \bar A),

which is what the cell showed: 0.0930≤0.20.0930 \le 0.2.

kk groups

For kk parts, define H∈Rn×k\mat{H} \in \R^{n \times k} with hij=1/∣Aj∣h_{ij} = 1/\sqrt{\abs{A_j}} if i∈Aji \in A_j and 0 otherwise. Its columns are orthonormal, H⊤H=Ik\mat{H}\T\mat{H} = \mat{I}_k, and each column hj\vb{h}_j satisfies hj⊤Lhj=cut(Aj,Aˉj)/∣Aj∣\vb{h}_j\T\mat{L}\vb{h}_j = \mathrm{cut}(A_j, \bar A_j)/\abs{A_j} (the same calculation with only one nonzero side). Summing,

RatioCut(A1,…,Ak)=tr⁡(H⊤LH).\mathrm{RatioCut}(A_1, \dots, A_k) = \tr(\mat{H}\T\mat{L}\mat{H}).

The relaxation permits any H\mat{H} with H⊤H=Ik\mat{H}\T\mat{H} = \mat{I}_k, and the minimum of tr⁡(H⊤LH)\tr(\mat{H}\T\mat{L}\mat{H}) under that constraint is λ1+⋯+λk\lambda_1 + \dots + \lambda_k, attained by the first kk eigenvectors (Ky Fan’s theorem, a consequence of Courant–Fischer). The solution is determined only up to rotation: UQ\mat{U}\mat{Q}, with orthogonal Q\mat{Q}, is equally good. Rounding therefore cannot read the partition column by column; use k-means on rows of U\mat{U}: 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:

fi=vol⁡(Aˉ)/vol⁡(A)  (i∈A),fi=−vol⁡(A)/vol⁡(Aˉ)  (i∈Aˉ),f_i = \sqrt{\operatorname{vol}(\bar A)/\operatorname{vol}(A)} \ \ (i \in A), \qquad f_i = -\sqrt{\operatorname{vol}(A)/\operatorname{vol}(\bar A)} \ \ (i \in \bar A),

and the same calculation gives (Df)⊤1=0(\mat{D}\vb{f})\T\vb{1} = 0, f⊤Df=vol⁡(V)\vb{f}\T\mat{D}\vb{f} = \operatorname{vol}(V) and f⊤Lf=vol⁡(V)⋅Ncut(A,Aˉ)\vb{f}\T\mat{L}\vb{f} = \operatorname{vol}(V) \cdot \mathrm{Ncut}(A, \bar A). Relaxing gives

min⁡ff⊤Lfsujeto aDf⊥1, f⊤Df=vol⁡(V),\min_{\vb{f}} \vb{f}\T\mat{L}\vb{f} \quad \text{sujeto a} \quad \mat{D}\vb{f} \perp \vb{1},\ \vb{f}\T\mat{D}\vb{f} = \operatorname{vol}(V),

whose solution is the second vector of generalized problem Lu=λDu\mat{L}\vb{u} = \lambda\mat{D}\vb{u}, namely the second eigenvector of Lrw\mat{L}_{\mathrm{rw}}. Substituting g=D1/2f\vb{g} = \mat{D}^{1/2}\vb{f} converts it to the Rayleigh quotient of Lsym\mat{L}_{\mathrm{sym}} restricted to g⊥D1/21\vb{g} \perp \mat{D}^{1/2}\vb{1} (derived in the second exercise). The analogous bound is λ2(Lrw)≤min⁡Ncut\lambda_2(\mat{L}_{\mathrm{rw}}) \le \min \mathrm{Ncut}: in the cell, 0.0675≤0.08690.0675 \le 0.0869. For kk groups, the H\mat{H} version yields the first kk generalized eigenvectors.

[ ]Scaled indicators satisfy relaxation identitiesBrowser
# 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 4k4k vertices missing some rungs, where optimal RatioCut cuts 2 edges and is 2/k2/k, while unnormalized spectral clustering always cuts horizontally, kk edges, with RatioCut 1: a factor k/2k/2 worse, order nn (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 L\mat{L} 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 Lsym\mat{L}_{\mathrm{sym}} are D1/21Aj\mat{D}^{1/2}\vb{1}_{A_j} (up to rotation): each point’s row is proportional to di\sqrt{d_i}. 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 Lrw\mat{L}_{\mathrm{rw}} are D−1/2\mat{D}^{-1/2} times those of Lsym\mat{L}_{\mathrm{sym}}, their rows differ only by factor di−1/2d_i^{-1/2}, 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 n→∞n \to \infty under general conditions, whereas unnormalized may not be. Among normalized forms she favors Lrw\mat{L}_{\mathrm{rw}}, whose ideal eigenvectors are indicators independent of di\sqrt{d_i}; Lsym\mat{L}_{\mathrm{sym}} 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 12(C+C⊤)\tfrac12(\mat{C} + \mat{C}\T); with "rbf", the complete Gaussian kernel with gamma =1/(2σ2)= 1/(2\sigma^2) and gamma=1.0 by default), computes eigenvectors of Lsym\mat{L}_{\mathrm{sym}} using ARPACK, multiplies them by D−1/2\mat{D}^{-1/2} (converts to Lrw\mat{L}_{\mathrm{rw}} vectors), and applies k-means without row normalization. Thus it is the Shi–Malik variant with k-means. Default gamma=1.0 means σ≈0.71\sigma \approx 0.71 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 k=10k = 10-neighbor graph with Gaussian weights (σ\sigma equal to median distance to the tenth neighbor), converts to the normalized matrix, computes the kk 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.

[ ]Ng, Jordan and Weiss from scratch, compared with scikit-learnBrowser
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 λ1=λ2=0\lambda_1 = \lambda_2 = 0 (the graph has two components, the ideal case), and on moons λ2\lambda_2 is small but nonzero with a gap to λ3\lambda_3. 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 ii, jump to jj with probability pij=wij/dip_{ij} = w_{ij}/d_i. Its transition matrix is P=D−1W\mat{P} = \mat{D}^{-1}\mat{W}, so Lrw=I−P\mat{L}_{\mathrm{rw}} = \mat{I} - \mat{P}: eigenvectors of Lrw\mat{L}_{\mathrm{rw}} with small eigenvalues are right eigenvectors of P\mat{P} with eigenvalues near 1, functions the walk barely changes in one step. If the graph is connected, the chain has a unique stationary distribution πi=di/vol⁡(V)\pi_i = d_i / \operatorname{vol}(V): check in one line, since (π⊤P)j=∑idivol⁡(V)wijdi=djvol⁡(V)(\boldsymbol\pi\T\mat{P})_j = \sum_i \frac{d_i}{\operatorname{vol}(V)} \frac{w_{ij}}{d_i} = \frac{d_j}{\operatorname{vol}(V)} (the walk is a Markov chain, whose convergence is studied in the stochastic-processes module).

Proof

P(X0∈A,X1∈Aˉ)=∑i∈A,j∈Aˉπipij=∑i∈A,j∈Aˉdivol⁡(V)wijdi=cut(A,Aˉ)vol⁡(V)\Pr(X_0 \in A, X_1 \in \bar A) = \sum_{i \in A, j \in \bar A} \pi_i p_{ij} = \sum_{i \in A, j \in \bar A} \frac{d_i}{\operatorname{vol}(V)} \frac{w_{ij}}{d_i} = \frac{\mathrm{cut}(A, \bar A)}{\operatorname{vol}(V)}, and P(X0∈A)=vol⁡(A)/vol⁡(V)\Pr(X_0 \in A) = \operatorname{vol}(A)/\operatorname{vol}(V). The ratio is cut(A,Aˉ)/vol⁡(A)\mathrm{cut}(A, \bar A)/\operatorname{vol}(A); 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 P\mat{P} with eigenvalues near 1 are precisely functions remaining almost constant during that wait. The same idea with Pt\mat{P}^t for several tt underlies diffusion maps.

InteractiveA random walk that rarely crosses
Walker distribution after t=72t = 72 steps (size and opacity: probability)
Mass on the other moon versus tt (logarithmic scale)
equilibrium
  • upper moon (AA)
  • lower moon (Aˉ\bar A)
  • starting point
72
Mass on the other moon after tt steps16.6 %
Mass on the other moon at equilibrium, π(other)\pi(\text{other})50.3 %
P(Aˉ∣A)\Pr(\bar A \mid A) in one step from π\pi0.07 %
P(A∣Aˉ)\Pr(A \mid \bar A) in one step from π\pi0.07 %
Ncut(A,Aˉ)\mathrm{Ncut}(A, \bar A) of the two moons0.0015
After 72 steps only 16.6 % of the probability has crossed to the other moon; at equilibrium it would be 50.3 %. From the stationary distribution, one step crosses with probability 0.07 % (from the upper moon) or 0.07 % (from the lower): that is Ncut.
The first interactive's moons (8-neighbor graph, σ=0.3\sigma = 0.3) and a walker starting at the marked point. Each point's size and opacity increase with probability the walker is there after tt steps. The initial point is on the upper moon nearest the other: already in the first step some probability crosses one of the few between-moon edges. Right, mass crossed to the other moon versus tt on a logarithmic scale, with equilibrium line π(otra luna)\pi(\text{otra luna}). Click a point in a moon's center and the curve takes even longer to rise. The P(Aˉ∣A)\Pr(\bar A \mid A) and P(A∣Aˉ)\Pr(A \mid \bar A) readouts sum exactly to Ncut.
[ ]Ncut is one-step escape probabilityBrowser
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 ϕ(A)=cut(A,Aˉ)/min⁡{vol⁡(A),vol⁡(Aˉ)}\phi(A) = \mathrm{cut}(A, \bar A) / \min\{\operatorname{vol}(A), \operatorname{vol}(\bar A)\}, and of a graph, ϕG=min⁡Aϕ(A)\phi_G = \min_A \phi(A). Since max⁡{x,y}≤x+y≤2max⁡{x,y}\max\{x, y\} \le x + y \le 2\max\{x, y\}, ϕ(A)≤Ncut(A,Aˉ)≤2ϕ(A)\phi(A) \le \mathrm{Ncut}(A, \bar A) \le 2\phi(A): 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, λ2/2≤ϕG≤2λ2\lambda_2/2 \le \phi_G \le \sqrt{2\lambda_2}: small λ2\lambda_2 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 D1/21Aj\mat{D}^{1/2}\vb{1}_{A_j}, orthogonal (disjoint supports) with norm vol⁡(Aj)\sqrt{\operatorname{vol}(A_j)}; columns of D1/2Hvol\mat{D}^{1/2}\mat{H}_{\mathrm{vol}} are an orthonormal basis of that eigenspace, and any other is D1/2HvolQ\mat{D}^{1/2}\mat{H}_{\mathrm{vol}}\mat{Q}. Row ii is di qg(i)⊤/vol⁡(Ag(i))\sqrt{d_i}\,\vb{q}_{g(i)}\T / \sqrt{\operatorname{vol}(A_{g(i)})}, a positive multiple of qg(i)⊤\vb{q}_{g(i)}\T; normalization leaves qg(i)⊤\vb{q}_{g(i)}\T. Rows of an orthogonal matrix are orthonormal.

∎

Ideally, k-means on normalized rows receives kk repeated mutually orthogonal points and separates them without error. The theorem does not depend on Q\mat{Q}: the solver may return any eigenspace basis (if eigenvalue 0 is multiple, any rotation is equally valid), and rows still form kk orthogonal points, merely rotated.

Perturbation: the Davis–Kahan theorem

Real data do not give disconnected components: they give affinity W=W0+ruido\mat{W} = \mat{W}_0 + \text{ruido}, with block-diagonal W0\mat{W}_0. 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 Θ\Theta between two kk-dimensional subspaces: if U\mat{U} and U^\hat{\mat{U}} have orthonormal columns and σ1,…,σk\sigma_1, \dots, \sigma_k are singular values of U⊤U^\mat{U}\T\hat{\mat{U}}, then cos⁡θj=σj\cos\theta_j = \sigma_j and ∥sin⁡Θ∥F2=k−∥U⊤U^∥F2\norm{\sin\Theta}_F^2 = k - \norm{\mat{U}\T\hat{\mat{U}}}_F^2. It is 0 for identical subspaces and k\sqrt k 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 δ\delta of the unperturbed matrix, allowing direct application. For spectral clustering apply it to Σ=Lsym(W0)\mat{\Sigma} = \mat{L}_{\mathrm{sym}}(\mat{W}_0) and Σ^=Lsym(W)\hat{\mat{\Sigma}} = \mat{L}_{\mathrm{sym}}(\mat{W}) with the kk smallest eigenvalues, and gap δ=λk+1−λk\delta = \lambda_{k+1} - \lambda_k 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 O(∥Δ∥/δ)\bigO(\norm{\Delta}/\delta) of ideal, so most rows are near the ideal case’s kk 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 kk orthogonal points.

The interactive quantifies this with an explicit model: W(t)=(1−t)W0+tE\mat{W}(t) = (1 - t)\mat{W}_0 + t\mat{E}, with block-diagonal W0\mat{W}_0 (20, 15 and 10 nodes, weights uniform on [0.5,1][0.5, 1] within blocks) and symmetric uniform noise E\mat{E} on [0,1][0, 1]. At t=0t = 0 affinity is ideal and at t=1t = 1 pure noise.

InteractivePerturbing a block matrix
Affinity WW (45 × 45, nodes ordered by block)
Normalized rows of [u1 u2 u3][u_1\ u_2\ u_3], aligned and projected; color: true block
e₁e₂e₃
Subspace rotation ∥sin⁡Θ∥F\|\sin\Theta\|_F (blue), Davis–Kahan bound (red, clipped at 2) and ARI (green) versus tt
  • actual ∥sin⁡Θ∥F\|\sin\Theta\|_F
  • bound 2min⁡(3∥Δ∥op,∥Δ∥F)/(λ4−λ3)2\min(\sqrt{3}\|\Delta\|_{\mathrm{op}}, \|\Delta\|_F)/(\lambda_4 - \lambda_3)
  • NJW ARI
  • ideal vertex ege_g of each block
0.00
t = 0.00
Gap of Lsym(t)L_{\mathrm{sym}}(t): λ4−λ3\lambda_4 - \lambda_30.977
∥Δ∥op\|\Delta\|_{\mathrm{op}}, perturbation of LsymL_{\mathrm{sym}}0.000
∥sin⁡Θ∥F\|\sin\Theta\|_F actual (maximum 3≈1.73\sqrt{3} \approx 1.73)0.000
Davis–Kahan bound0.000
NJW ARI1.000
Ideal case: LsymL_{\mathrm{sym}} is block diagonal, λ1=λ2=λ3=0\lambda_1 = \lambda_2 = \lambda_3 = 0, and each normalized row falls exactly on one of the three vertices.
Left: affinity W(t)W(t), with nodes ordered by block. Center: normalized rows of the first three eigenvectors of LsymL_{\mathrm{sym}}, rotated by Procrustes to align with ideal directions e1,e2,e3e_1, e_2, e_3 and projected onto the plane orthogonal to (1,1,1)(1, 1, 1), where directions form a triangle. Below versus tt: actual subspace rotation ∥sin⁡Θ∥F\|\sin\Theta\|_F, Davis–Kahan bound and ARI. Raise tt from 0: rows spread around vertices without mixing for a long time, and partition quality degrades only when perturbed gap λ4−λ3\lambda_4 - \lambda_3 closes near t=0.75t = 0.75. The bound exceeds 1 early, around t=0.16t = 0.16: a valid but very pessimistic worst-case guarantee for this noise.
[ ]Ideal case and perturbation: Davis–Kahan in numbersBrowser
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 λ4\lambda_4, 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 t=0.2t = 0.2) and ARI stays at 1 until t=0.6t = 0.6, though the bound is already 1.191 at t=0.2t = 0.2, about 18 times actual rotation. Partition quality degrades between t=0.7t = 0.7 and 0.90.9, 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 kk: with kk clear groups, λ1,…,λk\lambda_1, \dots, \lambda_k 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 kk. Range Kmax⁡K_{\max} matters: beyond the first eigenvalues, a neighbor graph’s within-group gaps can compete with the one sought.

InteractiveThe eigengap closes
Three clouds; color: NJW clusters with k=3k = 3
The first 10 eigenvalues of LsymL_{\mathrm{sym}}; green: largest gap with k≤6k \le 6
k̂ = 3
  • eigenvalues λ1,…,λk^\lambda_1, \dots, \lambda_{\hat k}
  • rest of spectrum
  • largest gap (eigengap)
6.0
Graph
λ2, λ3, λ4\lambda_2,\ \lambda_3,\ \lambda_40.002, 0.006, 0.424
Eigengap λ4−λ3\lambda_4 - \lambda_30.418
k^\hat k (largest gap, k≤6k \le 6)3
NJW ARI with k=3k = 31.000
The first three eigenvalues are small and the gap λ4−λ3=0.418\lambda_4 - \lambda_3 = 0.418 is the largest candidate: the heuristic succeeds, k^=3\hat k = 3.
Three Gaussian clouds with standard deviation 1 and centers at an equilateral triangle of side ss. Right: first 10 eigenvalues of LsymL_{\mathrm{sym}} and largest gap with k≤6k \le 6. Initially (s=6s = 6, complete graph with σ=1\sigma = 1) the first three eigenvalues are nearly zero and the gap after λ3\lambda_3 dominates: k^=3\hat k = 3. Bring clouds closer: the gap after λ3\lambda_3 shrinks, λ2\lambda_2 and λ3\lambda_3 rise, and ARI with k=3k = 3 falls simultaneously. The heuristic still says k^=3\hat k = 3 when the partition is mediocre, and only below s≈2.5s \approx 2.5 does the largest gap move after λ1\lambda_1 and propose one group. Switch to the 10-neighbor graph: with well-separated clouds it also gives k^=3\hat k = 3, but around s=3.6s = 3.6 the largest gap moves after λ5\lambda_5, and with overlapping clouds it proposes 5 groups. In that graph, within-cloud gaps beyond λ3\lambda_3 compete with the group-separating gap.
[ ]Eigengap versus separation of three cloudsBrowser
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 s≥3s \ge 3 the heuristic gives k^=3\hat k = 3; with s≤2s \le 2 it gives 1. But getting the count right does not imply a good partition: with s=3s = 3, k^=3\hat k = 3 and ARI for three groups is only 0.542, because clouds overlap and no method recovers common-region points well. Choosing kk 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 n×nn \times n matrix costs O(n3)\bigO(n^3) time and O(n2)\bigO(n^2) memory, computing nn eigenvectors when kk are needed. With a knnk_{\mathrm{nn}}-neighbor graph the matrix has O(nknn)\bigO(n k_{\mathrm{nn}}) nonzero entries, and Krylov subspace methods (Lanczos, implicitly restarted in ARPACK behind eigsh) need only matrix–vector products, each costing O(nnz)\bigO(\mathrm{nnz}). Iterations depend on the requested eigenvalues’ relative separation from the rest. Thus work with largest eigenvalues of D−1/2WD−1/2\mat{D}^{-1/2}\mat{W}\mat{D}^{-1/2} (which="LA") or shift-invert on Lsym\mat{L}_{\mathrm{sym}}, factoring Lsym−σI\mat{L}_{\mathrm{sym}} - \sigma\mat{I} once and converting eigenvalues near σ\sigma to the inverse’s largest. Scikit-learn uses the latter with σ=−10−5\sigma = -10^{-5} (negative shift avoids factoring a singular matrix, since 0 is an exact eigenvalue).

[ ]Sparse versus dense: memory, time and same resultBrowser
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 10510^5 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 knnk_{\mathrm{nn}}), you cannot even write W\mat{W}. Fowlkes, Belongie, Chung and Malik (2004) apply the Nyström approximation to spectral clustering: choose m≪nm \ll n landmark points, compute only affinities A∈Rm×m\mat{A} \in \R^{m \times m} among them and B∈Rm×(n−m)\mat{B} \in \R^{m \times (n - m)} between them and the rest, and approximate the missing block by B⊤A−1B\mat{B}\T\mat{A}^{-1}\mat{B}. They use this to estimate degrees, normalize and obtain approximate orthonormal eigenvectors from eigendecomposition of an m×mm \times m matrix: O(nm2)\bigO(nm^2) time and O(nm)\bigO(nm) memory.

[ ]Nyström: spectral clustering without the full matrixBrowser
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 V\mat{V} 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 σ\sigma of the complete Gaussian graph and the second kk of the neighbor graph, on 300-point moons and rings using NJW and dense eigenvectors (at n=300n = 300 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 10−1010^{-10} as edges.

[ ]Sensitivity to full-graph sigmaBrowser
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))
[ ]Sensitivity to neighbor countBrowser
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, σ=0.01\sigma = 0.01 or k=2k = 2 break the graph into dozens of components (93 and 76 at σ=0.01\sigma = 0.01, 21 and 30 at k=2k = 2) and the method returns pieces: ARI at most 0.152. With k=3k = 3 there are still 8 and 11 components, and ARI (0.693 and 0.366) depends on which pieces fall together. At the high end, σ≥0.5\sigma \ge 0.5 or k≥40k \ge 40 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 σ\sigma (these data have typical neighbor distance of order 0.1), and for kk, 5 to 10 on moons and 10 to 20 on rings, with k=10k = 10 the sole value good for both. The σ=0.02\sigma = 0.02 case deserves a note: the graph has several effective components yet ARI is 1 because weights below 10−1010^{-10} 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 rr apart are joined with weight

wij=exp⁡ ⁣(−∣Fi−Fj∣2σI2)exp⁡ ⁣(−∥Xi−Xj∥2σX2),w_{ij} = \exp\!\left(-\frac{\abs{F_i - F_j}^2}{\sigma_I^2}\right)\exp\!\left(-\frac{\norm{\vb{X}_i - \vb{X}_j}^2}{\sigma_X^2}\right),

where FF is intensity (or a color or texture vector) and X\vb{X} 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: 32×3232 \times 32 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.

[ ]Spectral segmentation of an image with a pixel graphBrowser
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 σI\sigma_I 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 σI≥0.1\sigma_I \ge 0.1, 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 σI=0.1\sigma_I = 0.1). σI\sigma_I must be below local contrast of edges to preserve and above noise, here 0.04 per pixel.

Common mistakes

Exercises

ProofThe Laplacian quadratic form and RatioCut
Prove: Let WW be symmetric with nonnegative entries, L=D−WL = D - W and, for A⊂VA \subset V with nonempty AA and Aˉ\bar A, let fi=∣Aˉ∣/∣A∣f_i = \sqrt{|\bar A|/|A|} if i∈Ai \in A and fi=−∣A∣/∣Aˉ∣f_i = -\sqrt{|A|/|\bar A|} if i∈Aˉi \in \bar A. Prove fTLf=12∑i,jwij(fi−fj)2f^{\mathsf T} L f = \tfrac12\sum_{i,j} w_{ij}(f_i - f_j)^2 and fTLf=∣V∣⋅RatioCut(A,Aˉ)f^{\mathsf T} L f = |V| \cdot \mathrm{RatioCut}(A, \bar A).
0
Write fTLf=fTDf−fTWff^{\mathsf T} L f = f^{\mathsf T} D f - f^{\mathsf T} W f and use symmetry of WW. Then distinguish pairs (i,j)(i, j) by each vertex's side.

Step 1 of 4. How do you go from f⊤Df−f⊤Wf\vb{f}\T\mat{D}\vb{f} - \vb{f}\T\mat{W}\vb{f} to the sum of squares?

ProofFrom Ncut to the generalized eigenvalue problem
Prove: With fi=vol(Aˉ)/vol(A)f_i = \sqrt{\mathrm{vol}(\bar A)/\mathrm{vol}(A)} on AA and fi=−vol(A)/vol(Aˉ)f_i = -\sqrt{\mathrm{vol}(A)/\mathrm{vol}(\bar A)} on Aˉ\bar A, prove (Df)T1=0(Df)^{\mathsf T}\mathbf 1 = 0, fTDf=vol(V)f^{\mathsf T}Df = \mathrm{vol}(V) and fTLf=vol(V) Ncut(A,Aˉ)f^{\mathsf T}Lf = \mathrm{vol}(V)\,\mathrm{Ncut}(A, \bar A), and that relaxation leads to Lu=λDuL u = \lambda D u.
0
Repeat the RatioCut calculation with volumes rather than cardinalities. For relaxation use Lagrange multipliers or substitute g=D1/2fg = D^{1/2} f.

Step 1 of 3. What is (Df)⊤1=∑idifi(\mat{D}\vb{f})\T\vb{1} = \sum_i d_i f_i?

NumericComponents and zero eigenvalues
A 30-vertex similarity graph has three connected components: one of 20 vertices, one of 9 and one isolated vertex without edges. How many zero eigenvalues does its unnormalized Laplacian L=D−WL = D - W have?
NumericNcut of two triangles
Two triangles with edge weights 1 are joined by one edge of weight 0.5 between a vertex in each. Let AA be one triangle. What is Ncut(A,Aˉ)\mathrm{Ncut}(A, \bar A)?
NumericReading the eigengap
A graph's first ten LsymL_{\mathrm{sym}} eigenvalues are 0, 0.004, 0.009, 0.013, 0.21, 0.25, 0.31, 0.34, 0.37, 0.520,\ 0.004,\ 0.009,\ 0.013,\ 0.21,\ 0.25,\ 0.31,\ 0.34,\ 0.37,\ 0.52. What cluster count k^\hat k does the eigengap heuristic propose with Kmax⁡=8K_{\max} = 8?
NumericNcut from escape probabilities
In a graph with vol(A)=300\mathrm{vol}(A) = 300 and vol(Aˉ)=200\mathrm{vol}(\bar A) = 200, an equilibrium random walk in AA moves to Aˉ\bar A on the next step with probability 0.02. What is Ncut(A,Aˉ)\mathrm{Ncut}(A, \bar A)?
NumericThe Davis–Kahan bound
Ideal affinity has λ3=0\lambda_3 = 0 and λ4=0.4\lambda_4 = 0.4 (LsymL_{\mathrm{sym}} eigenvalues in increasing order). Laplacian perturbation Δ\Delta has ∥Δ∥op=0.05\|\Delta\|_{\mathrm{op}} = 0.05 and ∥Δ∥F=0.12\|\Delta\|_F = 0.12. What bound does Yu, Wang and Samworth's variant give for ∥sin⁡Θ∥F\|\sin\Theta\|_F of the first three eigenvectors' subspace?
QuizWhich Laplacian with heterogeneous degrees?
Your similarity graph has a very dense group (degrees around 40) and a sparse one (degrees around 5), plus peripheral degree-1 vertices. Which Laplacian is appropriate and why?
QuizDiagnosing a graph from its spectrum
You seek 3 groups with a complete Gaussian graph. The first eight eigenvalues of LsymL_{\mathrm{sym}} are 0,0,0,0,0,0,2⋅10−9,4⋅10−90, 0, 0, 0, 0, 0, 2\cdot10^{-9}, 4\cdot10^{-9} and ARI is low. What is happening?
QuizSymmetrizing the neighbor graph
You have two groups of very different densities touching in one region: the dense one has 500 close points and the sparse one 100. With the 10-neighbor 'or' graph the method mixes them. What change is most sensible to try first?
QuizOne million points
You have 10610^6 embeddings of dimension 64 and want spectral clustering with about 20 groups. What do you do?
QuizThe role of row normalization
In Ng, Jordan and Weiss's algorithm, what happens if you remove row normalization and apply k-means directly to rows of LsymL_{\mathrm{sym}} eigenvectors?
CodeNg, Jordan and Weiss spectral embedding
Implement 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 Lsym=I−D−1/2WD−1/2L_{\mathrm{sym}} = I - D^{-1/2} W D^{-1/2}. Tests check shape and norms, agreement up to rotation with LsymL_{\mathrm{sym}} 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))
Shift+Enter to run

Summary

Key idea
Spectral clustering groups by connectivity rather than distance to a center. It frames clustering as a balanced cut of a similarity graph (RatioCut or Ncut), relaxes it to a Rayleigh–Ritz problem solved by the first Laplacian eigenvectors, and rounds with k-means on their rows. It works exactly when the graph has one component per group and robustly when spectral gap λk+1−λk\lambda_{k+1} - \lambda_k is large relative to perturbation.
  • Graph choice is the modeling decision: ε\varepsilon-neighborhood, kk neighbors (‘or’ or mutual), or complete Gaussian. kk-neighbor relations are asymmetric and must be symmetrized; kk of order log⁡n\log n and σ\sigma of order distance to the kkth neighbor are starting points, not rules.
  • f⊤Lf=12∑wij(fi−fj)2\vb{f}\T\mat{L}\vb{f} = \tfrac12\sum w_{ij}(f_i - f_j)^2: the number of zero eigenvalues is the number of components, with indicators (L\mat{L}, Lrw\mat{L}_{\mathrm{rw}}) or D1/2\mat{D}^{1/2} times indicators (Lsym\mat{L}_{\mathrm{sym}}) as eigenvectors.
  • MinCut isolates vertices; RatioCut and Ncut seek balance and are NP-hard. With scaled indicators, f⊤Lf=n RatioCut\vb{f}\T\mat{L}\vb{f} = n\,\mathrm{RatioCut} and f⊤Lf=vol⁡(V) Ncut\vb{f}\T\mat{L}\vb{f} = \operatorname{vol}(V)\,\mathrm{Ncut}; relaxation gives Lu=λu\mat{L}\vb{u} = \lambda\vb{u} and Lu=λDu\mat{L}\vb{u} = \lambda\mat{D}\vb{u}, with λ2\lambda_2 as a lower bound on optimum and no rounding guarantee.
  • Shi–Malik uses Lrw\mat{L}_{\mathrm{rw}}; Ng–Jordan–Weiss uses Lsym\mat{L}_{\mathrm{sym}} with row normalization (after which both embeddings coincide); scikit-learn uses the former with k-means. With heterogeneous degrees, use a normalized form.
  • Ncut(A,Aˉ)=P(Aˉ∣A)+P(A∣Aˉ)\mathrm{Ncut}(A, \bar A) = \Pr(\bar A \mid A) + \Pr(A \mid \bar A) for the equilibrium random walk, and Ncut and conductance differ by at most factor 2; Cheeger connects conductance with λ2\lambda_2.
  • Ideally normalized rows are kk orthonormal vectors; Davis–Kahan bounds subspace rotation by 2min⁡(k∥Δ∥op,∥Δ∥F)/δ2\min(\sqrt k\norm{\Delta}_{\mathrm{op}}, \norm{\Delta}_F)/\delta, a worst-case guarantee often pessimistic in practice. Eigengap chooses kk when groups are clear and is ambiguous otherwise.
  • At scale: sparse graphs and Lanczos (eigsh) for a few eigenvectors, or Nyström with m≪nm \ll n landmarks. Never the full dense matrix.