.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/04_neighborhoods/plot_05_spectral_communities.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_04_neighborhoods_plot_05_spectral_communities.py: 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. .. GENERATED FROM PYTHON SOURCE LINES 15-49 .. code-block:: Python 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() .. image-sg:: /auto_examples/04_neighborhoods/images/sphx_glr_plot_05_spectral_communities_001.png :alt: spectrum: largest gap after 3, self-tuning spectral clustering, Louvain communities of the Jaccard kNN graph :srcset: /auto_examples/04_neighborhoods/images/sphx_glr_plot_05_spectral_communities_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none spectral: 3 clusters, rate 1.0 Louvain : 3 communities, modularity 0.963 rate 1.0 .. GENERATED FROM PYTHON SOURCE LINES 50-51 Resolution and graph size control the granularity of the communities. .. GENERATED FROM PYTHON SOURCE LINES 51-54 .. code-block:: Python 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") .. rst-class:: sphx-glr-script-out .. code-block:: none resolution 1.0: 8 communities resolution 0.3: 5 communities resolution 0.1: 3 communities .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.611 seconds) .. _sphx_glr_download_auto_examples_04_neighborhoods_plot_05_spectral_communities.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/graphclust/main?urlpath=lab/tree/notebooks/auto_examples/04_neighborhoods/plot_05_spectral_communities.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_05_spectral_communities.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_05_spectral_communities.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_05_spectral_communities.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_