TExcelTAD

The Sweep-Cut Algorithm

The proof of the hard side of Cheeger's inequality is really an algorithm: sort the vertices by an eigenvector and return the best prefix. This lesson implements it in O(m+nlog⁡n)O(m + n\log n) time after the vector is known, and makes one observation that matters in practice: the proof never needs an exact eigenvector. Any degree-balanced vector with a small Rayleigh quotient gives a good cut, so a few hundred iterations of the power method are enough.

The algorithm

text
sweep_cut(G, x)                       x: one real value per vertex
1  order ← vertices sorted by x                                  O(n log n)
2  inS ← all false;  cut ← 0;  vol ← 0;  best ← ∞
3  for i ← 1 to n − 1                                            (prefix S_i = first i vertices)
4      v ← order[i];  inS[v] ← true;  vol ← vol + d(v)
5      for each neighbour u of v
6          if inS[u] then cut ← cut − w(u, v)   (edge now inside S)
7          else           cut ← cut + w(u, v)   (edge now leaves S)
8      φ ← cut / min(vol, vol(V) − vol)
9      if φ < best then best ← φ;  bestIndex ← i
10 return the first bestIndex vertices of order, best

Each edge is touched twice over the whole sweep (once from each endpoint), so lines 3 to 9 cost O(n+m)O(n + m); the sort dominates with O(nlog⁡n)O(n \log n). Computing xx is the expensive part.

Which vector? For the guarantee ϕ≤2ν2\phi \le \sqrt{2\nu_2}, sweep over x=D−1/2yx = D^{-1/2}y where yy is an eigenvector of the normalized Laplacian for ν2\nu_2; equivalently xx solves the generalized problem Lx=ν2DxLx = \nu_2 Dx. Sweeping over the eigenvector of the unnormalized LL also works well in practice and has an analogous guarantee for h(G)h(G) in terms of λ2(L)\lambda_2(L) and dmax⁡d_{\max}.

Approximate vectors suffice. Read the proof again: steps 1 to 3 use only that ∑vdvxv=0\sum_v d_v x_v = 0 and that the Rayleigh quotient R(x)=xTLxxTDxR(x) = \frac{x^{\mathsf{T}} L x}{x^{\mathsf{T}} D x} is small. So:

Theorem (sweep for any vector). For every x≠0x \ne 0 with ∑vdvxv=0\sum_v d_v x_v = 0, the best sweep set of xx has conductance at most 2R(x)\sqrt{2R(x)}.

This is what makes spectral partitioning practical: run power iteration (or Lanczos) until R(x)≤(1+ε)ν2R(x) \le (1 + \varepsilon)\nu_2, and sweep.

An implementation

The program plants three groups of 12 vertices with denser edges inside, computes xx two ways (exactly with eigh, and approximately with 30 steps of deflated power iteration on I+D−1/2AD−1/2I + D^{-1/2}AD^{-1/2}, whose top eigenvalues correspond to the bottom of NN), and checks the sweep guarantee for each.

python · try it yourself
import random
import numpy as np

def sweep_cut(adj, deg, x):
    """Best prefix of the vertices sorted by x: returns (conductance, set)."""
    order = sorted(range(len(x)), key=lambda v: (x[v], v))
    total = sum(deg)
    in_s = [False] * len(x)
    cut = vol = 0.0
    best, best_i = float("inf"), 0
    for i, v in enumerate(order[:-1], start=1):
        in_s[v] = True
        vol += deg[v]
        for u in adj[v]:
            cut += -1 if in_s[u] else 1
        phi = cut / min(vol, total - vol)
        if phi < best:
            best, best_i = phi, i
    return best, sorted(order[:best_i])

rng = random.Random(11)
n, k = 36, 12
edges = [(u, v) for u in range(n) for v in range(u + 1, n)
         if rng.random() < (0.5 if u // k == v // k else 0.04)]
adj = [[] for _ in range(n)]
for u, v in edges:
    adj[u].append(v); adj[v].append(u)
deg = np.array([len(a) for a in adj], dtype=float)
A = np.zeros((n, n))
for u, v in edges:
    A[u, v] = A[v, u] = 1
L = np.diag(deg) - A
s = 1 / np.sqrt(deg)
M = s[:, None] * A * s[None, :]                    # D^(-1/2) A D^(-1/2) = I - N
vals, vecs = np.linalg.eigh(np.eye(n) - M)
nu2 = float(vals[1])

def rayleigh(x):
    return float(x @ L @ x / (x @ (deg * x)))

top = np.sqrt(deg) / np.linalg.norm(np.sqrt(deg))   # eigenvector of nu_1 = 0, to deflate
y = np.random.default_rng(3).standard_normal(n)
for _ in range(30):
    y = y + M @ y                                   # (I + M) has eigenvalues 2 - nu_i >= 0
    y -= (y @ top) * top
    y /= np.linalg.norm(y)

print(f"{len(edges)} edges, nu_2 = {nu2:.4f}, nu_3 = {float(vals[2]):.4f}, nu_4 = {float(vals[3]):.4f}")
print(f"Cheeger bound sqrt(2 nu_2) = {np.sqrt(2 * nu2):.4f}")
for name, x in [("exact eigenvector", vecs[:, 1] * s), ("30 power steps", y * s)]:
    R = rayleigh(x)
    phi, S = sweep_cut(adj, deg, x)
    print(f"{name:18}: R(x) = {R:.4f}, sweep conductance {phi:.4f} <= sqrt(2 R) = {np.sqrt(2 * R):.4f}")
    print(f"{'':18}  set found: {S}")
107 edges, nu_2 = 0.1484, nu_3 = 0.2058, nu_4 = 0.4947
Cheeger bound sqrt(2 nu_2) = 0.5448
exact eigenvector : R(x) = 0.1484, sweep conductance 0.1343 <= sqrt(2 R) = 0.5448
                    set found: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
30 power steps    : R(x) = 0.1659, sweep conductance 0.1600 <= sqrt(2 R) = 0.5759
                    set found: [1, 2, 3, 5, 6, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

The exact eigenvector separates one planted group, vertices 12 to 23, from the other two (the set printed is the complement), with conductance 0.13, far below the Cheeger bound: the bound is pessimistic for graphs with clear clusters. The 30-step vector is worse. With three groups, ν2\nu_2 and ν3\nu_3 are close (the spectrum has a cluster of three small eigenvalues, one per group, as the lesson on spectral clustering explains), so power iteration mixes the two eigenvectors for a long time and the sweep set straddles the groups. Still, its conductance respects its own guarantee 2R(x)\sqrt{2R(x)}, as the theorem promises for every vector.

In C++

The same sweep with adjacency lists and an incremental cut, together with the power iteration that produces the vector, on a 3×123 \times 12 grid in which the middle column's horizontal edges have been removed except one. The optimal cut is obvious to a human; the algorithm finds it from the spectrum.

cpp · try it yourself
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <numeric>
#include <vector>

using Graph = std::vector<std::vector<int>>;

// Fiedler-like vector by power iteration on (I + D^-1/2 A D^-1/2), deflating sqrt(d).
std::vector<double> spectral_vector(const Graph& g, int steps) {
    int n = (int)g.size();
    std::vector<double> sd(n), y(n), z(n);
    double norm_top = 0;
    for (int v = 0; v < n; ++v) { sd[v] = std::sqrt((double)g[v].size()); norm_top += sd[v] * sd[v]; }
    for (int v = 0; v < n; ++v) y[v] = std::sin(1.0 + 7.0 * v);          // a fixed, irregular start vector
    for (int t = 0; t < steps; ++t) {
        for (int v = 0; v < n; ++v) {
            double s = 0;
            for (int u : g[v]) s += y[u] / sd[u];
            z[v] = y[v] + s / sd[v];
        }
        double dot = 0, nrm = 0;
        for (int v = 0; v < n; ++v) dot += z[v] * sd[v];
        for (int v = 0; v < n; ++v) { z[v] -= dot / norm_top * sd[v]; nrm += z[v] * z[v]; }
        for (int v = 0; v < n; ++v) y[v] = z[v] / std::sqrt(nrm);
    }
    for (int v = 0; v < n; ++v) y[v] /= sd[v];                         // x = D^-1/2 y
    return y;
}

// Best prefix of the vertices sorted by x; returns its conductance and fills `best_set`.
double sweep(const Graph& g, const std::vector<double>& x, std::vector<int>& best_set) {
    int n = (int)g.size();
    std::vector<int> order(n);
    std::iota(order.begin(), order.end(), 0);
    std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return x[a] < x[b]; });
    long total = 0;
    for (auto& nb : g) total += (long)nb.size();
    std::vector<char> in(n, 0);
    long cut = 0, vol = 0;
    double best = 1e9;
    int best_i = 0;
    for (int i = 0; i + 1 < n; ++i) {
        int v = order[i];
        in[v] = 1;
        vol += (long)g[v].size();
        for (int u : g[v]) cut += in[u] ? -1 : 1;
        double phi = double(cut) / double(std::min(vol, total - vol));
        if (phi < best) { best = phi; best_i = i + 1; }
    }
    best_set.assign(order.begin(), order.begin() + best_i);
    std::sort(best_set.begin(), best_set.end());
    return best;
}

int main() {
    const int R = 3, C = 12, n = R * C;
    Graph g(n);
    auto add = [&](int a, int b) { g[a].push_back(b); g[b].push_back(a); };
    for (int i = 0; i < R; ++i)
        for (int j = 0; j < C; ++j) {
            int v = i * C + j;
            if (i + 1 < R) add(v, v + C);
            if (j + 1 < C && (j != 5 || i == 1)) add(v, v + 1);   // only row 1 crosses the middle
        }
    for (int steps : {20, 200, 2000}) {
        std::vector<int> S;
        double phi = sweep(g, spectral_vector(g, steps), S);
        std::printf("%4d power steps: sweep conductance %.4f, |S| = %zu\n", steps, phi, S.size());
        if (steps == 2000) {
            for (int i = 0; i < R; ++i) {
                for (int j = 0; j < C; ++j)
                    std::printf("%c", std::binary_search(S.begin(), S.end(), i * C + j) ? 'S' : '.');
                std::printf("\n");
            }
        }
    }
}
  20 power steps: sweep conductance 0.0182, |S| = 18
 200 power steps: sweep conductance 0.0182, |S| = 18
2000 power steps: sweep conductance 0.0182, |S| = 18
......SSSSSS
......SSSSSS
......SSSSSS

The sweep separates the two halves through the single remaining edge, conductance 1/551/55 (each half has volume 55), already after 20 steps: here ν2\nu_2 is far below ν3\nu_3, so power iteration converges quickly.

Common mistakes

  • Sweeping the wrong vector. The guarantee 2ν2\sqrt{2\nu_2} is for x=D−1/2yx = D^{-1/2}y, not for the eigenvector yy of NN itself. On regular graphs the two differ only by a constant factor and it does not matter; on graphs with hubs it does.
  • Splitting at zero or at the median. Taking the signs of xx, or forcing equal halves, is one particular sweep set. The theorem is about the best of all n−1n - 1 prefixes; a fixed split can be far worse (see the cockroach graph in Higher-Order Cheeger).
  • Recomputing the cut from scratch for every prefix. That costs O(nm)O(nm); the incremental update in lines 5 to 7 is what makes the sweep linear.
  • Trusting a repeated eigenvalue's vector. If ν2=ν3\nu_2 = \nu_3, the solver may return any vector of the eigenspace and the sweep result depends on it; sweep a few vectors of the eigenspace, or all of the bottom eigenvectors, and keep the best set.

Local versions

The sweep needs a global vector, so it costs at least linear time. For huge graphs one often wants a small cluster around a given seed vertex in time proportional to the cluster, not the graph. Spielman and Teng (2004) gave the first such local clustering algorithm (Nibble: truncated random walks from the seed, followed by sweeps), and Andersen, Chung and Lang (2006) replaced the walk by an approximate personalized PageRank vector computed by a push procedure, with a sweep over pv/dvp_v/d_v. Given a seed in a target set of conductance ϕ\phi, Nibble finds a set of conductance about O(ϕ1/3polylog⁡n)O(\phi^{1/3}\operatorname{polylog} n), and Andersen, Chung and Lang improved this to O(ϕlog⁡m)O(\sqrt{\phi\log m}); both run in time nearly linear in the volume of the output (times a factor polynomial in 1/ϕ1/\phi). These local algorithms are subroutines of the nearly-linear-time Laplacian solver of Spielman and Teng (Nearly-Linear-Time Laplacian Solvers).

Test yourself

After sorting, how long does the sweep over all n−1n - 1 prefixes take?

  1. O(n2)O(n^2)
  2. O(n+m)O(n + m), because each edge's contribution to the cut changes only when one of its endpoints moves into SS
  3. O(nm)O(nm)
  4. O(2n)O(2^n)

Which property of the vector xx does the sweep guarantee ϕ≤2R(x)\phi \le \sqrt{2R(x)} need?

  1. xx must be an exact eigenvector
  2. Only ∑vdvxv=0\sum_v d_v x_v = 0; the bound is in terms of its own Rayleigh quotient R(x)R(x)
  3. xx must be nonnegative
  4. xx must have distinct entries

To guarantee ϕ≤2ν2\phi \le \sqrt{2\nu_2}, which vector should be swept?

  1. The eigenvector yy of NN for ν2\nu_2 itself
  2. x=D−1/2yx = D^{-1/2} y, i.e. a solution of Lx=ν2DxLx = \nu_2 D x
  3. The degree vector
  4. The eigenvector of the largest eigenvalue of AA

What do local clustering algorithms such as Andersen-Chung-Lang (PageRank-Nibble) achieve?

  1. Exact minimum conductance
  2. A low-conductance set near a seed in time nearly linear in the size of the output, not the graph
  3. Optimal bisections
  4. Exact eigenvectors in linear time