Chapter 1
Graphs as a language for data
This chapter explains why a graph over the samples is a good intermediate representation for clustering and visualization, introduces the pipeline that all later chapters instantiate (representatives, graph, distances, clustering or map), fixes the notation, and gives a first example in Python. It ends with a reading guide.
1.1 Why graphs
Most clustering and projection methods start from distances between samples. The Euclidean distance is a reasonable measure of dissimilarity only for samples that are close to each other: within a small neighborhood the data look flat and the straight line between two samples stays inside the data. For samples that are far apart, the straight line may cross regions without any data, cut through the fold of a curved surface, or bridge two groups that a human observer would keep apart. Graph-based methods take this observation seriously. They keep only the local relations—who is next to whom—and derive everything else from them. A long distance becomes the length of a chain of short steps; a cluster becomes a set of samples connected by such chains and separated from the rest by gaps; a map becomes a layout in which linked samples stay close.
This shift has three practical consequences that recur throughout the book. First, clusters may have any shape. A chain of samples bent into an arc is one cluster for a graph method, whereas a prototype method such as k-means cuts it into pieces of roughly equal size. Second, the distances along a graph follow the data: on a rolled-up sheet such as the swiss roll, the graph distance between two samples measures how far one has to walk on the sheet, which is what a map should reproduce if it is to unroll the sheet. Third, a graph is a compact object. With neighbors per sample it has at most edges instead of the pairs of a distance matrix, and if the samples are first replaced by representatives, the graph of the representatives summarizes the data with a few hundred nodes.
The price of these advantages is a new decision that distance-based methods do not have to make: what counts as a neighbor. Too strict a definition breaks a cluster into pieces; too generous a definition creates short circuits that link samples on different branches of the data. Much of this book is about making that decision well, or making the result insensitive to it.
1.2 The pipeline
All methods in this book can be described as instances of a pipeline with four stages (fig. 1.1):
- 1.
- Reduction (optional). The samples are replaced by representatives with vector quantization (k-means, neural gas, growing networks; chapter 3). This reduces the cost of the later stages and suppresses noise.
- 2.
- Graph construction. The samples or representatives are linked by a neighborhood rule: nearest neighbors, an -radius, an empty-region criterion such as the Gabriel graph, the minimal spanning tree, or edges learned by competitive Hebbian learning (chapters 2 and 3).
- 3.
- Graph distances or similarities. Edge lengths are propagated to all pairs as shortest-path (geodesic) distances, or edges are reweighted by the number of shared neighbors, by densities, or by kernels (chapters 2 and 5).
- 4.
- Use. The graph or the derived dissimilarities are partitioned into clusters (chapters 4 and 5) or embedded in two or three dimensions for visualization (chapters 7 to 9); maps and partitions are then assessed (chapter 6).
The stages are largely independent, and much of the progress of the last decade consists of new combinations. Isomap [6] uses a kNN graph, geodesic distances, and classical scaling; TRNMap [4] replaces the kNN graph by a topology representing network; HDBSCAN* [7] replaces Euclidean edge lengths by density-corrected ones before taking the minimal spanning tree; UMAP [8] turns a kNN graph into fuzzy memberships and lays it out by stochastic gradient descent. The package follows the same modular structure, so that the stages can be exchanged freely.
1.3 What has changed since 2013
The methods of the authors’ 2013 monograph [1] belong to a period in which graphs were mainly a tool for manifold learning and for clustering of moderate data sets. Three developments of the following years shape the extensions of this book.
Density enters the graph. The minimal spanning tree of Zahn [9] has a well-known weakness: one dense chain of samples suffices to merge two groups. HDBSCAN* [7, 10] corrects each edge length by the local density of its end points before taking the tree and selects the clusters that persist over the widest range of density levels. Its validity counterpart DBCV [11] scores partitions with the same density-corrected trees. Density peaks clustering [12] links every sample to its nearest denser neighbor, which again yields a tree. These methods are treated together with the hybrid MST–Gath–Geva algorithm in chapter 4.
Graphs become large. Community detection algorithms developed for networks—the Louvain method [13] and its successor Leiden [14]—scale to millions of nodes and were adopted for clustering kNN graphs of data, most visibly in single-cell biology [15]. Approximate nearest neighbor search with navigable small-world graphs [16] and nearest-neighbor descent [17] made kNN graphs of millions of samples routine. Chapter 5 shows how these methods relate to the shared-neighbor similarities of Jarvis and Patrick [18] and of the fuzzy neighborhood similarity [3].
Neighbor embeddings take over visualization. t-SNE [19] and UMAP [8] produce maps with crisp clusters from a weighted kNN graph. Their success raised the question of how to judge a map; the co-ranking matrix [20] and the area under the curve [21] became standard summaries, and critical studies showed that these maps distort global structure in ways that are easy to over-interpret [22, 23]. Chapters 6 and 9 treat the measures and the methods; chapter 10 compares them with the topology-based maps of the monograph.
1.4 Notation
The same symbols are used in all chapters, in the docstrings of the package, and in its documentation (table 1.1). Samples are rows of the data matrix, as in scikit-learn. Index runs over samples when clusters are discussed; for pairwise quantities the indices denote samples or nodes, as stated in each section.
| Symbol | Meaning | In the code |
| , | number of samples, number of features | X.shape |
| , | data matrix , -th sample | X, X[k] |
| , | number of representatives (nodes), codebook vector of node | n_nodes, nodes_[i] |
| graph with vertices and edges | sparse adjacency_ | |
| Euclidean distance (or between nodes) | ||
| graph (geodesic) distance, length of the shortest path | dist_matrix_ | |
| set of the nearest neighbors of sample | knn_indices | |
| , | number of clusters, -th cluster | n_clusters_, labels_ |
| , | membership of sample in cluster , fuzzy covariance matrix | membership_, covariances_ |
| , | dimension of the map, map position of sample or node | embedding_ |
| , | dissimilarity in the input space, distance in the map | |
| , | rank of among the neighbors of in the input space, in the map | |
| , | iteration counter, number of iterations of an online algorithm | max_iter |
| , | initial and final value of a parameter with schedule | tuples (gi, gf) |
1.5 A first example
The package follows the conventions of scikit-learn [24]: estimators are configured in the constructor, fitted with fit, and expose their results as attributes with a trailing underscore. Graphs are SciPy sparse matrices [25], so that the routines of scipy.sparse.csgraph and NetworkX [26] apply directly. The following lines build a topology representing network of a two-dimensional manifold, map it to the plane with TRNMap, and cluster a toy data set with the hybrid MST–Gath–Geva algorithm and with HDBSCAN*:
from graphclust import TRNMap, HybridMSTGG, HDBSCANStar from graphclust.datasets import make_s_curve, make_chainlink X, t = make_s_curve(2000, random_state=0) tm = TRNMap(n_nodes=150, random_state=0).fit(X) print(tm.nodes_.shape, tm.adjacency_.nnz // 2, tm.embedding_.shape) Xc, yc = make_chainlink() print(HybridMSTGG(max_clusters=4, lambda_=2.5).fit(Xc).labels_) print(HDBSCANStar(min_cluster_size=8).fit(Xc).labels_)
The estimators can be combined with the rest of the scientific Python stack: every mapping returns a NumPy array, every clusterer returns labels, and the quality measures of chapter 6 accept data matrices as well as precomputed distance matrices.
1.6 How the book is organized
Chapter 2 introduces the graphs that can be built from data and the distances they induce. Chapter 3 treats vector quantization and topology learning, which produce a graph of representatives. Chapters 4 and 5 are devoted to clustering: first with spanning trees and density hierarchies, then with shared neighbors, densities, spectra, and communities. Chapter 6 explains how to see whether data contain clusters at all and how to measure the quality of a map. Chapters 7 to 9 present the mapping methods in three families: distance- and neighborhood-preserving maps, topology-based maps that use graph distances, and neighbor-graph embeddings. Chapter 10 compares the methods systematically and summarizes practical advice. The appendices list the programming interface, relate the package to the MATLAB toolbox, and index the example scripts.
Each chapter follows the same pattern: a roadmap, the idea in plain words with a concept figure, the theory with one algorithm box and one summary box per method, the use of the method in graphclust, examples on data with known structure, and pointers to further reading.
1.7 Further reading
Jain and Dubes [27] remains a thorough introduction to clustering, including its graph-theoretic side; Jain’s later survey [28] puts the field in perspective. The monograph of Lee and Verleysen [29] covers nonlinear dimensionality reduction with an emphasis on distance and topology preservation, which is the viewpoint of chapters 7 and 8. Von Luxburg’s tutorial [30] is the standard introduction to spectral methods, and Fortunato’s review [31] to community detection.