.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_clustering/plot_04_gg_densities.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_04_gg_densities.py: Gath–Geva: clusters of different size and density ================================================== GK fixes the volume of every cluster, so it handles a small dense cluster next to a large diffuse one poorly: the volume constraint forces the dense cluster to "steal" points from its big neighbor. The Gath–Geva (GG) algorithm uses the fuzzy maximum-likelihood distance .. math:: D^2_{ik} = \frac{\sqrt{\det\mathbf{F}_{wi}}}{\alpha_i} \exp\!\left(\tfrac12(\mathbf{x}_k-\mathbf{v}_i)^T\mathbf{F}_{wi}^{-1}(\mathbf{x}_k-\mathbf{v}_i)\right), the reciprocal of a Gaussian density weighted by the prior :math:`\alpha_i`. Both the volume **and** the density of each cluster adapt, so GG recovers clusters of strongly different size. The price is sensitivity to initialization: with the exponential distance the iteration quickly converges to a nearby local optimum, so GG is almost always initialized with the partition of FCM or GK. .. GENERATED FROM PYTHON SOURCE LINES 23-44 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import adjusted_rand_score from fuzzyclust import FCM, GG, GK from fuzzyclust.datasets import make_different_densities from fuzzyclust.plotting import plot_covariance_ellipses, plot_membership_contours X, y_true = make_different_densities(sizes=(300, 60, 60), spreads=(1.5, 0.3, 0.6), random_state=0) fcm = FCM(n_clusters=3, random_state=0).fit(X) gk = GK(n_clusters=3, random_state=0).fit(X) gg = GG(n_clusters=3, init=fcm.membership_).fit(X) # initialized from FCM fig, axes = plt.subplots(1, 3, figsize=(15, 4.5), sharex=True, sharey=True) for ax, model, name in zip(axes, (fcm, gk, gg), ("FCM", "GK", "GG (init: FCM)"), strict=False): plot_membership_contours(model, X, ax=ax, labels=False) plot_covariance_ellipses(model.cluster_centers_, model.covariances_, ax=ax) ax.set_title(f"{name}: ARI = {adjusted_rand_score(y_true, model.labels_):.2f}") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_04_gg_densities_001.png :alt: FCM: ARI = 0.70, GK: ARI = 0.44, GG (init: FCM): ARI = 0.98 :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_04_gg_densities_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 45-49 FCM and GK let the two small clusters take over the margin of the big one; GG assigns it a large covariance and a large prior probability and leaves the small dense clusters intact. The priors :math:`\alpha_i=\frac1N\sum_k\mu_{ik}` estimate the relative sizes: .. GENERATED FROM PYTHON SOURCE LINES 49-52 .. code-block:: Python print("GG prior probabilities:", gg.priors_.round(3)) print("true proportions :", (np.bincount(y_true) / len(y_true)).round(3)) .. rst-class:: sphx-glr-script-out .. code-block:: none GG prior probabilities: [0.142 0.147 0.711] true proportions : [0.714 0.143 0.143] .. GENERATED FROM PYTHON SOURCE LINES 53-60 Why initialization matters -------------------------- Started from random prototypes, GG can end in a poor local optimum, and the outcome varies from seed to seed. We run GG from ten random initializations and from the FCM partition and compare the agreement with the generating labels: the FCM-initialized run is as good as the best random run, without depending on the seed. .. GENERATED FROM PYTHON SOURCE LINES 60-67 .. code-block:: Python aris = [] for seed in range(10): model = GG(n_clusters=3, init="random", random_state=seed).fit(X) aris.append(adjusted_rand_score(y_true, model.labels_)) print(f"random init : ARI mean = {np.mean(aris):.2f}, min = {np.min(aris):.2f}, max = {np.max(aris):.2f}") print(f"FCM init : ARI = {adjusted_rand_score(y_true, gg.labels_):.2f}") .. rst-class:: sphx-glr-script-out .. code-block:: none random init : ARI mean = 0.97, min = 0.83, max = 0.98 FCM init : ARI = 0.98 .. GENERATED FROM PYTHON SOURCE LINES 68-75 The GG distance interpreted as a density ---------------------------------------- Because :math:`1/D^2_{ik}` is proportional to a Gaussian density, the membership :math:`\mu_{ik}` is the posterior probability that :math:`\mathbf{x}_k` was generated by component :math:`i`. The figure shows the sum of :math:`\alpha_i\,\mathcal{N}(\mathbf{x};\mathbf{v}_i,\mathbf{F}_i)` over the three fitted components. .. GENERATED FROM PYTHON SOURCE LINES 75-91 .. code-block:: Python gx, gy = np.meshgrid(np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 200), np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 200)) G = np.c_[gx.ravel(), gy.ravel()] dens = np.zeros(G.shape[0]) for i in range(3): diff = G - gg.cluster_centers_[i] inv = np.linalg.inv(gg.covariances_[i]) maha = np.einsum("kj,jl,kl->k", diff, inv, diff) dens += gg.priors_[i] * np.exp(-0.5 * maha) / (2 * np.pi * np.sqrt(np.linalg.det(gg.covariances_[i]))) fig, ax = plt.subplots(figsize=(5.5, 4.5)) cf = ax.contourf(gx, gy, dens.reshape(gx.shape), levels=20, cmap="Blues") ax.scatter(X[:, 0], X[:, 1], s=5, color="k", alpha=0.5) plt.colorbar(cf, ax=ax, label="mixture density") ax.set_title("GG clusters as a Gaussian mixture") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_04_gg_densities_002.png :alt: GG clusters as a Gaussian mixture :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_04_gg_densities_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 92-100 Parameter study: the fuzziness exponent for FCM, GK, and GG ----------------------------------------------------------- The exponent :math:`m` is the one parameter the three algorithms share. Scanning it on the same data separates two effects: the softness of the partition (set by :math:`m`) and the shape of the distance (set by the algorithm). The agreement with the generating labels and the GG priors are recorded for every :math:`m`; GG is initialized from the FCM partition obtained with the same exponent. .. GENERATED FROM PYTHON SOURCE LINES 100-131 .. code-block:: Python from fuzzyclust.plotting import PALETTE # [snippet:m_scan] m_values = (1.2, 1.5, 2.0, 2.5, 3.0) ari = {"FCM": [], "GK": [], "GG (init: FCM)": []} priors = [] for m in m_values: fcm_m = FCM(n_clusters=3, m=m, random_state=0).fit(X) gk_m = GK(n_clusters=3, m=m, random_state=0).fit(X) gg_m = GG(n_clusters=3, m=m, init=fcm_m.membership_).fit(X) for name, model in zip(ari, (fcm_m, gk_m, gg_m), strict=True): ari[name].append(adjusted_rand_score(y_true, model.labels_)) priors.append(np.sort(gg_m.priors_)[::-1]) # [/snippet:m_scan] fig, ax = plt.subplots(figsize=(6.5, 4)) for j, (name, values) in enumerate(ari.items()): ax.plot(m_values, values, "o-", color=PALETTE[j], label=name) ax.set_xlabel("fuzziness exponent $m$") ax.set_ylabel("ARI with the generating labels") ax.set_ylim(0, 1.05) ax.set_title("the distance, not the exponent, decides whether the dense clusters survive") ax.legend(frameon=False) ax.grid(True, color="0.9") plt.tight_layout() print(" m FCM GK GG GG priors (sorted)") for j, (m, pr) in enumerate(zip(m_values, priors, strict=True)): print(f"{m:4.1f} {ari['FCM'][j]:5.2f} {ari['GK'][j]:5.2f} {ari['GG (init: FCM)'][j]:5.2f} {pr.round(2)}") .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_04_gg_densities_003.png :alt: the distance, not the exponent, decides whether the dense clusters survive :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_04_gg_densities_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none m FCM GK GG GG priors (sorted) 1.2 0.71 0.29 0.98 [0.71 0.15 0.14] 1.5 0.70 0.30 0.98 [0.71 0.15 0.14] 2.0 0.70 0.44 0.98 [0.71 0.15 0.14] 2.5 0.69 0.48 0.98 [0.72 0.14 0.14] 3.0 0.69 0.53 0.98 [0.73 0.14 0.14] .. GENERATED FROM PYTHON SOURCE LINES 132-145 Take-away --------- The exponential distance of Gath--Geva makes the cluster volume and the prior probability part of the model, so a large diffuse group and small dense groups can coexist in one partition, and the memberships are the posterior probabilities of a Gaussian mixture. FCM and GK, whose distances fix the volume, cut into the large group whatever the exponent: changing :math:`m` alters how soft the partition is but not which structure it describes, so across the whole range GG stays near :math:`ARI\approx1` while FCM and GK stay far below it. The price of the flexible distance is a rugged objective; as the restart experiment above shows, GG should be started from a converged FCM or GK partition rather than from random prototypes. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.558 seconds) .. _sphx_glr_download_auto_examples_01_clustering_plot_04_gg_densities.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_04_gg_densities.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_04_gg_densities.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_04_gg_densities.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_04_gg_densities.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_