.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_clustering/plot_05_validity_scan.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_01_clustering_plot_05_validity_scan.py: Choosing the number of clusters with validity indices ====================================================== A clustering algorithm always delivers a partition for the requested :math:`c`, whether or not it is meaningful. Cluster validity indices quantify how well a partition fits the data; running the algorithm for :math:`c = 2,\dots,c_{\max}` and locating the extremum of the indices is the classical recipe for selecting the number of clusters. No single index is reliable on its own, so :mod:`fuzzyclust.validity` offers a family of them: ====== =============================== ======================== ========= Index Name Measures Optimum ====== =============================== ======================== ========= PC partition coefficient fuzziness only max CE classification entropy fuzziness only min MPC modified partition coefficient fuzziness, rescaled max SC partition index compactness/separation min S separation index compactness/separation min XB Xie–Beni compactness/separation min FS Fukuyama–Sugeno compactness − separation min DI Dunn's index crisp, O(N²) max ADI alternative Dunn index crisp, cheap bound max SIL silhouette crisp max ====== =============================== ======================== ========= .. GENERATED FROM PYTHON SOURCE LINES 29-39 .. code-block:: Python import matplotlib.pyplot as plt from fuzzyclust import FCM, GK from fuzzyclust.datasets import make_fuzzy_blobs from fuzzyclust.plotting import plot_clusters, plot_validity_scan from fuzzyclust.validity import scan_n_clusters, suggest_n_clusters X, y_true = make_fuzzy_blobs(n_clusters=5, n_samples_per_cluster=80, spread=0.55, box=12.0, random_state=2) plot_clusters(X, y_true).set_title("data generated from 5 components") .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_05_validity_scan_001.png :alt: data generated from 5 components :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_05_validity_scan_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none Text(0.5, 1.0, 'data generated from 5 components') .. GENERATED FROM PYTHON SOURCE LINES 40-44 ``scan_n_clusters`` refits the estimator for every :math:`c` and returns a ``DataFrame`` of index values; ``suggest_n_clusters`` reads off the optimum of every column, taking into account whether the index is maximized or minimized. .. GENERATED FROM PYTHON SOURCE LINES 44-49 .. code-block:: Python table = scan_n_clusters(FCM(m=2.0, random_state=0), X, n_clusters_range=range(2, 10)) print(table.round(3)) print("\nsuggested number of clusters per index:") print(suggest_n_clusters(table)) .. rst-class:: sphx-glr-script-out .. code-block:: none PC CE MPC SC ... APD PBMF KWON PCAES n_clusters ... 2 0.733 0.416 0.466 0.507 ... 28.877 22.696 101.960 2.205 3 0.746 0.470 0.618 0.083 ... 45.518 51.945 26.732 3.300 4 0.774 0.460 0.699 0.048 ... 74.468 85.947 28.153 3.199 5 0.834 0.383 0.793 0.021 ... 105.545 98.421 20.831 3.444 6 0.767 0.516 0.720 0.021 ... 95.523 90.538 262.672 9.802 7 0.709 0.623 0.661 0.017 ... 86.572 85.417 238.840 7.808 8 0.665 0.711 0.617 0.014 ... 84.908 87.551 240.588 6.326 9 0.626 0.780 0.579 0.011 ... 82.645 98.130 207.053 4.858 [8 rows x 16 columns] suggested number of clusters per index: PC 5 CE 5 MPC 5 SC 9 S 5 XB 5 FS 5 DI 5 ADI 5 SIL 5 FHV 5 PD 5 APD 5 PBMF 5 KWON 5 PCAES 6 Name: suggested_n_clusters, dtype: int64 .. GENERATED FROM PYTHON SOURCE LINES 50-55 Plotting the (min–max normalized) indices against :math:`c` shows the consensus: the separation-based indices (XB, S, DI, ADI, and SIL) agree on :math:`c=5`. PC and CE measure fuzziness only and drift with :math:`c` and :math:`m`; here they peak at :math:`c=5`, but the table below shows that for :math:`m\ge2.5` they point to :math:`c=2`. .. GENERATED FROM PYTHON SOURCE LINES 55-62 .. code-block:: Python fig, axes = plt.subplots(1, 2, figsize=(12, 4.5)) plot_validity_scan(table[["PC", "CE", "MPC"]], ax=axes[0]) axes[0].set_title("partition-based indices") plot_validity_scan(table[["SC", "S", "XB", "DI", "ADI", "SIL"]], ax=axes[1]) axes[1].set_title("geometry-based indices") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_05_validity_scan_002.png :alt: partition-based indices, geometry-based indices :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_05_validity_scan_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 63-67 Validity indices are algorithm-agnostic: the same scan works for GK (or any other estimator of the toolbox). Because GK adapts the cluster shapes, its compactness/separation indices are usually slightly better than those of FCM for the same :math:`c`. .. GENERATED FROM PYTHON SOURCE LINES 67-71 .. code-block:: Python table_gk = scan_n_clusters(GK(random_state=0), X, range(2, 10), indices=["XB", "SIL"]) comparison = table[["XB", "SIL"]].join(table_gk, lsuffix="_FCM", rsuffix="_GK") print(comparison.round(3)) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/fuzzyclust/fuzzyclust/examples/01_clustering/plot_05_validity_scan.py:68: Pandas4Warning: The 'lsuffix' and 'rsuffix' keywords in DataFrame.join are deprecated and will be removed in a future version. Use the 'suffixes' keyword instead. comparison = table[["XB", "SIL"]].join(table_gk, lsuffix="_FCM", rsuffix="_GK") XB_FCM SIL_FCM XB_GK SIL_GK n_clusters 2 0.254 0.449 0.286 0.450 3 0.066 0.588 0.074 0.610 4 0.068 0.619 0.083 0.641 5 0.049 0.715 0.049 0.715 6 0.617 0.623 0.650 0.627 7 0.553 0.537 0.626 0.549 8 0.549 0.459 0.570 0.460 9 0.463 0.375 0.757 0.441 .. GENERATED FROM PYTHON SOURCE LINES 72-76 In practice, compute several indices, prefer the value of :math:`c` on which the geometry-based indices agree, and inspect the resulting partition visually (e.g., with the projections of :mod:`fuzzyclust.viz`) before trusting it. An index extremum is a hint, not a proof. .. GENERATED FROM PYTHON SOURCE LINES 78-90 Parameter study: the verdict and the fuzziness exponent ------------------------------------------------------- Every index is evaluated on the partition that FCM delivers, and that partition depends on :math:`m`. The scan is therefore repeated for several exponents, and the suggested number of clusters is tabulated per index. XB, DI, SIL, and MPC keep pointing at :math:`c=5` for every exponent because the prototypes barely move with :math:`m`; S, FS, and ADI deviate only for the smallest or the largest exponents. The indices that only measure fuzziness (PC, CE) behave differently: for a soft partition (:math:`m\ge2.5`) they flip to :math:`c=2`, since fewer clusters simply means less fuzziness to share. The Xie--Beni curves show that the minimum deepens as :math:`m` grows but stays at :math:`c=5`. .. GENERATED FROM PYTHON SOURCE LINES 90-112 .. code-block:: Python # [snippet:m_scan] import pandas as pd m_values = (1.3, 1.6, 2.0, 2.5, 3.0) tables = {m: scan_n_clusters(FCM(m=m, random_state=0), X, n_clusters_range=range(2, 10)) for m in m_values} verdict = pd.DataFrame({f"m = {m}": suggest_n_clusters(t) for m, t in tables.items()}) # [/snippet:m_scan] print("suggested number of clusters per index and exponent:") print(verdict.loc[["PC", "CE", "MPC", "SC", "S", "XB", "FS", "DI", "ADI", "SIL"]]) fig, ax = plt.subplots(figsize=(6.5, 4)) for m, t in tables.items(): ax.plot(t.index, t["XB"], "o-", label=f"m = {m}") ax.axvline(5, color="0.5", ls=":") ax.set_xlabel("number of clusters $c$") ax.set_ylabel("Xie–Beni index (lower is better)") ax.set_title("the Xie–Beni minimum stays at $c=5$ for every exponent") ax.legend(frameon=False, fontsize=8) ax.grid(True, color="0.9") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_05_validity_scan_003.png :alt: the Xie–Beni minimum stays at $c=5$ for every exponent :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_05_validity_scan_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none suggested number of clusters per index and exponent: m = 1.3 m = 1.6 m = 2.0 m = 2.5 m = 3.0 PC 5 5 5 2 2 CE 5 5 5 2 2 MPC 5 5 5 5 5 SC 9 9 9 9 9 S 5 5 5 5 3 XB 5 5 5 5 5 FS 9 5 5 5 4 DI 5 5 5 5 5 ADI 3 3 5 5 5 SIL 5 5 5 5 5 .. GENERATED FROM PYTHON SOURCE LINES 113-126 Take-away --------- A validity scan turns the choice of :math:`c` into a comparison of partitions, and the indices that combine compactness with separation (XB, S, DI, SIL, and the volume-based FHV/PD) are the ones to trust: on these five well-separated groups they agree with each other and with the GK variant of the scan, and XB, DI, and SIL also across the range of exponents tested (S drops to three clusters at :math:`m=3`). The fuzziness-only indices PC and CE change their verdict with :math:`m` (:math:`c=5` for :math:`m\le2`, :math:`c=2` for larger exponents); SC favors many small clusters on this data set. No index replaces a look at the partition (the projections of :mod:`fuzzyclust.viz` are the next step), but a consensus of the geometry-based indices is a strong hint. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 1.047 seconds) .. _sphx_glr_download_auto_examples_01_clustering_plot_05_validity_scan.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/fuzzyclust/main?urlpath=lab/tree/notebooks/auto_examples/01_clustering/plot_05_validity_scan.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_05_validity_scan.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_05_validity_scan.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_05_validity_scan.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_