Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Spectral clustering

ProblemCluster points by the connectivity of a similarity graph, using eigenvectors of its Laplacian
Devised byMiroslav Fiedler (1973), algebraic connectivity; William Donath and Alan Hoffman (1973), graph partitioning by eigenvectors; Jianbo Shi and Jitendra Malik (2000), normalised cuts; Andrew Ng, Michael Jordan and Yair Weiss (2002), the normalised embedding used here
AccuracyExact for graphs with disconnected components; a relaxation of the normalised-cut problem otherwise
Cost to build the graph and for the dense eigendecomposition
Read firstk-means and k-medoids, Symmetric and general eigensolvers
APISpectralClustering (new(k, affinity, seed), eigenvalues), Affinity (Rbf { gamma }, NearestNeighbors { k })

Overview

Spectral clustering turns the data into a graph, with points as vertices and edges between similar points, and looks for groups of vertices that are well connected inside and weakly connected to each other. The eigenvectors of the graph’s Laplacian matrix with the smallest eigenvalues give each point new coordinates in which such groups are compact and well separated, and k-means finishes the job. Because it clusters by connectivity rather than by distance to a centre, it separates rings, moons and other shapes that defeat centroid methods.

Where it is used

Spectral clustering finds groups defined by connectivity, not by distance to a centre.

  • Image segmentation. Partitioning an image into regions by the similarity of neighbouring pixels (normalised cuts).
  • Community detection in networks. Social and communication networks, protein-interaction networks.
  • Non-convex clusters. Two interlocking rings, which k-means cannot separate.
  • Graph Laplacian. The algorithm connects the clustering problem to the eigenvectors of the graph Laplacian of the graph chapter.

History

Miroslav Fiedler (1973) showed that the second-smallest eigenvalue of a graph’s Laplacian measures how well connected the graph is, and that its eigenvector, the Fiedler vector, splits the graph. William Donath and Alan Hoffman (1973) used eigenvectors to partition circuits. In image segmentation, Jianbo Shi and Jitendra Malik (2000) relaxed the NP-hard normalised cut to an eigenproblem. Andrew Ng, Michael Jordan and Yair Weiss (2002) gave the simple algorithm with row normalisation used here, and Ulrike von Luxburg’s tutorial (2007) set out the theory.

The idea

The similarity graph

The method first builds a symmetric weight matrix with large for similar points. The library offers two choices:

  • RBF: , a dense graph whose reach is set by .
  • -nearest neighbours: if either point is among the other’s nearest, else 0. Only nearby points are connected, so the graph follows the shape of the data.

The Laplacian and its null space

Think of the points as the vertices of a graph, with the weight of the edge between points and . A clustering assigns a label to each vertex, and a good one seldom gives different labels to strongly connected vertices. That requirement can be expressed with a matrix. Let the degree of vertex be the total weight of its edges, , collected in a diagonal matrix . The graph Laplacian is . For any vector that assigns a number to each vertex, expanding and using the symmetry of gives

This quantity adds up, over all edges, the squared difference of across the edge, weighted by the edge’s strength. It is small when is nearly constant across strongly weighted edges, which is exactly what we want of a labelling.

It is zero only if wherever , that is, if is constant on each connected component of the graph. Since always, such vectors are eigenvectors of with eigenvalue 0, the smallest possible. So a graph with components has the eigenvalue 0 with multiplicity , and the corresponding eigenvectors are combinations of the indicator vectors of the components (1 on one component, 0 elsewhere). The clusters can be read off from the eigenvectors of smallest eigenvalue. That is the whole idea of spectral clustering; the rest is about making it robust when the clusters are not perfectly separated. Clusters that are almost disconnected give eigenvalues near zero and a jump, the eigengap, after them:

Figure 12.7. Laplacian eigenvalues.

With three blobs, three eigenvalues are zero and the fourth jumps to 0.09; with five blobs the jump comes after the fifth. The eigengap is a natural guide to the number of clusters.

Normalised cuts and the embedding

Splitting a graph by the minimum total weight of cut edges tends to cut off single points. The normalised cut divides the cut weight by the total degree of each side, which favours balanced parts. Finding the best normalised cut is NP-hard, but allowing the cluster indicators to take real values turns it into an eigenproblem for the normalised Laplacian

Ng, Jordan and Weiss take the eigenvectors of with the smallest eigenvalues as the columns of an matrix. They scale each row to unit length and cluster the rows with k-means. For disconnected clusters the rows of each cluster coincide on one point of the unit sphere, orthogonal to the other clusters’ points. The clusters are then trivially separable, and k-means with sensible seeding finds them (Lloyd’s algorithm can still stop in a poor local optimum if two initial centres fall in the same cluster). Weak connections only perturb this picture.

k-means cuts the rings in half. The 8-nearest-neighbour graph has no edges between the rings, so spectral clustering separates them perfectly.

The graph decides

Everything depends on building a graph whose components are the clusters:

Table 12.11. Spectral clustering with different similarity graphs.

similarity graphmoons (ARI)rings (ARI)
3-NN graph0.1860.105
5-NN graph1.0001.000
10-NN graph1.0001.000
20-NN graph1.0001.000
40-NN graph0.536-0.003
RBF, γ = 10.296-0.003
RBF, γ = 100.809-0.003
RBF, γ = 301.0001.000
RBF, γ = 1001.0001.000

With 3 neighbours the graph falls into many small pieces, and the eigenvectors describe those pieces instead of the clusters; with 40 it connects the two moons. An RBF graph needs large enough (a reach below the gap between clusters) to cut the weak links. The nearest-neighbour graph adapts to the local density and works over a wide range of .

Algorithm

Input: the data, the number of clusters and the choice of graph.

  1. Build the graph. Compute the weight matrix : either the RBF similarities, or the -nearest-neighbour graph made symmetric by joining two points if either is among the other’s nearest neighbours. Set its diagonal to zero. Compute the degrees .
  2. Form the normalised Laplacian .
  3. Eigenvectors. Compute the eigendecomposition of with the symmetric eigensolver, and take the eigenvectors of the smallest eigenvalues as the columns of an matrix.
  4. Normalise the rows. Scale each row of that matrix to unit length. Row is now the image of point in a -dimensional space in which the clusters are compact.
  5. Cluster the rows with k-means, using 10 restarts.

The cost is dominated by the dense eigendecomposition, , which limits the method to a few thousand points.

Implementation

        let deg: Vec<f64> = (0..n).map(|i| w.row(i).sum()).collect();
        let inv_sqrt: Vec<f64> = deg.iter().map(|&d| if d > 1e-12 { 1.0 / d.sqrt() } else { 0.0 }).collect();
        let lap = R2D::from_shape_fn((n, n), |(i, j)| f64::from(i == j) - inv_sqrt[i] * w[[i, j]] * inv_sqrt[j]);
        let (vals, vecs) = lap.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("The Laplacian eigendecomposition failed."))?;
        self.eigenvalues = vals.iter().take(self.k).copied().collect();
        // Embed with the k smallest eigenvectors, normalising each row to unit length.
        let mut embedding = R2D::from_shape_fn((n, self.k), |(i, j)| vecs[[i, j]]);
        for mut row in embedding.rows_mut() {
            let norm = row.iter().map(|v| v * v).sum::<f64>().sqrt();
            if norm > 1e-12 {
                row.mapv_inplace(|v| v / norm);
            }
        }
        KMeans::new(self.k, self.seed).with_restarts(10).fit_predict(embedding.view())
  • The dense symmetric eigensolver (eigh) computes all eigenpairs, so the method suits up to a few thousand points. Large problems use sparse graphs and Lanczos iterations for the few eigenvectors needed.
  • An isolated vertex (degree zero) gets a zero row in the embedding instead of a division by zero.

In practice

//! Spectral clustering of concentric rings, and the eigengap as a guide to the number of clusters.

use lib_jsl_machine_learning::common::Clusterer;
use lib_jsl_machine_learning::datasets::{make_blobs, make_circles};
use lib_jsl_machine_learning::metrics::adjusted_rand_index;
use lib_jsl_machine_learning::unsupervised::clustering::{Affinity, KMeans, SpectralClustering};

fn main() {
    let (x, truth) = make_circles(150, 0.04, 0.45, 1);
    let truth: Vec<Option<usize>> = truth.into_iter().map(Some).collect();
    let km = KMeans::new(2, 1).fit_predict(x.view()).unwrap();
    let sc = SpectralClustering::new(2, Affinity::NearestNeighbors { k: 8 }, 1).fit_predict(x.view()).unwrap();
    println!("rings: k-means ARI {:.3}, spectral ARI {:.3}", adjusted_rand_index(&km, &truth).unwrap(), adjusted_rand_index(&sc, &truth).unwrap());

    let (b, _) = make_blobs(40, &[vec![0.0, 0.0], vec![8.0, 0.0], vec![4.0, 7.0]], 0.8, 3);
    let mut probe = SpectralClustering::new(6, Affinity::NearestNeighbors { k: 8 }, 1);
    probe.fit_predict(b.view()).unwrap();
    println!("smallest Laplacian eigenvalues for three blobs: {:.4?}", probe.eigenvalues());
}
rings: k-means ARI -0.003, spectral ARI 1.000
smallest Laplacian eigenvalues for three blobs: [-0.0000, 0.0000, 0.0000, 0.0882, 0.1044, 0.1296]

Strengths

  • Finds clusters of any shape that are connected in the graph; the eigengap suggests .
  • Works from any similarity matrix, including graphs with no coordinates at all.

Weaknesses

  • The result depends on the graph construction ( or ), which needs tuning.
  • The dense eigendecomposition costs time and memory; new points cannot be assigned without refitting.

Exercises

  1. Prove the identity , and deduce that is positive semidefinite.
  2. Show that the multiplicity of the eigenvalue 0 of equals the number of connected components.
  3. Compute the Laplacian eigenvalues of a path graph and of a cycle graph with vertices.
  4. Show that the eigenvalues of lie in .
  5. Relate the second eigenvector of (the Fiedler vector) to the ratio-cut problem for .
Hints and answers
  1. since .
  2. implies , so whenever : is constant on each connected component, giving a null space of dimension equal to the number of components.
  3. The path graph has eigenvalues for and the cycle graph for .
  4. and the eigenvalues of lie in because it is similar to the random-walk matrix , whose rows sum to 1 with non-negative entries.
  5. Ratio cut minimises . Relaxing the discrete indicator vector to a real vector orthogonal to turns the problem into minimising , whose solution is the Fiedler vector.

Further reading

  • A. Y. Ng, M. I. Jordan and Y. Weiss, “On spectral clustering: analysis and an algorithm”, Advances in Neural Information Processing Systems 14 (2002).
  • J. Shi and J. Malik, “Normalized cuts and image segmentation”, IEEE Transactions on Pattern Analysis and Machine Intelligence 22 (2000) 888–905.
  • U. von Luxburg, “A tutorial on spectral clustering”, Statistics and Computing 17 (2007) 395–416.
  • M. Fiedler, “Algebraic connectivity of graphs”, Czechoslovak Mathematical Journal 23 (1973) 298–305.