TExcelTAD
Home › Spectral Graph Theory & Modern Graph Algorithms › Mini Project: A Spectral Clustering Tool for Small Graphs

Mini Project: A Spectral Clustering Tool for Small Graphs

In this project you build a small but complete spectral partitioning tool from the pieces of the course, and you test it honestly: against the true optimum found by brute force, and against the simplest competitor, random cuts. The tool

  1. builds the Laplacian and normalized Laplacian of a graph given as an edge list (Adjacency, Degree and Laplacian Matrices);
  2. computes the Fiedler vector with its own power iteration (The Courant-Fischer Theorem and Power Iteration);
  3. finds a low-conductance set with a sweep cut and reports Cheeger's bounds (The Sweep-Cut Algorithm);
  4. compares with the exact minimum conductance and with random cuts;
  5. extends to kk clusters (k-Way Spectral Clustering) and prints a report.

Each step is a complete program. All of them start with the same graph generator, so you can run any step on its own; every random choice comes from a seeded generator, so the numbers below are exactly what you will see.

Step 1: The graph and its matrices

The test graph has 20 vertices in two planted groups of 12 and 8 (edge probability 0.5 inside a group, 0.08 across). The tool must not use the labels; they are only for checking at the end. The program builds AA, DD, LL and NN and checks the basic facts: L1=0L\mathbf{1} = 0, LL is positive semidefinite, and the quadratic form of an indicator vector is a cut size.

python · try it yourself
import random
import numpy as np

def make_graph(n=20, sizes=(12, 8), p_in=0.5, p_out=0.08, seed=7):
    rng = random.Random(seed)
    group = [g for g, s in enumerate(sizes) for _ in range(s)]
    edges = [(u, v) for u in range(n) for v in range(u + 1, n)
             if rng.random() < (p_in if group[u] == group[v] else p_out)]
    return n, edges, group

def matrices(n, edges):
    A = np.zeros((n, n))
    for u, v in edges:
        A[u, v] = A[v, u] = 1
    d = A.sum(axis=1)
    L = np.diag(d) - A
    s = 1 / np.sqrt(d)
    N = np.eye(n) - s[:, None] * A * s[None, :]
    return A, d, L, N

n, edges, group = make_graph()
A, d, L, N = matrices(n, edges)
print(f"{n} vertices, {len(edges)} edges, degrees from {int(d.min())} to {int(d.max())}")
print("L 1 = 0:", bool(np.allclose(L @ np.ones(n), 0)))
print("smallest eigenvalues of L:", np.round(np.linalg.eigvalsh(L)[:3], 4) + 0.0)
print("smallest eigenvalues of N:", np.round(np.linalg.eigvalsh(N)[:3], 4) + 0.0)
S = np.array([1.0 if group[v] == 0 else 0.0 for v in range(n)])
cut = sum(group[u] != group[v] for u, v in edges)
print(f"planted cut: 1_S^T L 1_S = {float(S @ L @ S):.0f}, counted directly = {cut}")
20 vertices, 64 edges, degrees from 3 to 11
L 1 = 0: True
smallest eigenvalues of L: [0.     1.409  2.4888]
smallest eigenvalues of N: [0.     0.2725 0.6267]
planted cut: 1_S^T L 1_S = 10, counted directly = 10

Step 2: The Fiedler vector by power iteration

Implement the deflated power iteration on I+D−1/2AD−1/2=2I−NI + D^{-1/2}AD^{-1/2} = 2I - N, whose top eigenvector D1/21D^{1/2}\mathbf{1} is projected out at every step, so the iteration converges to the eigenvector of ν2\nu_2. Stop when the Rayleigh quotient changes by less than 10−1210^{-12}, and compare with NumPy.

python · try it yourself
import random
import numpy as np

def make_graph(n=20, sizes=(12, 8), p_in=0.5, p_out=0.08, seed=7):
    rng = random.Random(seed)
    group = [g for g, s in enumerate(sizes) for _ in range(s)]
    edges = [(u, v) for u in range(n) for v in range(u + 1, n)
             if rng.random() < (p_in if group[u] == group[v] else p_out)]
    return n, edges, group

def matrices(n, edges):
    A = np.zeros((n, n))
    for u, v in edges:
        A[u, v] = A[v, u] = 1
    d = A.sum(axis=1)
    s = 1 / np.sqrt(d)
    return A, d, np.diag(d) - A, np.eye(n) - s[:, None] * A * s[None, :]

def fiedler(A, d, tol=1e-12, max_steps=100000, seed=0):
    """Returns (nu_2 estimate, x = D^(-1/2) y, steps) by deflated power iteration on I + D^-1/2 A D^-1/2."""
    s = 1 / np.sqrt(d)
    M = s[:, None] * A * s[None, :]
    top = np.sqrt(d) / np.linalg.norm(np.sqrt(d))
    y = np.random.default_rng(seed).standard_normal(len(d))
    old = np.inf
    for step in range(1, max_steps + 1):
        y = y + M @ y
        y -= (y @ top) * top
        y /= np.linalg.norm(y)
        nu = 1 - float(y @ M @ y)                     # Rayleigh quotient of N
        if abs(old - nu) < tol:
            break
        old = nu
    x = y * s
    i = np.flatnonzero(np.abs(x) > 1e-9)[0]
    return nu, (x if x[i] > 0 else -x), step

n, edges, group = make_graph()
A, d, L, N = matrices(n, edges)
nu2, x, steps = fiedler(A, d)
vals, vecs = np.linalg.eigh(N)
y = vecs[:, 1] / np.sqrt(d)
y = y if y[np.flatnonzero(np.abs(y) > 1e-9)[0]] > 0 else -y
print(f"power iteration: nu_2 = {nu2:.6f} after {steps} steps;  numpy: nu_2 = {float(vals[1]):.6f}, nu_3 = {float(vals[2]):.6f}")
cos = abs(float(x @ (d * y))) / np.sqrt(float(x @ (d * x)) * float(y @ (d * y)))
print(f"agreement of the two vectors (cosine in the D-inner product): {cos:.6f}")
print("signs of x:      ", "".join("+" if v > 0 else "-" for v in x))
print("planted groups:  ", "".join("+" if g == 0 else "-" for g in group))
power iteration: nu_2 = 0.272530 after 50 steps;  numpy: nu_2 = 0.272530, nu_3 = 0.626726
agreement of the two vectors (cosine in the D-inner product): 1.000000
signs of x:       ++++++++-+++--------
planted groups:   ++++++++++++--------

Step 3: Sweep cut and Cheeger's bounds

Sort the vertices by xx, sweep, and report the best prefix together with the two sides of Cheeger's inequality: ν2/2\nu_2/2 is a lower bound on every cut's conductance (a certificate that no set is much better), and 2ν2\sqrt{2\nu_2} is the guarantee for the sweep.

python · try it yourself
import random
import numpy as np

def make_graph(n=20, sizes=(12, 8), p_in=0.5, p_out=0.08, seed=7):
    rng = random.Random(seed)
    group = [g for g, s in enumerate(sizes) for _ in range(s)]
    edges = [(u, v) for u in range(n) for v in range(u + 1, n)
             if rng.random() < (p_in if group[u] == group[v] else p_out)]
    return n, edges, group

def adjacency(n, edges):
    A = np.zeros((n, n))
    for u, v in edges:
        A[u, v] = A[v, u] = 1
    return A, A.sum(axis=1)

def fiedler_exact(A, d):
    s = 1 / np.sqrt(d)
    vals, vecs = np.linalg.eigh(np.eye(len(d)) - s[:, None] * A * s[None, :])
    x = vecs[:, 1] * s
    return float(vals[1]), (x if x[np.flatnonzero(np.abs(x) > 1e-9)[0]] > 0 else -x)

def conductance(edges, d, members):
    inside = set(members)
    cut = sum((u in inside) != (v in inside) for u, v in edges)
    vol = sum(d[v] for v in inside)
    return cut / min(vol, d.sum() - vol)

def sweep(edges, d, x):
    order = sorted(range(len(x)), key=lambda v: (x[v], v))
    best = min(range(1, len(x)), key=lambda i: conductance(edges, d, order[:i]))
    S = sorted(order[:best])
    return conductance(edges, d, S), S

n, edges, group = make_graph()
A, d = adjacency(n, edges)
nu2, x = fiedler_exact(A, d)
phi, S = sweep(edges, d, x)
planted = [v for v in range(n) if group[v] == 0]
print(f"nu_2 / 2 = {nu2 / 2:.4f}  <=  sweep conductance {phi:.4f}  <=  sqrt(2 nu_2) = {np.sqrt(2 * nu2):.4f}")
print(f"sweep set ({len(S)} vertices): {S}")
print(f"planted group 0 has conductance {conductance(edges, d, planted):.4f}")
nu_2 / 2 = 0.1363  <=  sweep conductance 0.2683  <=  sqrt(2 nu_2) = 0.7383
sweep set (8 vertices): [8, 12, 13, 14, 15, 16, 18, 19]
planted group 0 has conductance 0.2778

The sweep set is not exactly the planted group of 8: vertex 8 (planted in the first group) and vertex 17 (planted in the second) have more edges to the other side, and moving them gives a better cut than the planted one. The next step shows that the sweep found the true optimum. The sweep conductance is about twice ν2/2\nu_2/2, far from the worst case 2ν2\sqrt{2\nu_2}.

Step 4: Against brute force and random cuts

With 20 vertices, all 219−12^{19} - 1 cuts can be checked. The program computes the exact minimum conductance with bit operations over all subsets at once, and the best of 2000 random cuts (each vertex joins SS with probability 12\frac12) as a naive baseline.

python · try it yourself
import random
import numpy as np

def make_graph(n=20, sizes=(12, 8), p_in=0.5, p_out=0.08, seed=7):
    rng = random.Random(seed)
    group = [g for g, s in enumerate(sizes) for _ in range(s)]
    edges = [(u, v) for u in range(n) for v in range(u + 1, n)
             if rng.random() < (p_in if group[u] == group[v] else p_out)]
    return n, edges, group

def conductance(edges, d, members):
    inside = set(members)
    cut = sum((u in inside) != (v in inside) for u, v in edges)
    vol = sum(d[v] for v in inside)
    return cut / min(vol, d.sum() - vol)

n, edges, group = make_graph()
d = np.zeros(n)
for u, v in edges:
    d[u] += 1; d[v] += 1

# exact: every subset of {0..n-2} (vertex n-1 is always outside, so each cut is counted once)
masks = np.arange(1, 2 ** (n - 1), dtype=np.int64)
cut = np.zeros(len(masks))
for u, v in edges:
    cut += ((masks >> u) ^ (masks >> v)) & 1
vol = np.zeros(len(masks))
for v in range(n - 1):
    vol += d[v] * ((masks >> v) & 1)
phi_all = cut / np.minimum(vol, d.sum() - vol)
best = int(np.argmin(phi_all))
exact_set = [v for v in range(n - 1) if (int(masks[best]) >> v) & 1]

# spectral sweep (as in step 3)
A = np.zeros((n, n))
for u, v in edges:
    A[u, v] = A[v, u] = 1
s = 1 / np.sqrt(d)
vals, vecs = np.linalg.eigh(np.eye(n) - s[:, None] * A * s[None, :])
x = vecs[:, 1] * s
order = sorted(range(n), key=lambda v: (x[v], v))
sweep_phi = min(conductance(edges, d, order[:i]) for i in range(1, n))

rng = random.Random(1)
random_phis = []
for _ in range(2000):
    S = [v for v in range(n) if rng.random() < 0.5]
    if 0 < len(S) < n:
        random_phis.append(conductance(edges, d, S))
print(f"exact minimum conductance over {len(masks)} cuts: {float(phi_all[best]):.4f}, set {exact_set}")
print(f"spectral sweep:                                {sweep_phi:.4f}")
print(f"best of {len(random_phis)} random cuts:                     {min(random_phis):.4f}  (median {float(np.median(random_phis)):.4f})")
print(f"lower bound nu_2 / 2:                          {float(vals[1]) / 2:.4f}")
exact minimum conductance over 524287 cuts: 0.2683, set [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 17]
spectral sweep:                                0.2683
best of 2000 random cuts:                     0.3684  (median 0.6170)
lower bound nu_2 / 2:                          0.1363

The sweep matches the exhaustive optimum, which costs 2192^{19} evaluations instead of 19, while 2000 random cuts do not come close: a random cut crosses about half of all edges. And ν2/2\nu_2/2, computed without looking at any cut, certifies that no set has conductance below it.

Step 5: k clusters and a report

The final tool takes an edge list and a number of clusters kk, embeds the vertices with the bottom kk eigenvectors of NN (rows normalized, as in Ng-Jordan-Weiss), runs a small seeded kk-means, and prints each cluster's size and conductance, plus the eigenvalues that justify the choice of kk. It is tested on a 45-vertex graph with three planted groups.

python · try it yourself
import random
import numpy as np

def make_graph(n, sizes, p_in, p_out, seed):
    rng = random.Random(seed)
    group = [g for g, s in enumerate(sizes) for _ in range(s)]
    edges = [(u, v) for u in range(n) for v in range(u + 1, n)
             if rng.random() < (p_in if group[u] == group[v] else p_out)]
    return n, edges, group

def kmeans(X, k, seed, restarts=8, iters=50):
    rng = np.random.default_rng(seed)
    best, best_cost = None, np.inf
    for _ in range(restarts):
        C = X[rng.choice(len(X), size=k, replace=False)]
        for _ in range(iters):
            lab = ((X[:, None] - C[None]) ** 2).sum(-1).argmin(1)
            C = np.array([X[lab == j].mean(0) if np.any(lab == j) else C[j] for j in range(k)])
        cost = ((X - C[lab]) ** 2).sum()
        if cost < best_cost:
            best, best_cost = lab, cost
    return best

def spectral_report(n, edges, k, seed=0):
    A = np.zeros((n, n))
    for u, v in edges:
        A[u, v] = A[v, u] = 1
    d = A.sum(axis=1)
    s = 1 / np.sqrt(d)
    vals, vecs = np.linalg.eigh(np.eye(n) - s[:, None] * A * s[None, :])
    U = vecs[:, :k] / np.linalg.norm(vecs[:, :k], axis=1, keepdims=True)
    lab = kmeans(U, k, seed)
    print(f"graph: {n} vertices, {len(edges)} edges")
    print(f"nu_1..nu_{k + 1}: {np.round(vals[:k + 1], 4) + 0.0}   gap after nu_{k}: {float(vals[k] - vals[k - 1]):.4f}")
    clusters = sorted((sorted(np.flatnonzero(lab == j).tolist()) for j in range(k)), key=lambda c: c[0])
    phis = []
    for i, c in enumerate(clusters):
        inside = set(c)
        cut = sum((u in inside) != (v in inside) for u, v in edges)
        phis.append(cut / sum(d[v] for v in c))
        print(f"  cluster {i}: {len(c):2} vertices, conductance {phis[-1]:.4f}")
    print(f"worst cluster conductance {max(phis):.4f}; no {k} disjoint sets can do better than nu_{k}/2 = {float(vals[k - 1]) / 2:.4f}")
    return clusters

n, edges, group = make_graph(45, (20, 15, 10), 0.4, 0.03, seed=2024)
clusters = spectral_report(n, edges, 3)
truth = [sorted(v for v in range(n) if group[v] == g) for g in range(3)]
print("clusters equal the planted groups:", sorted(clusters) == sorted(truth))
graph: 45 vertices, 152 edges
nu_1..nu_4: [0.     0.1505 0.2187 0.4935]   gap after nu_3: 0.2749
  cluster 0: 20 vertices, conductance 0.1067
  cluster 1: 15 vertices, conductance 0.1373
  cluster 2: 10 vertices, conductance 0.2308
worst cluster conductance 0.2308; no 3 disjoint sets can do better than nu_3/2 = 0.1093
clusters equal the planted groups: True

The report prints the evidence along with the answer: three small eigenvalues and a large gap after the third say "three clusters"; the worst cluster's conductance is compared with νk/2\nu_k/2, the higher-order Cheeger lower bound on the worst conductance of any kk disjoint sets, so the report shows how far from provably optimal the clustering can be (here at most a factor of about 2).

Ideas for extensions

  • Replace np.linalg.eigh in step 5 by the power iteration of step 2 with deflation of several vectors (block power iteration, or scipy.sparse.linalg.eigsh) to handle sparse graphs with thousands of vertices.
  • Add recursive bisection (Shi-Malik style): split by the sweep cut, then split the larger side again, and compare with kk-way clustering.
  • Try the failure cases of Higher-Order Cheeger and When Spectral Partitioning Fails: attach a whisker to the test graph and watch the Fiedler vector move to it; then remove degree-1 vertices first.
  • Use the tool on a real network (an e-mail graph, a co-authorship graph) and compare the clusters with known attributes.

Test yourself

In step 3, what does ν2/2\nu_2/2 certify?

  1. The sweep set's exact conductance
  2. That no set at all has conductance below ν2/2\nu_2/2 (the easy side of Cheeger's inequality)
  3. The number of clusters
  4. Nothing

Why do random cuts perform so badly in step 4?

  1. They are too slow
  2. A random cut crosses about half of all edges, while a good cut crosses only the few edges between groups
  3. Random numbers are biased
  4. They ignore degrees

In the power iteration of step 2, why is D1/21D^{1/2}\mathbf{1} projected out at every step?

  1. To normalize the vector
  2. It is the eigenvector of ν1=0\nu_1 = 0 (the top eigenvector of I+D−1/2AD−1/2I + D^{-1/2}AD^{-1/2}); removing it makes the iteration converge to the eigenvector of ν2\nu_2
  3. To keep the entries positive
  4. To speed up the matrix product

Which evidence does the step 5 report use to support the choice k=3k = 3?

  1. The number of edges
  2. Three small normalized-Laplacian eigenvalues followed by a large gap
  3. The maximum degree
  4. The diameter