Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Spectral clustering and graph communities#
Global graph methods partition the whole neighborhood graph at once. Normalized spectral clustering embeds the samples with the leading eigenvectors of the normalized affinity matrix, where the clusters become compact, and the eigengap suggests their number. Community detection maximizes modularity: more edges inside the groups than expected by chance. The Jaccard-weighted kNN graph used here (the PhenoGraph construction) is exactly the first-order fuzzy neighborhood similarity restricted to the kNN pairs. With a fine graph and the standard resolution, modularity prefers many small communities; a coarser resolution recovers the three groups.
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons
from graphclust import GraphCommunityClustering, SpectralGraphClustering
from graphclust.plotting import plot_graph, plot_partition
from graphclust.validity import clustering_rate
rng = np.random.default_rng(0)
Xm, ym = make_moons(400, noise=0.06, random_state=0)
blob = rng.normal([2.6, 1.2], 0.15, (120, 2))
X = np.vstack([Xm, blob])
y = np.r_[ym, np.full(120, 2)]
# [snippet:spectral]
sp = SpectralGraphClustering(n_clusters="auto", affinity="self_tuning", k=10, random_state=0).fit(X)
com = GraphCommunityClustering(k=30, graph="jaccard", method="louvain", resolution=0.1, random_state=0).fit(X)
# [/snippet:spectral]
print("spectral:", sp.n_clusters_, "clusters, rate", clustering_rate(y, sp.labels_))
print("Louvain :", com.n_clusters_, "communities, modularity", round(com.modularity_, 3), "rate", clustering_rate(y, com.labels_))
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
axes[0].plot(np.arange(1, len(sp.eigenvalues_) + 1), sp.eigenvalues_, "o-", color="#0072B2")
axes[0].set_xlabel("index")
axes[0].set_ylabel("eigenvalue")
axes[0].set_title(f"spectrum: largest gap after {sp.n_clusters_}")
plot_partition(X, sp.labels_, ax=axes[1], title="self-tuning spectral clustering")
plot_graph(X, com.graph_, labels=com.labels_, ax=axes[2], node_size=8, lw=0.3, title="Louvain communities of the Jaccard kNN graph")
for ax in axes[1:]:
ax.set_xticks([])
ax.set_yticks([])
plt.tight_layout()

spectral: 3 clusters, rate 1.0
Louvain : 3 communities, modularity 0.963 rate 1.0
Resolution and graph size control the granularity of the communities.
for res in (1.0, 0.3, 0.1):
c = GraphCommunityClustering(k=30, resolution=res, random_state=0).fit(X)
print(f"resolution {res}: {c.n_clusters_} communities")
resolution 1.0: 8 communities
resolution 0.3: 5 communities
resolution 0.1: 3 communities
Total running time of the script: (0 minutes 0.611 seconds)