Graph-Based Clustering and Data Visualization in PythonThe graphclust toolbox

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 k 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 [0,1] and extends it beyond the direct neighbors; the resulting dissimilarity can be fed to any distance-based tool.

Figure 5.1

Figure 5.1. Shared neighbors are independent of density. The overlap of the k-nearest-neighbor sets is large inside each group, dense or sparse, and small across the gap.

5.2 Theory

5.2.1 Jarvis–Patrick clustering

Let Ai be the set of the k nearest neighbors of xi and mij = |Ai ∩Aj| the number of shared neighbors. Jarvis–Patrick clustering links xi and xj if

xi ∈Aj,xj ∈Ai,mij ≥l,
(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 k and l are both integers with a strong influence: a small change of l 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

sij(1) = |Ai ∩Aj| |Ai ∪Aj| ,
(5.2)

a similarity in [0,1] that equals one for identical neighborhoods; thresholding it at different levels replaces the integer l by a continuous parameter. Second, the neighborhood is widened step by step. The r-order neighborhood Ai(r) contains the members of Ai(r−1) and all their k nearest neighbors; with Ai(1) = Ai ∪{i} it grows like a breadth-first search on the kNN graph. The similarities of the orders are combined by a first-order filter,

sij(r) = (1 −α)s ij(r−1) + α |Ai(r) ∩Aj(r)| |Ai(r) ∪Aj(r)| ,sij(0) = 0,
(5.3)

for r = 1,…,rmax ⁡ (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 S = [sij] is symmetric, and D = 1 −S is a dissimilarity. Because sij(rmax ⁡ ) ≤1 −(1 −α)rmax ⁡ off the diagonal, the dissimilarities of a run lie in a narrow band (for α = 0.2, rmax ⁡ = 3 above 0.512); only their order matters for hierarchical clustering.

Algorithm

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 rmax ⁡ = 1 and α = 1, 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 r-order neighborhoods with a first-order filter.
  • Parameters: k (small values separate clusters better), rmax ⁡ (higher values give more compact clusters), α (weight of the wider neighborhoods).
  • 1 −S 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 mij 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 MinPts 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 ρi, for example ∑ ⁡ j exp ⁡ (−dij2∕dc2) with a cutoff dc, and the distance δi = min ⁡ j:ρj>ρidij to the nearest sample of higher density. Cluster centers are local density maxima and therefore have both a large ρi and an unusually large δi; 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 A = [aij] and degrees gi = ∑ ⁡ jaij, the normalized cut objective of Shi and Malik [61] leads to the leading eigenvectors of G−1∕2AG−1∕2, G = diag ⁡ (gi). Ng, Jordan, and Weiss [62] normalize the rows of the c leading eigenvectors and cluster them with k-means: if the graph had c disconnected components, the rows would collapse to c orthogonal points. Zelnik-Manor and Perona [63] choose a local scale σi for every sample (the distance to its k-th neighbor) and use aij = exp ⁡ (−dij2∕σiσj) on the kNN graph, which handles clusters of different density. The number of clusters can be read from the spectrum: c weakly connected groups produce c eigenvalues of the normalized Laplacian 1 −λl 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

Q = 1 2M∑ i,j (aij −γgigj 2M )[ℓi = ℓj],2M = ∑ ijaij,
(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 Q 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 k = 12, l = 8 recovers the three clusters and the outlier, while k = 12, l = 6 merges two clusters (74% correct).

Figure 5.2

Figure 5.2. Jarvis–Patrick clustering for four parameter settings. The number of groups and the treatment of the outlier change abruptly with the integer parameters.

Open in ColabExample plot_01_jarvis_patrick.py in the gallery

5.4.2 Fuzzy neighborhood similarity of the Variety data

With k = 6, rmax ⁡ = 3, and α = 0.2, 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 d = 0.75 (fig. 5.3). Cutting it there yields the three clusters and the outlier without a single error. The result is stable: for k between 6 and 15 and rmax ⁡ between 2 and 4 the four-group cut of the dendrogram is correct in all but one setting; only very small neighborhoods (k = 3) with high orders and very large ones with rmax ⁡ = 4 merge groups.

Figure 5.3

Figure 5.3. Fuzzy neighborhood distances of the Variety data, shown by MDS, by a VAT image, and by a single linkage dendrogram. The three clusters and the outlier are separated by all three views.

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 k ∈{8,10} and l ∈{2,…,5} does not exceed 40%, because it breaks the cultivars into many small groups.

Figure 5.4

Figure 5.4. Euclidean and fuzzy neighborhood distances of the Wine data. The fuzzy neighborhood distances separate the three cultivars much better.

Open in ColabExample plot_03_wine.py in the gallery

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 (k = 15, 𝜀 = 5, MinPts = 8) 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.

Figure 5.5

Figure 5.5. Shared-neighbor density clustering and density peaks on three groups of very different spread. The decision graph shows the three density peaks.

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 γ = 1 it divides the moons into eight communities, illustrating that modularity has its own scale.

Figure 5.6

Figure 5.6. Spectral clustering and Louvain communities. The eigengap of the normalized affinity matrix indicates three clusters; modularity with a coarse resolution finds the same groups.

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.