.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/03_models/plot_04_fcrm_switching.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_03_models_plot_04_fcrm_switching.py: Fuzzy c-regression models: switching regression with crossing lines =================================================================== In a *switching regression* problem, every sample :math:`(\mathbf{x}_k, y_k)` obeys one of :math:`c` unknown linear laws, but which one is not known. Hathaway and Bezdek replaced the point prototypes of fuzzy c-means by regression models: the "distance" of a sample to cluster :math:`i` is the squared residual :math:`E_{ik}=(y_k-\mathbf{x}_{e,k}^T\boldsymbol\theta_i)^2` of the :math:`i`-th model, and the alternating optimization of .. math:: J=\sum_{i=1}^{c}\sum_{k=1}^{N}\mu_{ik}^m E_{ik}(\boldsymbol\theta_i) alternates weighted least squares (with :math:`\mu_{ik}^m` as weights) and the FCM membership update. Because the prototypes are hyperplanes, the clusters may cross each other. Clustering the points with FCM fails in this configuration, because its spherical clusters cut the cross into halves; GK, whose clusters stretch along the lines, separates them but describes each law only by an ellipsoid. This example compares the point prototypes with FCRM and shows the role of the restarts and of the exponent :math:`m`. .. GENERATED FROM PYTHON SOURCE LINES 25-38 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.metrics import adjusted_rand_score from fuzzyclust import FCM, GK from fuzzyclust.models import FuzzyCRegression, make_switching_lines from fuzzyclust.plotting import PALETTE, plot_clusters, plot_covariance_ellipses X, y, labels = make_switching_lines(n_samples=300, slopes=(1.0, -1.0), intercepts=(0.0, 1.0), noise=0.1, random_state=0) Z = np.hstack([X, y[:, None]]) # the product space (x, y) .. GENERATED FROM PYTHON SOURCE LINES 39-43 Point prototypes versus regression prototypes --------------------------------------------- FCM and GK are run on the :math:`(x, y)` points, FCRM on the input–output pairs. .. GENERATED FROM PYTHON SOURCE LINES 43-69 .. code-block:: Python # [snippet:fit] fcm = FCM(n_clusters=2, random_state=0).fit(Z) gk = GK(n_clusters=2, random_state=0).fit(Z) fcrm = FuzzyCRegression(n_clusters=2, n_init=5, random_state=0).fit(X, y) print("slopes :", fcrm.coef_[:, 0].round(3)) print("intercepts:", fcrm.intercept_.round(3)) # [/snippet:fit] grid = np.linspace(-2, 2, 100)[:, None] fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), sharey=True) for ax, model, name in zip(axes[:2], (fcm, gk), ("FCM", "GK"), strict=True): plot_clusters(Z, model.labels_, model.cluster_centers_, ax=ax, legend=False) if hasattr(model, "covariances_"): plot_covariance_ellipses(model.cluster_centers_, model.covariances_, ax=ax) ax.set_title(f"{name} on the points: ARI = {adjusted_rand_score(labels, model.labels_):.2f}") plot_clusters(Z, fcrm.labels_, ax=axes[2], legend=False) lines = fcrm.predict(grid) for i in range(2): axes[2].plot(grid[:, 0], lines[:, i], color=PALETTE[i], lw=2.5) axes[2].set_title(f"FCRM on the pairs: ARI = {adjusted_rand_score(labels, fcrm.labels_):.2f}") for ax in axes: ax.set_xlabel("x") axes[0].set_ylabel("y") plt.tight_layout() .. image-sg:: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_001.png :alt: FCM on the points: ARI = 0.28, GK on the points: ARI = 0.96, FCRM on the pairs: ARI = 0.96 :srcset: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none slopes : [-0.998 1.005] intercepts: [ 0.98 -0.007] .. GENERATED FROM PYTHON SOURCE LINES 70-84 FCM splits the plane into a left and a right half. GK finds two elongated ellipsoids that follow one line each and labels the points as well as FCRM; both mislabel only a few points at the crossing, where the two laws are equally close. FCRM, in addition, recovers the slopes and intercepts and assigns every point to the line with the smaller residual. Memberships along the input --------------------------- The membership of a pair depends on both residuals: near the crossing (:math:`x=0.5`) both lines fit and the memberships approach 1/2, whereas far from it the assignment is crisp. The membership can only be evaluated for *pairs*. For a new input alone, the model returns the outputs of all :math:`c` local models (``predict``), because a switching model does not know which law a new input obeys. .. GENERATED FROM PYTHON SOURCE LINES 84-100 .. code-block:: Python U = fcrm.predict_proba(X, y) fig, axes = plt.subplots(1, 2, figsize=(11, 4)) for i in range(2): axes[0].scatter(X[labels == i, 0], U[labels == i, 0], s=10, color=PALETTE[i], label=f"generated by line {i + 1}") axes[0].axhline(0.5, color="0.5", ls=":") axes[0].set_xlabel("x") axes[0].set_ylabel(r"membership $\mu_{1k}$ in model 1") axes[0].set_title("Memberships are fuzzy only where the lines cross") axes[0].legend(frameon=False, fontsize=8) axes[1].plot(fcrm.objective_history_, "o-", color=PALETTE[0]) axes[1].set_xlabel("iteration") axes[1].set_ylabel("$J$") axes[1].set_title(f"Monotone decrease of the objective ({fcrm.n_iter_} iterations)") axes[1].grid(True, color="0.9") plt.tight_layout() .. image-sg:: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_002.png :alt: Memberships are fuzzy only where the lines cross, Monotone decrease of the objective (11 iterations) :srcset: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 101-109 Three lines, and the need for restarts -------------------------------------- With more models the functional has more local minima, in particular when two of the laws are similar. Here two parallel lines (slope 1, intercepts 0 and 1) are crossed by a third one. A random initial partition may converge to a solution in which one model fits the "average" of the two parallel lines and another one is wasted. Running ``n_init`` restarts and keeping the lowest :math:`J` eliminates most such solutions. .. GENERATED FROM PYTHON SOURCE LINES 109-134 .. code-block:: Python X3, y3, lab3 = make_switching_lines( n_samples=450, slopes=(1.0, 1.0, -1.0), intercepts=(0.0, 1.0, 0.5), noise=0.1, random_state=3 ) # [snippet:restarts] single = [FuzzyCRegression(n_clusters=3, random_state=s).fit(X3, y3) for s in range(12)] best = FuzzyCRegression(n_clusters=3, n_init=12, random_state=0).fit(X3, y3) objectives = np.array([m.objective_ for m in single]) aris = np.array([adjusted_rand_score(lab3, m.labels_) for m in single]) # [/snippet:restarts] print(pd.DataFrame({"seed": range(12), "J": objectives.round(2), "ARI": aris.round(3)}).to_string(index=False)) print(f"best of 12 restarts: J = {best.objective_:.2f}, ARI = {adjusted_rand_score(lab3, best.labels_):.3f}") fig, axes = plt.subplots(1, 2, figsize=(11, 4.2)) worst = single[int(np.argmax(objectives))] for ax, model, name in zip(axes, (worst, best), ("worst single run", "best of 12 restarts"), strict=True): plot_clusters(np.hstack([X3, y3[:, None]]), model.labels_, ax=ax, legend=False) lines = model.predict(grid) for i in range(3): ax.plot(grid[:, 0], lines[:, i], color=PALETTE[i], lw=2.5) ax.set_title(f"{name}: J = {model.objective_:.1f}, ARI = {adjusted_rand_score(lab3, model.labels_):.2f}") ax.set_xlabel("x") axes[0].set_ylabel("y") plt.tight_layout() .. image-sg:: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_003.png :alt: worst single run: J = 46.3, ARI = 0.06, best of 12 restarts: J = 3.9, ARI = 0.93 :srcset: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none seed J ARI 0 3.87 0.931 1 3.87 0.931 2 14.73 0.333 3 14.73 0.333 4 3.87 0.931 5 14.73 0.333 6 46.34 0.064 7 3.87 0.931 8 14.73 0.333 9 3.87 0.931 10 3.87 0.931 11 46.34 0.064 best of 12 restarts: J = 3.87, ARI = 0.931 .. GENERATED FROM PYTHON SOURCE LINES 135-142 Parameter study: the fuzziness exponent --------------------------------------- As in FCM, :math:`m` controls how sharply the residual ratio is turned into memberships. A small :math:`m` gives a nearly crisp assignment (close to the classical switching-regression EM with hard labels); a large :math:`m` spreads the memberships. Here the fitted lines hardly move with :math:`m`, because the residual ratios away from the crossing are sharp. .. GENERATED FROM PYTHON SOURCE LINES 142-168 .. code-block:: Python # [snippet:m_scan] rows = [] for m in (1.2, 1.5, 2.0, 3.0, 5.0): model = FuzzyCRegression(n_clusters=2, m=m, n_init=5, random_state=0).fit(X, y) rows.append( { "m": m, "slopes": np.sort(model.coef_[:, 0]).round(3), "ARI": adjusted_rand_score(labels, model.labels_), "mean max membership": model.membership_.max(axis=1).mean(), } ) table = pd.DataFrame(rows) # [/snippet:m_scan] print(table.round(3).to_string(index=False)) fig, ax = plt.subplots(figsize=(6, 4)) ax.plot(table["m"], table["mean max membership"], "o-", color=PALETTE[0], label="mean of $\\max_i \\mu_{ik}$") ax.plot(table["m"], table["ARI"], "s-", color=PALETTE[1], label="ARI with the generating lines") ax.set_xlabel("fuzziness exponent $m$") ax.set_title("Effect of $m$ on the FCRM partition") ax.legend(frameon=False, fontsize=8) ax.grid(True, color="0.9") plt.tight_layout() .. image-sg:: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_004.png :alt: Effect of $m$ on the FCRM partition :srcset: /auto_examples/03_models/images/sphx_glr_plot_04_fcrm_switching_004.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none m slopes ARI mean max membership 1.2 [-0.998, 1.005] 0.96 0.999 1.5 [-0.998, 1.005] 0.96 0.993 2.0 [-0.998, 1.005] 0.96 0.981 3.0 [-0.999, 1.005] 0.96 0.938 5.0 [-1.0, 1.004] 0.96 0.832 .. GENERATED FROM PYTHON SOURCE LINES 169-179 **Take-away.** When the structure in the data is a set of linear laws rather than a set of compact groups, the prototype must be a regression model. FCRM measures the distance of a sample by its residual and thus handles crossing lines that defeat FCM and that GK describes only by ellipsoids. The method inherits the local minima of the c-means functional (use ``n_init``), and its membership needs the output. Prediction from the input alone requires a model with an input-space partition (Takagi–Sugeno) or the hinging-hyperplane construction of the next examples. Keep :math:`m` near 2; larger values make the partition fuzzier without improving the lines. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.496 seconds) .. _sphx_glr_download_auto_examples_03_models_plot_04_fcrm_switching.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/03_models/plot_04_fcrm_switching.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_04_fcrm_switching.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_04_fcrm_switching.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_04_fcrm_switching.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_