.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_clustering/plot_07_motorcycle_scaling.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_07_motorcycle_scaling.py: Feature scaling on real data: the motorcycle data set ===================================================== Distance-based clustering is meaningful only when the features are commensurable. The motorcycle data set (time after impact in ms versus head acceleration in g) is a classical case: the two variables have different units and ranges, so the raw Euclidean distance is dominated by the variable with the larger spread. The MATLAB toolbox offered ``clust_normalize`` for this purpose; :mod:`fuzzyclust` delegates scaling to scikit-learn so that it composes with ``Pipeline``, and keeps :func:`fuzzyclust.preprocessing.normalize` as a convenience function that also returns the scaler for the inverse transformation. .. GENERATED FROM PYTHON SOURCE LINES 17-32 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import MinMaxScaler, StandardScaler from fuzzyclust import GK from fuzzyclust.datasets import load_motorcycle from fuzzyclust.plotting import plot_clusters, plot_membership_contours from fuzzyclust.preprocessing import normalize mc = load_motorcycle() X = mc.data print(mc.feature_names, X.shape) print("ranges:", np.ptp(X, axis=0).round(1)) .. rst-class:: sphx-glr-script-out .. code-block:: none ['time_ms', 'acceleration_g'] (133, 2) ranges: [ 55.2 209. ] .. GENERATED FROM PYTHON SOURCE LINES 33-37 Without scaling, the time axis (range ≈ 55 ms) and the acceleration axis (range ≈ 210 g) receive unequal weights. We cluster the raw, the range-scaled, and the variance-scaled data with GK and map the prototypes back to the original units with the scaler's ``inverse_transform``. .. GENERATED FROM PYTHON SOURCE LINES 37-53 .. code-block:: Python variants = { "raw": None, "range [0, 1]": MinMaxScaler(), "unit variance": StandardScaler(), } fig, axes = plt.subplots(1, 3, figsize=(15, 4.3), sharex=True, sharey=True) for ax, (name, scaler) in zip(axes, variants.items(), strict=False): Xs = X if scaler is None else scaler.fit_transform(X) gk = GK(n_clusters=4, random_state=0).fit(Xs) centers = gk.cluster_centers_ if scaler is None else scaler.inverse_transform(gk.cluster_centers_) plot_clusters(X, gk.labels_, centers, ax=ax, legend=False) ax.set_title(name) ax.set_xlabel("time [ms]") axes[0].set_ylabel("acceleration [g]") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_07_motorcycle_scaling_001.png :alt: raw, range [0, 1], unit variance :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_07_motorcycle_scaling_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 54-66 The three partitions are identical, and so are the prototypes in physical units: the clusters follow the course of the signal in time, which is the physically meaningful segmentation. Gustafson--Kessel adapts its norm to the covariance of every cluster, so in exact arithmetic it is invariant to a rescaling of the features, and on these data the units do not change the optimum it reaches. A Euclidean method (k-means, FCM) would instead be dominated by the acceleration axis; for GK, scaling still matters when the covariance regularization is active or when the initialization leads to different local optima. A scikit-learn pipeline gives the same result and is the recommended pattern, because the scaler is then applied to new data automatically: .. GENERATED FROM PYTHON SOURCE LINES 66-70 .. code-block:: Python pipe = make_pipeline(StandardScaler(), GK(n_clusters=4, random_state=0)).fit(X) new_points = np.array([[10.0, 0.0], [30.0, -100.0], [45.0, 20.0]]) print("memberships of new points:\n", pipe.predict_proba(new_points).round(2)) .. rst-class:: sphx-glr-script-out .. code-block:: none memberships of new points: [[0.01 0.03 0.97 0. ] [0.15 0.25 0.06 0.54] [0.95 0. 0.03 0.01]] .. GENERATED FROM PYTHON SOURCE LINES 71-74 The membership contours are drawn in the scaled space, where the GK ellipses are easy to interpret; ``normalize`` returns the fitted scaler, so the figure can be labeled in original units if needed. .. GENERATED FROM PYTHON SOURCE LINES 74-83 .. code-block:: Python Xs, scaler = normalize(X, "var") gk = pipe[-1] fig, ax = plt.subplots(figsize=(6, 4.6)) plot_membership_contours(gk, Xs, ax=ax, labels=False) ax.set_xlabel("time (standardized)") ax.set_ylabel("acceleration (standardized)") ax.set_title("GK on the standardized motorcycle data") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_07_motorcycle_scaling_002.png :alt: GK on the standardized motorcycle data :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_07_motorcycle_scaling_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 84-92 Parameter study: the number of clusters on the standardized data ----------------------------------------------------------------- The motorcycle signal is one continuous curve, not a set of compact groups, so the number of clusters is the number of *pieces* the curve is cut into: a resolution, not a property of the data. The scan below fits GK on the standardized data for :math:`c=2,\dots,8` and reports the validity indices; the four panels show the partitions in the original units. .. GENERATED FROM PYTHON SOURCE LINES 92-112 .. code-block:: Python # [snippet:c_scan] from fuzzyclust.validity import scan_n_clusters, suggest_n_clusters scaler = StandardScaler().fit(X) Xs = scaler.transform(X) table = scan_n_clusters(GK(random_state=0, n_init=3), Xs, range(2, 9), indices=["XB", "SIL", "SC", "FHV"]) # [/snippet:c_scan] print(table.round(3)) print("suggested number of clusters:", suggest_n_clusters(table).to_dict()) fig, axes = plt.subplots(1, 4, figsize=(18, 4), sharex=True, sharey=True) for ax, c in zip(axes, (2, 3, 4, 6), strict=True): model = GK(n_clusters=c, random_state=0, n_init=3).fit(Xs) plot_clusters(X, model.labels_, scaler.inverse_transform(model.cluster_centers_), ax=ax, legend=False) ax.set_title(f"GK, c = {c}: XB = {table.loc[c, 'XB']:.2f}, SIL = {table.loc[c, 'SIL']:.2f}") ax.set_xlabel("time [ms]") axes[0].set_ylabel("acceleration [g]") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_07_motorcycle_scaling_003.png :alt: GK, c = 2: XB = 0.18, SIL = 0.48, GK, c = 3: XB = 0.14, SIL = 0.47, GK, c = 4: XB = 0.33, SIL = 0.30, GK, c = 6: XB = 0.23, SIL = 0.36 :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_07_motorcycle_scaling_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none XB SIL SC FHV n_clusters 2 0.180 0.479 0.353 0.688 3 0.144 0.472 0.133 0.566 4 0.326 0.299 0.278 0.469 5 0.795 0.302 0.112 0.413 6 0.230 0.365 0.075 0.406 7 0.292 0.365 0.056 0.361 8 0.318 0.382 0.044 0.360 suggested number of clusters: {'XB': 3, 'SIL': 2, 'SC': 8, 'FHV': 8} .. GENERATED FROM PYTHON SOURCE LINES 113-128 Take-away --------- Distances are meaningful only between commensurable features, so scaling is part of the model and belongs in the pipeline, where it is applied to new data automatically. On the motorcycle data the raw, range-scaled, and variance-scaled data give the same GK partition, a segmentation along the time axis, because the adaptive norm of GK absorbs the units; a Euclidean method would not. The number of clusters is a different kind of decision. The indices disagree (XB prefers three pieces, the silhouette two, and SC and the fuzzy hypervolume as many as allowed) because a curve has no "true" number of compact groups. Each extra cluster gives a finer local linear approximation of the signal. This is the viewpoint of the Takagi--Sugeno models in the modeling section, where :math:`c` is chosen by the prediction error rather than by a cluster validity index. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.881 seconds) .. _sphx_glr_download_auto_examples_01_clustering_plot_07_motorcycle_scaling.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_07_motorcycle_scaling.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_07_motorcycle_scaling.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_07_motorcycle_scaling.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_07_motorcycle_scaling.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_