Chapter 5
Shared neighbors, densities, and communities
Two samples that share many neighbors probably belong to the same cluster, whatever the density of the region they are in. This chapter builds clustering methods on that idea: Jarvis–Patrick clustering with its crisp threshold, the fuzzy neighborhood similarity that softens the threshold and propagates it to neighbors of neighbors, shared-neighbor density clustering, and density peaks. It then turns to methods that partition the whole neighborhood graph at once—normalized spectral clustering and modularity-based community detection with Louvain and Leiden—and shows that the edge weights of the popular PhenoGraph construction are the first-order fuzzy neighborhood similarity.
5.1 Problem and idea
Distance thresholds fail when clusters differ in density: a radius that separates two dense groups shatters a sparse one. Counting shared neighbors removes the absolute scale. Inside a cluster, dense or sparse, the nearest neighbors of two adjacent samples overlap strongly; across a gap they hardly overlap, because each sample finds its neighbors on its own side (fig. 5.1). Jarvis and Patrick [18] turned this into a clustering rule in 1973. Its weakness is the crisp integer threshold on the number of shared neighbors, which makes the result jump as the threshold changes. The fuzzy neighborhood similarity [3] replaces the count by a share in and extends it beyond the direct neighbors; the resulting dissimilarity can be fed to any distance-based tool.
5.2 Theory
5.2.1 Jarvis–Patrick clustering
Let be the set of the nearest neighbors of and the number of shared neighbors. Jarvis–Patrick clustering links and if
|
| (5.1) |
and takes the connected components of the resulting graph as clusters. Samples left without links are outliers. The method handles different densities and shapes and needs no number of clusters, but and are both integers with a strong influence: a small change of can split a cluster or merge two, and the decision is restricted to direct neighbors.
5.2.2 Fuzzy neighborhood similarity
Vathy-Fogarassy, Kiss, and Abonyi [3] soften the rule in two ways. First, the count is replaced by the share of common neighbors in the union of the neighbor sets, the Jaccard index
|
| (5.2) |
a similarity in that equals one for identical neighborhoods; thresholding it at different levels replaces the integer by a continuous parameter. Second, the neighborhood is widened step by step. The -order neighborhood contains the members of and all their nearest neighbors; with it grows like a breadth-first search on the kNN graph. The similarities of the orders are combined by a first-order filter,
|
| (5.3) |
for (algorithm 5.1). Higher orders let samples that are not direct neighbors but belong to the same region become similar, which makes clusters more compact; the filter parameter controls how much the wider neighborhoods count. The matrix is symmetric, and is a dissimilarity. Because off the diagonal, the dissimilarities of a run lie in a narrow band (for , above ); only their order matters for hierarchical clustering.
The dissimilarity can be used by every method that accepts one: hierarchical clustering, whose dendrogram suggests the threshold that separates the clusters; MDS, which shows the cluster structure in the plane (chapter 7); and VAT (chapter 6). With and , eq. (5.3) reduces to the Jaccard index eq. (5.2). The same quantity, computed only for pairs linked in the kNN graph, became the edge weight of the PhenoGraph method [15], which clusters such graphs by modularity and is widely used in single-cell biology.
In a nutshell: Fuzzy neighborhood similarity
- Measures similarity by the share of common neighbors, independent of density; extends it to -order neighborhoods with a first-order filter.
- Parameters: (small values separate clusters better), (higher values give more compact clusters), (weight of the wider neighborhoods).
- feeds hierarchical clustering, MDS, and VAT; outliers have low similarity to everything and stand out.
5.2.3 Shared-neighbor density clustering
Ertöz, Steinbach, and Kumar [60] combine shared neighbors with the core-point idea of DBSCAN [58]. The SNN similarity of two samples is if they are in each other’s neighbor lists and zero otherwise; the SNN density of a sample is the number of samples with similarity at least . Samples with density at least are core samples; core samples linked by similarity form the clusters, non-core samples join their most similar core sample if that similarity reaches , and the rest is noise. The method finds clusters of different density in high dimension, where distances concentrate and density thresholds are hard to set.
5.2.4 Density peaks
Rodriguez and Laio [12] characterize every sample by two numbers: its local density , for example with a cutoff , and the distance to the nearest sample of higher density. Cluster centers are local density maxima and therefore have both a large and an unusually large ; they stand out in the decision graph of against . Every other sample inherits the label of its nearest denser neighbor, processed in order of decreasing density. The links to the nearest denser neighbor form a spanning forest whose roots are the density peaks, so density peaks clustering is another tree method; the choice of the centers replaces the choice of edges to cut.
5.2.5 Spectral clustering
Spectral methods partition a weighted graph by its eigenvectors. With an affinity matrix and degrees , the normalized cut objective of Shi and Malik [61] leads to the leading eigenvectors of , . Ng, Jordan, and Weiss [62] normalize the rows of the leading eigenvectors and cluster them with k-means: if the graph had disconnected components, the rows would collapse to orthogonal points. Zelnik-Manor and Perona [63] choose a local scale for every sample (the distance to its -th neighbor) and use on the kNN graph, which handles clusters of different density. The number of clusters can be read from the spectrum: weakly connected groups produce eigenvalues of the normalized Laplacian close to zero followed by a jump, the eigengap [30].
5.2.6 Communities
Network science measures the quality of a partition of a graph by its modularity
|
| (5.4) |
the fraction of edge weight inside communities minus its expectation in a random graph with the same degrees [64]; the resolution parameter shifts the preferred community size. The Louvain method [13] maximizes greedily by moving single nodes between communities and then aggregating communities into super-nodes, repeating both phases until no improvement is possible. Leiden [14] adds a refinement phase that guarantees well-connected communities, which Louvain does not. Label propagation [65] is a faster alternative without an explicit objective. Applied to a kNN graph of data, these methods give a clustering whose number of clusters follows from the graph and the resolution; the PhenoGraph construction first reweights the kNN edges by the Jaccard index eq. (5.2).
In a nutshell: Global graph partitioning
- Spectral clustering embeds the samples with the leading eigenvectors of the normalized affinity matrix; the eigengap suggests the number of clusters.
- Louvain and Leiden maximize modularity on very large graphs; the resolution controls the granularity.
- Both work on any neighborhood graph; Jaccard-weighted kNN graphs (first-order fuzzy neighborhood similarity) are a robust default.
5.3 Using it in graphclust
graphclust.cluster
JarvisPatrick(k=8, min_shared=4); fuzzy_neighborhood_similarity(X, k=6, r_max=3, alpha=0.2); FuzzyNeighborhoodClustering(n_clusters=None, k, r_max, alpha, linkage="single", distance_threshold=None) with similarity_ and linkage_matrix_; SharedNearestNeighborClustering(k=20, eps=7, min_pts=10); DensityPeaks(n_clusters, density="gaussian" or "knn") with rho_, delta_, nearest_denser_; SpectralGraphClustering(n_clusters or "auto", affinity="self_tuning", "fuzzy" or "precomputed", k); GraphCommunityClustering(k=15, graph="jaccard", method="louvain", "leiden", "label_propagation" or "greedy", resolution=1.0); jaccard_knn_graph(X, k). Leiden uses the optional packages leidenalg and igraph (pip install graphclust[leiden]).
The fuzzy neighborhood distances and the corresponding hierarchical clustering are obtained as follows:
S = fuzzy_neighborhood_similarity(X, k=6, r_max=3, alpha=0.2) D = 1.0 - S np.fill_diagonal(D, 0.0) fnc = FuzzyNeighborhoodClustering(k=6, r_max=3, alpha=0.2, linkage="single", distance_threshold=0.75).fit(X) print("clusters:", fnc.n_clusters_, " clustering rate:", clustering_rate(y, fnc.labels_))
5.4 Examples
5.4.1 Jarvis–Patrick clustering of the Variety data
Figure 5.2 shows Jarvis–Patrick clustering of the Variety data for four parameter pairs. The same data give six, six, three, and four groups; only , recovers the three clusters and the outlier, while , merges two clusters (74% correct).
Open in ColabExample plot_01_jarvis_patrick.py in the gallery
5.4.2 Fuzzy neighborhood similarity of the Variety data
With , , and , MDS of the fuzzy neighborhood distances shows three compact groups and the outlier far from all of them, the VAT image shows three dark blocks and a single isolated sample, and the single linkage dendrogram has a long gap below (fig. 5.3). Cutting it there yields the three clusters and the outlier without a single error. The result is stable: for between 6 and 15 and between 2 and 4 the four-group cut of the dendrogram is correct in all but one setting; only very small neighborhoods () with high orders and very large ones with merge groups.
Open in ColabExample plot_02_fuzzy_similarity.py in the gallery
5.4.3 The Wine data
On the standardized Wine data (178 samples, 13 features, three cultivars) MDS of the Euclidean distances shows overlapping groups, whereas MDS of the fuzzy neighborhood distances pulls the cultivars apart (fig. 5.4). Average linkage on the fuzzy neighborhood distances classifies 93.3% of the wines correctly. Jarvis–Patrick clustering with and does not exceed 40%, because it breaks the cultivars into many small groups.
5.4.4 Shared-neighbor density and density peaks
Figure 5.5 uses three groups whose spreads differ by a factor of four. SNN clustering (, , MinPts ) finds the three groups and labels five border samples as noise (98.7% correct). In the decision graph of density peaks three samples stand out with both high density and large distance to any denser sample; with them as centers, 99.5% of the samples are assigned correctly. The thin lines show the tree of nearest denser neighbors.
Open in ColabExample plot_04_snn_density_peaks.py in the gallery
5.4.5 Spectral clustering and communities
Two interleaved half-moons and a compact blob form the data of fig. 5.6. The spectrum of the self-tuning affinity matrix has three eigenvalues equal to one before the jump, so the eigengap selects three clusters, which are recovered exactly. Louvain on the Jaccard-weighted 30-NN graph with resolution 0.1 also finds the three groups; with the standard resolution it divides the moons into eight communities, illustrating that modularity has its own scale.
Open in ColabExample plot_05_spectral_communities.py in the gallery
5.5 Further reading
The original description of shared-neighbor clustering is Jarvis and Patrick [18]; the fuzzy neighborhood similarity is introduced in [3]. Ertöz, Steinbach, and Kumar [60] discuss shared-neighbor densities in high dimension. Von Luxburg [30] explains spectral clustering, Fortunato [31] community detection; Traag, Waltman, and van Eck [14] show why Louvain may produce badly connected communities and how Leiden avoids them.