Graph-Based Clustering and Data Visualization in PythonThe graphclust toolbox

Chapter 2
Graphs from data

A graph-based method begins with a rule that decides which samples are linked. This chapter collects the rules—nearest neighbors, radii, empty regions, spanning trees—explains how they are related, and shows how edge lengths are turned into distances between all pairs of samples by shortest paths. It also discusses how the size of the neighborhood is chosen and how kNN graphs are built for large data. The graphs defined here are used by every later chapter.

2.1 Problem and idea

Given N samples in ℝD, we want a graph whose edges connect samples that are genuinely close: close enough that the straight segment between them lies within the data. Two families of rules exist. Size-based rules link each sample to a fixed number of nearest neighbors or to all samples within a fixed radius; they are cheap and work in any dimension, but each has a parameter that must fit the density of the data. Geometry-based rules link two samples when a region defined by them—a lune, a ball, a circumsphere—contains no other sample; they have no parameter but become expensive or degenerate in high dimension. The minimal spanning tree takes a third route: it keeps the shortest set of edges that connects everything, and thereby provides the backbone of the data.

Figure 2.1 illustrates how strongly the choice matters. On two groups of different density, a radius that suits the dense group leaves the sparse one fragmented, while a radius that suits the sparse group merges the groups. A fixed number of neighbors adapts to the density automatically but may still link the groups through their closest members. The minimal spanning tree connects the groups by exactly one edge, which is longer than all edges inside the groups and therefore easy to identify.

Figure 2.1

Figure 2.1. Three ways to link the same samples. A radius chosen for the dense group misses the sparse one; nearest neighbors adapt to the local density; the minimal spanning tree joins the groups by one long, conspicuous edge.

2.2 Theory

2.2.1 Graphs, paths, and trees

A graph G = (V,E) consists of a finite set of vertices V (here: samples or representatives) and a set E of unordered pairs of vertices, the edges. A weighted graph assigns a weight wij > 0 to every edge {i,j}∈E; in this book weights are either lengths (usually the Euclidean distance dij, small means close) or similarities (large means close), and every function states which one it expects. A path is a sequence of edges in which consecutive edges share a vertex; its length is the sum of its edge lengths. A graph is connected if every pair of vertices is joined by a path, and its connected components are its maximal connected subgraphs. A tree is a connected graph without cycles; a tree on N vertices has exactly N −1 edges, and removing any one of them splits it into two subtrees. A spanning tree of a connected graph is a tree that contains all its vertices; a minimal spanning tree (MST) is a spanning tree of minimal total length.

2.2.2 Size-based neighborhood graphs

The k-nearest-neighbor graph links xi to the k samples closest to it, the set Nk(i). Because j ∈Nk(i) does not imply i ∈Nk(j), the directed relation is symmetrized either by union (an edge if one sample is a neighbor of the other; the default in this book) or by intersection, which gives the mutual kNN graph. The mutual graph is sparser and avoids most edges between a dense region and isolated samples, at the risk of disconnecting sparse regions. The nearest neighbor graph (NNG) is the case k = 1. The 𝜀-graph links all pairs with dij < 𝜀; it treats all directions and densities alike and is therefore appropriate for uniformly sampled manifolds only.

2.2.3 Empty-region graphs and their nesting

Geometry-based graphs link two samples if a region determined by the pair is empty:

Since each empty region contains the next smaller one, the graphs are nested. Together with the minimal spanning tree and the nearest neighbor graph they form the chain

NNG ⊆MST ⊆RNG ⊆GG ⊆DT
(2.1)

(see Jaromczyk and Toussaint [35] for proofs, which assume distinct distances). The chain orders the graphs from the most conservative to the most permissive notion of neighborhood. The Delaunay triangulation contains every edge that any of the others could need, but in high dimension it becomes nearly complete and its computation impractical; RNG and Gabriel graph can be computed in O(N3) time in any dimension, and the MST in O(N2) time from a distance matrix.

2.2.4 Minimal spanning trees

Two classical greedy algorithms compute the MST. Prim’s algorithm [36] grows a single tree from an arbitrary start vertex and adds, in every step, the shortest edge that connects the tree to a vertex outside it. Kruskal’s algorithm [37] sorts all edges by length and adds them in this order unless they would close a cycle, so that it merges a forest of growing trees. The order in which Kruskal’s algorithm merges components is exactly the merge order of single-linkage agglomerative clustering [38]: cutting the c −1 longest edges of the MST yields the single-linkage partition into c clusters. This equivalence is the basis of chapter 4, and the order in which Prim’s algorithm visits the vertices is the basis of the VAT image of chapter 6.

2.2.5 Shared neighbors

A graph can also define similarities rather than lengths. The number of shared neighbors

mij = |Nk(i) ∩Nk(j)|
(2.2)

is large for samples inside the same dense region and small across gaps, whatever the absolute density. Normalizing it by the size of the union gives the Jaccard index mij∕(2k −mij). Shared-neighbor counts are the starting point of Jarvis–Patrick clustering, of the fuzzy neighborhood similarity, and of the community graphs of chapter 5.

2.2.6 Geodesic distances

On a connected weighted graph the graph distance δij is the length of a shortest path between i and j. When the graph links only close samples of a manifold, δij approximates the length of the shortest curve on the manifold, the geodesic distance; Bernstein et al. [39] showed that the approximation becomes arbitrarily good as the sampling density grows, provided the neighborhood is small enough not to create short circuits. All pairwise graph distances are computed either by running Dijkstra’s algorithm [40] from every vertex, which costs O(N( |E| + Nlog ⁡ N)) with a heap and suits sparse graphs, or by the Floyd–Warshall recursion [41], which costs O(N3) regardless of the number of edges.

If the graph is not connected, distances between components are infinite. Mapping methods cannot handle infinite distances, and two remedies are common: increase the neighborhood until the graph is connected, which may create short circuits elsewhere, or join the components explicitly by their shortest connecting edges, which keeps the local structure. The package uses the second remedy (algorithm 2.1), which is also step 2 of TRNMap in chapter 8.

Algorithm

In a nutshell: Neighborhood graphs and geodesic distances

  • kNN graphs adapt to the local density and work in any dimension; k controls the trade-off between fragmentation (too small) and short circuits (too large).
  • Empty-region graphs (RNG, Gabriel, Delaunay) need no parameter and are nested with the MST and the NNG; they are practical in low dimension.
  • The MST is the backbone of the data; cutting its longest edges reproduces single linkage.
  • Shared-neighbor counts turn a kNN graph into a density-independent similarity.
  • Shortest paths on a neighborhood graph approximate geodesic distances on the manifold the data lie on.

2.2.7 Choosing the neighborhood and scaling up

No universal rule for k exists, but three observations help. The graph should be connected, or the number of components should be meaningful; the smallest k that gives a connected graph is a natural lower bound. Short circuits show up as a sudden drop of the agreement between graph distances and any known intrinsic coordinate, or, without ground truth, as a sudden increase of the number of very long edges. Finally, many methods are insensitive to k over a wide range once the graph is connected (fig. 2.3). For large N the exact kNN search, which costs O(N2D) by brute force, is replaced by approximate methods: hierarchical navigable small-world graphs [16] and nearest-neighbor descent [17] build kNN graphs of millions of samples with near-exact recall, and all graph-based methods in this book can take such a graph as input.

2.3 Using it in graphclust

graphclust.graphs

knn_graph(X, k), mutual_knn_graph(X, k), epsilon_graph(X, eps), nearest_neighbor_graph(X), minimum_spanning_tree(X) or minimum_spanning_tree(graph=G), relative_neighborhood_graph(X), gabriel_graph(X), delaunay_graph(X), competitive_hebbian_graph(X, nodes): symmetric sparse matrices with Euclidean edge lengths. shared_neighbor_counts(X, k) returns the matrix [mij]. connect_components(points, G) joins components; geodesic_distances(G, points=X, connect=True) returns [δij]. neighborhood_chain(X) checks eq. (2.1); to_networkx(G) converts a graph.

The graphs are built and checked in a few lines:

X, y = make_variety() 
G = { 
    "nearest neighbor graph": graphs.nearest_neighbor_graph(X), 
    "minimal spanning tree": graphs.minimum_spanning_tree(X), 
    "relative neighborhood graph": graphs.relative_neighborhood_graph(X), 
    "Gabriel graph": graphs.gabriel_graph(X), 
    "Delaunay triangulation": graphs.delaunay_graph(X), 
    "symmetric 5-NN graph": graphs.knn_graph(X, k=5), 
} 
print(graphs.neighborhood_chain(X))
   

2.4 Examples

2.4.1 The proximity graphs of a data set with three clusters and an outlier

The Variety data (make_variety) contain three groups of different size, shape, and density and one outlier. Figure 2.2 shows the graphs of the chain eq. (2.1) and the symmetric 5-NN graph. The nearest neighbor graph already reveals the three groups but breaks them into many small trees. The minimal spanning tree connects everything with 99 edges; the edges between the groups and to the outlier are visibly longer than those inside the groups. RNG and Gabriel graph add edges inside the groups, while the Delaunay triangulation also fills the empty space between them with long edges. The 5-NN graph keeps the groups apart, except for a single bridge, but leaves the outlier attached to its nearest group.

Figure 2.2

Figure 2.2. The proximity graphs of the Variety data. From the nearest neighbor graph to the Delaunay triangulation each graph contains the previous one; the kNN graph adapts to the densities of the groups.

Open in ColabExample plot_01_proximity_graphs.py in the gallery

2.4.2 Geodesic distances on the swiss roll

Figure 2.3 compares Euclidean and graph distances from one end of the swiss roll. The Euclidean distance is small for samples on the next winding, although they are far away along the sheet; the graph distance on the 8-NN graph grows steadily along the roll. The right panel varies k: with two neighbors the graph has seventy components, with four it is connected, and the graph distance from the start sample is nearly perfectly correlated with the position along the roll up to k ≈12. Beyond that, short-circuit edges between windings appear and the correlation drops quickly.

Figure 2.3

Figure 2.3. Euclidean and geodesic distances on the swiss roll. Graph distances follow the sheet; the right panel shows the window of neighborhood sizes between fragmentation and short circuits.

Open in ColabExample plot_02_geodesic_distances.py in the gallery

2.5 Further reading

Jaromczyk and Toussaint [35] survey relative neighborhood graphs and their relatives with algorithms and proofs of the nesting. The relation of MSTs and single linkage is due to Gower and Ross [38]. Bernstein et al. [39] give the convergence guarantees behind Isomap. For large-scale kNN graphs see Malkov and Yashunin [16] and Dong, Charikar, and Li [17].