.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/0120_tabicl.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 JupyterLite or Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_0120_tabicl.py: Skrub as preprocessing for Table Foundation Models ================================================== `TabICL `_ is an open source tabular foundation model: its a powerful predictor that doesn't need hyper-parameter tuning. In this example, skrub takes care of preparing the dataframe, and TabICL makes the predictions. .. note:: This example requires ``tabicl``, which is not installed with skrub. You can install it with ``pip install tabicl``. The TabICL documentation also has a tutorial on how to handle string columns with skrub: `TabICL string handling tutorial `_. .. GENERATED FROM PYTHON SOURCE LINES 20-27 Loading the data ---------------- We use the employee salaries dataset: the goal is to predict the salary of an employee from information such as their department, position title and hiring date. We only keep the first 500 rows to keep the memory pressure and runtime of the example low. .. GENERATED FROM PYTHON SOURCE LINES 27-34 .. code-block:: Python import skrub from skrub.datasets import fetch_employee_salaries data = fetch_employee_salaries() X, y = data.X.iloc[:500], data.y.iloc[:500] skrub.TableReport(X) .. raw:: html

Please enable javascript

The skrub table reports need javascript to display correctly. If you are displaying a report in a Jupyter notebook and you see this message, you may need to re-execute the cell or to trust the notebook (button on the top right or "File > Trust notebook").



.. GENERATED FROM PYTHON SOURCE LINES 35-54 Building the pipeline --------------------- :func:`~skrub.tabular_pipeline` recognizes TabICL estimators and configures the :class:`~skrub.TableVectorizer` with the following configuration: .. code-block:: python skrub.TableVectorizer( low_cardinality="passthrough", high_cardinality=skrub.StringEncoder(), cardinality_threshold=10, datetime=skrub.DatetimeEncoder(periodic_encoding="spline"), ) String columns with at most 10 unique values are passed through as-is, since TabICL handles them natively, while columns with more unique values are encoded with a :class:`~skrub.StringEncoder`. TabICL handles missing values and scaling by itself, so no imputer or scaler is added. .. GENERATED FROM PYTHON SOURCE LINES 54-61 .. code-block:: Python from tabicl import TabICLRegressor # To keep this example fast, we use a single estimator. Results would probably # be a bit better with the default ``n_estimators=8``, but it is more expensive. model = skrub.tabular_pipeline(TabICLRegressor(n_estimators=1)) model .. raw:: html
Pipeline(steps=[('tablevectorizer',
                     TableVectorizer(cardinality_threshold=10,
                                     datetime=DatetimeEncoder(periodic_encoding='spline'),
                                     low_cardinality='passthrough')),
                    ('tabiclregressor', TabICLRegressor(n_estimators=1))])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


.. GENERATED FROM PYTHON SOURCE LINES 62-66 Evaluating the model -------------------- We evaluate the pipeline with a 3-fold cross-validation. .. GENERATED FROM PYTHON SOURCE LINES 66-73 .. code-block:: Python from sklearn.model_selection import cross_validate tabicl_results = cross_validate(model, X, y, cv=3) scores = tabicl_results["test_score"] del model print(f"R2 score: {scores.mean():.3f} ± {scores.std():.3f}") .. rst-class:: sphx-glr-script-out .. code-block:: none Checkpoint 'tabicl-regressor-v2-20260212.ckpt' not cached. Downloading from Hugging Face Hub (jingang/TabICL). Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads. R2 score: 0.760 ± 0.091 .. GENERATED FROM PYTHON SOURCE LINES 74-81 Comparing with the default pipeline ----------------------------------- Passing ``"regressor"`` to :func:`~skrub.tabular_pipeline` gives a pipeline that ends with a :class:`~sklearn.ensemble.HistGradientBoostingRegressor`. The data preparation is still handled by skrub: switching the model is a one-line change. .. GENERATED FROM PYTHON SOURCE LINES 81-92 .. code-block:: Python hgb_results = cross_validate(skrub.tabular_pipeline("regressor"), X, y, cv=3) named_results = [("TabICL", tabicl_results), ("HGBT", hgb_results)] for name, results in named_results: scores = results["test_score"] duration = results["fit_time"].mean() + results["score_time"].mean() print( f"{name:<7} R2 score: {scores.mean():.3f} ± {scores.std():.3f}" f" (fit + predict time: {duration:.1f} s)" ) .. rst-class:: sphx-glr-script-out .. code-block:: none TabICL R2 score: 0.760 ± 0.091 (fit + predict time: 4.3 s) HGBT R2 score: 0.697 ± 0.113 (fit + predict time: 0.5 s) .. GENERATED FROM PYTHON SOURCE LINES 93-95 We use a boxplot to visualize the distribution of R2 scores across folds for each model. .. GENERATED FROM PYTHON SOURCE LINES 95-105 .. code-block:: Python import matplotlib.pyplot as plt fig, ax = plt.subplots() names, scores = zip(*[(name, result["test_score"]) for name, result in named_results]) ax.boxplot(scores, orientation="horizontal") ax.set_yticks(range(1, len(names) + 1), labels=list(names), size=12) ax.set_xlabel("R2 score", size=14) ax.set_title("R2 distribution across folds (higher is better)", size=14) plt.show() .. image-sg:: /auto_examples/images/sphx_glr_0120_tabicl_001.png :alt: R2 distribution across folds (higher is better) :srcset: /auto_examples/images/sphx_glr_0120_tabicl_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 106-116 On this small subset, TabICL gives better predictions than the default pipeline, at the cost of a longer computation time. This comparison is only meant to show how easily models can be swapped: results depend a lot on the dataset and its size. Note that TabICL does not need hyperparameter tuning: it works well with its default parameters. The data preparation, however, still has parameters that can matter, such as the number of components of the :class:`~skrub.StringEncoder`. These can be tuned like in any scikit-learn pipeline, for example with :class:`~sklearn.model_selection.GridSearchCV`. .. GENERATED FROM PYTHON SOURCE LINES 118-124 Conclusion ---------- skrub prepares the dataframe for TabICL in a single line with :func:`~skrub.tabular_pipeline`, which also makes it easy to compare TabICL with other models. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 21.752 seconds) **Estimated memory usage:** 1370 MB .. _sphx_glr_download_auto_examples_0120_tabicl.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/skrub-data/skrub/0.12.0?urlpath=lab/tree/notebooks/auto_examples/0120_tabicl.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../lite/lab/index.html?path=auto_examples/0120_tabicl.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: 0120_tabicl.ipynb <0120_tabicl.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: 0120_tabicl.py <0120_tabicl.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: 0120_tabicl.zip <0120_tabicl.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_