.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/06_extensions/plot_04_kernel_fcm.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_06_extensions_plot_04_kernel_fcm.py: Kernel fuzzy c-means: rings and moons through the kernel trick ============================================================== FCM finds clusters that are convex in the input space because its distance is Euclidean. Kernel FCM maps the data with an implicit nonlinear map :math:`\Phi` into the feature space of a Mercer kernel :math:`K(\mathbf{x},\mathbf{y})=\langle\Phi(\mathbf{x}),\Phi(\mathbf{y})\rangle` and runs FCM *there*: the prototypes are weighted means of the mapped samples, and the squared distance of a sample to a prototype is evaluated with kernel values only, .. math:: D^2_{ik} = K(\mathbf{x}_k,\mathbf{x}_k) - 2\sum_l w_{il}K(\mathbf{x}_k,\mathbf{x}_l) + \sum_{l,l'} w_{il}w_{il'}K(\mathbf{x}_l,\mathbf{x}_{l'}),\qquad w_{il} = \frac{\mu_{il}^m}{\sum_{l'}\mu_{il'}^m}. With a Gaussian kernel :math:`\exp(-\gamma\|\mathbf{x}-\mathbf{y}\|^2)` a sphere in feature space is a curved region in the input space, so rings and moons become separable. The example shows the two data sets, the scan over the kernel width :math:`\gamma` that every kernel method requires, the role of the fuzziness exponent :math:`m`, and the input-space variant of Zhang and Chen that trades flexibility for robustness. .. GENERATED FROM PYTHON SOURCE LINES 27-39 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import adjusted_rand_score from fuzzyclust import FCM from fuzzyclust.datasets import make_noisy_blobs, make_rings, make_two_moons from fuzzyclust.extensions import KernelFCM from fuzzyclust.plotting import PALETTE, plot_clusters, plot_membership_contours rings = make_rings(n_samples_per_ring=150, radii=(1.0, 3.0), noise=0.1, random_state=0) moons = make_two_moons(n_samples=400, noise=0.04, random_state=0) .. GENERATED FROM PYTHON SOURCE LINES 40-50 FCM versus kernel FCM --------------------- FCM cuts both data sets in half. Kernel FCM with a Gaussian kernel of suitable width separates the rings and the moons; the contours of the maximal membership (evaluated on a grid with the kernelized distance, which is how new samples are classified) follow the rings and bend around the moons. Two settings need attention. The exponent :math:`m` is close to one, because in feature space the mapped samples are nearly orthogonal and with a fuzzier exponent the memberships spread out too much. Several restarts are used because the kernel objective has many local optima. .. GENERATED FROM PYTHON SOURCE LINES 50-69 .. code-block:: Python # [snippet:fit] fcm_r = FCM(n_clusters=2, random_state=0).fit(rings[0]) kfcm_r = KernelFCM(n_clusters=2, kernel="rbf", gamma=0.3, m=1.2, n_init=5, random_state=0).fit(rings[0]) fcm_m = FCM(n_clusters=2, random_state=0).fit(moons[0]) kfcm_m = KernelFCM(n_clusters=2, kernel="rbf", gamma=15.0, m=1.1, n_init=5, random_state=0).fit(moons[0]) for name, (_, y), f, k in (("rings", rings, fcm_r, kfcm_r), ("moons", moons, fcm_m, kfcm_m)): print(f"{name}: FCM ARI = {adjusted_rand_score(y, f.labels_):.2f}, " f"kernel FCM (gamma = {k.gamma_:g}) ARI = {adjusted_rand_score(y, k.labels_):.2f}") # [/snippet:fit] fig, axes = plt.subplots(2, 2, figsize=(11, 8.6)) for row, (name, (X, y), f, k) in enumerate((("rings", rings, fcm_r, kfcm_r), ("moons", moons, fcm_m, kfcm_m))): plot_membership_contours(f, X, ax=axes[row, 0], labels=False) axes[row, 0].set_title(f"FCM on {name}: ARI = {adjusted_rand_score(y, f.labels_):.2f}") plot_membership_contours(k, X, ax=axes[row, 1], labels=False) axes[row, 1].set_title(rf"kernel FCM on {name} ($\gamma$ = {k.gamma_:g}, m = {k.m}): ARI = {adjusted_rand_score(y, k.labels_):.2f}") plt.tight_layout() .. image-sg:: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_001.png :alt: FCM on rings: ARI = -0.00, kernel FCM on rings ($\gamma$ = 0.3, m = 1.2): ARI = 1.00, FCM on moons: ARI = 0.26, kernel FCM on moons ($\gamma$ = 15, m = 1.1): ARI = 1.00 :srcset: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none rings: FCM ARI = -0.00, kernel FCM (gamma = 0.3) ARI = 1.00 moons: FCM ARI = 0.26, kernel FCM (gamma = 15) ARI = 1.00 .. GENERATED FROM PYTHON SOURCE LINES 70-75 The crosses are the approximate pre-images of the feature-space prototypes (membership-weighted means of the samples). They are only a summary for plotting (on the rings both lie near the origin) and play no role in the distances, which is why the method can describe a hollow cluster. .. GENERATED FROM PYTHON SOURCE LINES 77-89 Parameter study I: the kernel width :math:`\gamma` ---------------------------------------------------- :math:`\gamma\to0` makes the Gaussian kernel linear in the squared distance and kernel FCM collapses to FCM; a large :math:`\gamma` makes all samples mutually orthogonal in feature space, so every sample is equally far from every prototype and the partition is arbitrary. The usable window lies in between, where :math:`1/\sqrt{\gamma}` is about the gap between the structures: :math:`\gamma=0.3` gives 1.8 for the rings (gap 2), :math:`\gamma=15` gives 0.26 for the moons (gap about 0.3). The window spans less than a decade. This is the familiar difficulty of kernel clustering, and the reason why the geodesic clustering of the graph chapter is often the easier tool for manifolds. .. GENERATED FROM PYTHON SOURCE LINES 89-111 .. code-block:: Python gammas_r = (0.05, 0.1, 0.2, 0.3, 0.5, 1.0, 2.0, 5.0) gammas_m = (1.0, 2.0, 5.0, 10.0, 15.0, 20.0, 30.0, 50.0) ari_r = [adjusted_rand_score(rings[1], KernelFCM(n_clusters=2, gamma=g, m=1.2, n_init=5, random_state=0).fit(rings[0]).labels_) for g in gammas_r] ari_m = [adjusted_rand_score(moons[1], KernelFCM(n_clusters=2, gamma=g, m=1.1, n_init=5, random_state=0).fit(moons[0]).labels_) for g in gammas_m] fig, axes = plt.subplots(1, 2, figsize=(11, 4)) axes[0].plot(gammas_r, ari_r, "o-", color=PALETTE[0]) axes[0].axhline(adjusted_rand_score(rings[1], fcm_r.labels_), color="0.4", ls="--", label="FCM") axes[0].set_title("Rings: agreement with the true rings (m = 1.2)") axes[1].plot(gammas_m, ari_m, "o-", color=PALETTE[1]) axes[1].axhline(adjusted_rand_score(moons[1], fcm_m.labels_), color="0.4", ls="--", label="FCM") axes[1].set_title("Moons: agreement with the true moons (m = 1.1)") for ax in axes: ax.set_xscale("log") ax.set_xlabel(r"kernel width $\gamma$") ax.set_ylabel("adjusted Rand index") ax.set_ylim(-0.05, 1.05) ax.grid(True, color="0.9") ax.legend(frameon=False, fontsize=8) plt.tight_layout() .. image-sg:: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_002.png :alt: Rings: agreement with the true rings (m = 1.2), Moons: agreement with the true moons (m = 1.1) :srcset: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 112-121 .. code-block:: Python fig, axes = plt.subplots(1, 3, figsize=(15, 4.3), sharex=True, sharey=True) for ax, g in zip(axes, (0.05, 0.3, 5.0), strict=True): model = KernelFCM(n_clusters=2, gamma=g, m=1.2, n_init=5, random_state=0).fit(rings[0]) plot_clusters(rings[0], model.labels_, ax=ax, legend=False) ax.set_title(rf"$\gamma$ = {g}: ARI = {adjusted_rand_score(rings[1], model.labels_):.2f}, " f"mean max membership {model.membership_.max(axis=1).mean():.2f}") ax.set_aspect("equal") plt.tight_layout() .. image-sg:: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_003.png :alt: $\gamma$ = 0.05: ARI = -0.00, mean max membership 0.95, $\gamma$ = 0.3: ARI = 1.00, mean max membership 0.95, $\gamma$ = 5.0: ARI = 0.13, mean max membership 0.52 :srcset: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 122-132 Parameter study II: the exponent :math:`m` and other kernels -------------------------------------------------------------- The fuzzier the exponent, the more every feature-space prototype becomes the mean of *all* mapped samples and the less the prototypes differ; the rings are only recovered for :math:`m\lesssim1.5`. A polynomial kernel of degree two maps the plane to the quadratic monomials, in which a circle is a hyperplane and one hyperplane does separate the rings; but the outer ring is spread much more widely in that space than the inner one, and a partition that splits it has the smaller objective. The linear kernel is FCM itself. .. GENERATED FROM PYTHON SOURCE LINES 132-142 .. code-block:: Python print("rings, gamma = 0.3: ARI against m") for m in (1.1, 1.2, 1.5, 2.0, 3.0): model = KernelFCM(n_clusters=2, gamma=0.3, m=m, n_init=5, random_state=0).fit(rings[0]) print(f" m = {m}: ARI = {adjusted_rand_score(rings[1], model.labels_):.2f}, " f"mean max membership {model.membership_.max(axis=1).mean():.2f}") print("rings, other kernels (m = 1.2):") for kw in (dict(kernel="poly", degree=2), dict(kernel="poly", degree=3), dict(kernel="linear")): model = KernelFCM(n_clusters=2, m=1.2, n_init=5, random_state=0, **kw).fit(rings[0]) print(f" {kw}: ARI = {adjusted_rand_score(rings[1], model.labels_):.2f}") .. rst-class:: sphx-glr-script-out .. code-block:: none rings, gamma = 0.3: ARI against m m = 1.1: ARI = 1.00, mean max membership 1.00 m = 1.2: ARI = 1.00, mean max membership 0.95 m = 1.5: ARI = 1.00, mean max membership 0.73 m = 2.0: ARI = 0.96, mean max membership 0.50 m = 3.0: ARI = 0.27, mean max membership 0.50 rings, other kernels (m = 1.2): {'kernel': 'poly', 'degree': 2}: ARI = 0.19 {'kernel': 'poly', 'degree': 3}: ARI = 0.18 {'kernel': 'linear'}: ARI = -0.00 .. GENERATED FROM PYTHON SOURCE LINES 143-151 Parameter study III: prototypes in the input space (Zhang and Chen) --------------------------------------------------------------------- The variant with input-space prototypes keeps the centers in the data space and uses :math:`D^2=2(1-K(\mathbf{x}_k,\mathbf{v}_i))`, which saturates at 2 for distant samples. It cannot find rings, because the hard partition is still bounded by bisecting hyperplanes, but the saturation makes it a robust FCM: on the noisy blobs the outliers hardly move its centers over a wide range of :math:`\gamma`. .. GENERATED FROM PYTHON SOURCE LINES 151-184 .. code-block:: Python Xn, yn = make_noisy_blobs(n_clusters=3, n_samples_per_cluster=100, n_outliers=60, random_state=0) inl = yn >= 0 true_centers = np.array([Xn[inl][yn[inl] == i].mean(axis=0) for i in range(3)]) def center_error(V): from scipy.optimize import linear_sum_assignment D = np.linalg.norm(V[:, None] - true_centers[None], axis=2) r, c = linear_sum_assignment(D) return D[r, c].max() fcm_n = FCM(n_clusters=3, random_state=0).fit(Xn) fig, axes = plt.subplots(1, 2, figsize=(11, 4.4)) kin = KernelFCM(n_clusters=3, prototypes="input", gamma=0.1, n_init=3, random_state=0).fit(Xn) plot_membership_contours(kin, Xn, ax=axes[0], labels=False) axes[0].scatter(*true_centers.T, marker="*", s=160, color="gold", edgecolor="black", zorder=6) axes[0].set_title(rf"input-space prototypes, $\gamma$ = 0.1: center error {center_error(kin.cluster_centers_):.2f}" f" (FCM {center_error(fcm_n.cluster_centers_):.2f})") gs = (0.01, 0.03, 0.1, 0.3, 1.0, 3.0) errs = [center_error(KernelFCM(n_clusters=3, prototypes="input", gamma=g, n_init=3, random_state=0).fit(Xn).cluster_centers_) for g in gs] axes[1].plot(gs, errs, "o-", color=PALETTE[2], label="kernel FCM, input-space prototypes") axes[1].axhline(center_error(fcm_n.cluster_centers_), color="0.4", ls="--", label="FCM") axes[1].set_xscale("log") axes[1].set_xlabel(r"kernel width $\gamma$") axes[1].set_ylabel("largest center error") axes[1].set_title(r"Robustness against $\gamma$ on noisy blobs") axes[1].grid(True, color="0.9") axes[1].legend(frameon=False, fontsize=8) plt.tight_layout() .. image-sg:: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_004.png :alt: input-space prototypes, $\gamma$ = 0.1: center error 0.03 (FCM 0.20), Robustness against $\gamma$ on noisy blobs :srcset: /auto_examples/06_extensions/images/sphx_glr_plot_04_kernel_fcm_004.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 185-194 **Take-away.** Kernel FCM keeps the FCM functional and membership formula and changes only the distance, which is evaluated in the feature space of a kernel through kernel values alone; with feature-space prototypes it finds rings and moons that no point prototype can describe, with input-space prototypes it becomes a robust FCM. Both hinge on the kernel width: :math:`1/\sqrt{\gamma}` should match the gap between the structures, and the usable window is narrow, so scan :math:`\gamma`, use a nearly crisp exponent and several restarts, and prefer the geodesic methods when the data form clear manifolds. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 5.453 seconds) .. _sphx_glr_download_auto_examples_06_extensions_plot_04_kernel_fcm.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/06_extensions/plot_04_kernel_fcm.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_04_kernel_fcm.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_04_kernel_fcm.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_04_kernel_fcm.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_