.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_clustering/plot_08_sklearn_pandas_workflow.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_08_sklearn_pandas_workflow.py: Working with pandas and scikit-learn: pipelines, DataFrames, and model selection ================================================================================ Every estimator of :mod:`fuzzyclust` follows the scikit-learn conventions, so it works with the usual tooling: :class:`~sklearn.pipeline.Pipeline`, ``set_output(transform="pandas")``, :func:`~sklearn.base.clone`, :class:`~sklearn.model_selection.GridSearchCV`, pickling, and so on. Feature names of a :class:`pandas.DataFrame` are stored in ``feature_names_in_``, and the distance matrix returned by ``transform`` can itself be a DataFrame. .. GENERATED FROM PYTHON SOURCE LINES 14-29 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from fuzzyclust import FCM, GK from fuzzyclust.datasets import load_iris from fuzzyclust.validity import validity_indices iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) print(df.head()) .. rst-class:: sphx-glr-script-out .. code-block:: none sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) 0 5.1 3.5 1.4 0.2 1 4.9 3.0 1.4 0.2 2 4.7 3.2 1.3 0.2 3 4.6 3.1 1.5 0.2 4 5.0 3.6 1.4 0.2 .. GENERATED FROM PYTHON SOURCE LINES 30-32 A pipeline of scaling and GK. ``set_output`` makes ``transform`` return a DataFrame whose columns are named after the clusters. .. GENERATED FROM PYTHON SOURCE LINES 32-39 .. code-block:: Python pipe = Pipeline([("scale", StandardScaler()), ("gk", GK(n_clusters=3, random_state=0))]) pipe.set_output(transform="pandas") pipe.fit(df) distances = pipe.transform(df) print(distances.head().round(3)) print("feature names seen by GK:", list(pipe["gk"].feature_names_in_)) .. rst-class:: sphx-glr-script-out .. code-block:: none dist_cluster_0 dist_cluster_1 dist_cluster_2 0 0.144 3.882 2.430 1 0.364 3.413 1.978 2 0.264 3.569 2.106 3 0.315 3.300 1.998 4 0.193 3.941 2.510 feature names seen by GK: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] .. GENERATED FROM PYTHON SOURCE LINES 40-42 The memberships as a DataFrame, with the species attached and averaged per species: .. GENERATED FROM PYTHON SOURCE LINES 42-46 .. code-block:: Python U = pd.DataFrame(pipe.predict_proba(df), columns=[f"cluster {i + 1}" for i in range(3)]) U["species"] = pd.Categorical.from_codes(iris.target, iris.target_names) print(U.groupby("species", observed=True).mean().round(3)) .. rst-class:: sphx-glr-script-out .. code-block:: none cluster 1 cluster 2 cluster 3 species setosa 0.947 0.014 0.039 versicolor 0.024 0.252 0.724 virginica 0.013 0.701 0.285 .. GENERATED FROM PYTHON SOURCE LINES 47-53 Model selection with ``GridSearchCV`` ------------------------------------- Clustering has no ground truth, but any validity index can serve as the scoring function. Here we select :math:`c` and :math:`m` of FCM by the Xie–Beni index (lower is better, hence the negative sign), computed with the estimator's ``predict_proba`` on held-out folds. .. GENERATED FROM PYTHON SOURCE LINES 53-72 .. code-block:: Python def neg_xie_beni(estimator, X): fcm = estimator[-1] Xs = estimator[:-1].transform(X) U = fcm.predict_proba(Xs) return -validity_indices(Xs, U, fcm.cluster_centers_, m=fcm.m, indices=["XB"])["XB"] grid = GridSearchCV( Pipeline([("scale", StandardScaler()), ("fcm", FCM(random_state=0))]), param_grid={"fcm__n_clusters": [2, 3, 4, 5], "fcm__m": [1.5, 2.0, 2.5]}, scoring=neg_xie_beni, cv=3, ) grid.fit(df) print("best parameters:", grid.best_params_) res = pd.DataFrame(grid.cv_results_) pivot = res.pivot(index="param_fcm__n_clusters", columns="param_fcm__m", values="mean_test_score") print((-pivot).round(3)) # Xie–Beni values .. rst-class:: sphx-glr-script-out .. code-block:: none best parameters: {'fcm__m': 2.5, 'fcm__n_clusters': 2} param_fcm__m 1.5 2.0 2.5 param_fcm__n_clusters 2 1.206 0.935 0.723 3 2.187 1.841 1.275 4 3.426 2.186 1.230 5 3.558 2.645 2.031 .. GENERATED FROM PYTHON SOURCE LINES 73-83 .. code-block:: Python fig, ax = plt.subplots(figsize=(5.5, 4)) for m in pivot.columns: ax.plot(pivot.index, -pivot[m], marker="o", label=f"m = {m}") ax.set_xlabel("number of clusters $c$") ax.set_ylabel("Xie–Beni index (held-out)") ax.set_xticks(pivot.index) ax.legend(frameon=False) ax.grid(True, color="0.9") plt.tight_layout() .. image-sg:: /auto_examples/01_clustering/images/sphx_glr_plot_08_sklearn_pandas_workflow_001.png :alt: plot 08 sklearn pandas workflow :srcset: /auto_examples/01_clustering/images/sphx_glr_plot_08_sklearn_pandas_workflow_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 84-91 The XB index favors two clusters on iris (setosa versus the rest), a well-known property of the data set: versicolor and virginica overlap in feature space. Validity indices measure geometric separation, not agreement with external labels. Finally, the fitted pipeline can be saved with ``pickle`` or ``joblib`` like any other scikit-learn object: .. GENERATED FROM PYTHON SOURCE LINES 91-99 .. code-block:: Python import io import pickle buf = io.BytesIO() pickle.dump(pipe, buf) restored = pickle.loads(buf.getvalue()) print("pickle round trip ok:", np.allclose(restored.predict_proba(df), pipe.predict_proba(df))) .. rst-class:: sphx-glr-script-out .. code-block:: none pickle round trip ok: True .. GENERATED FROM PYTHON SOURCE LINES 100-112 Parameter study: the scoring index and the folds decide the "best" model ------------------------------------------------------------------------- Without ground truth, the scoring function *is* the model-selection criterion, so the grid search is repeated with several validity indices as scorers and with three and five folds. Two details matter in practice. First, the iris rows are sorted by species, so the folds must be shuffled (``KFold(shuffle=True)``): an unshuffled fold made of one species gives a single predicted cluster and an undefined silhouette. Second, the indices that measure fuzziness (PC) or compactness relative to separation (XB, S) agree on two clusters, whereas the fuzzy hypervolume, which estimates one covariance per cluster from 30--50 held-out samples, changes its verdict with the number of folds. .. GENERATED FROM PYTHON SOURCE LINES 112-144 .. code-block:: Python # [snippet:scoring_scan] from sklearn.model_selection import KFold def index_scorer(index, sign): def score(estimator, X): fcm = estimator[-1] Xs = estimator[:-1].transform(X) U = fcm.predict_proba(Xs) return sign * validity_indices(Xs, U, fcm.cluster_centers_, m=fcm.m, indices=[index])[index] return score scoring = {"XB": index_scorer("XB", -1), "S": index_scorer("S", -1), "SIL": index_scorer("SIL", +1), "PC": index_scorer("PC", +1), "FHV": index_scorer("FHV", -1)} best = {} for n_folds in (3, 5): search = GridSearchCV( Pipeline([("scale", StandardScaler()), ("fcm", FCM(random_state=0))]), param_grid={"fcm__n_clusters": [2, 3, 4, 5], "fcm__m": [1.5, 2.0, 2.5]}, scoring=scoring, refit=False, cv=KFold(n_folds, shuffle=True, random_state=0), ).fit(df) res = pd.DataFrame(search.cv_results_) for name in scoring: i = res[f"mean_test_{name}"].idxmax() best[(name, f"{n_folds} folds")] = f"c = {res.loc[i, 'param_fcm__n_clusters']}, m = {res.loc[i, 'param_fcm__m']}" # [/snippet:scoring_scan] print("best (c, m) per scoring index and number of folds:") print(pd.Series(best).unstack()) .. rst-class:: sphx-glr-script-out .. code-block:: none best (c, m) per scoring index and number of folds: 3 folds 5 folds FHV c = 2, m = 1.5 c = 5, m = 1.5 PC c = 2, m = 1.5 c = 2, m = 1.5 S c = 2, m = 2.0 c = 2, m = 2.0 SIL c = 2, m = 1.5 c = 2, m = 1.5 XB c = 2, m = 2.5 c = 2, m = 2.5 .. GENERATED FROM PYTHON SOURCE LINES 145-157 Take-away --------- Because the estimators follow the scikit-learn contract, scaling, fitting, membership prediction, and persistence compose without glue code, and DataFrames keep feature and cluster names attached to the numbers. The same contract makes model selection with ``GridSearchCV`` possible, but the user has to supply the criterion: a validity index evaluated with ``predict_proba`` on held-out folds. The outcome depends on that choice (the geometric indices pick the two-group structure of iris, while the hypervolume needs more data than small folds provide) and on sensible folds (shuffle sorted data). Treat the search as a consistent way to rank candidates, not as a replacement for inspecting the partitions. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.743 seconds) .. _sphx_glr_download_auto_examples_01_clustering_plot_08_sklearn_pandas_workflow.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_08_sklearn_pandas_workflow.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_08_sklearn_pandas_workflow.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_08_sklearn_pandas_workflow.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_08_sklearn_pandas_workflow.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_