.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/preprocessing/plot_target_encoder.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_preprocessing_plot_target_encoder.py>`
        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_preprocessing_plot_target_encoder.py:


============================================
Comparing Target Encoder with Other Encoders
============================================

.. currentmodule:: sklearn.preprocessing

The :class:`TargetEncoder` uses the value of the target to encode each
categorical feature. In this example, we will compare three different approaches
for handling categorical features: :class:`TargetEncoder`,
:class:`OrdinalEncoder`, :class:`OneHotEncoder` and dropping the category.

.. note::
    `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a
    cross fitting scheme is used in `fit_transform` for encoding. See the
    :ref:`User Guide <target_encoder>`. for details.

.. GENERATED FROM PYTHON SOURCE LINES 20-24

Loading Data from OpenML
========================
First, we load the wine reviews dataset, where the target is the points given
be a reviewer:

.. GENERATED FROM PYTHON SOURCE LINES 24-31

.. code-block:: Python

    from sklearn.datasets import fetch_openml

    wine_reviews = fetch_openml(data_id=42074, as_frame=True)

    df = wine_reviews.frame
    df.head()






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>country</th>
          <th>description</th>
          <th>designation</th>
          <th>points</th>
          <th>price</th>
          <th>province</th>
          <th>region_1</th>
          <th>region_2</th>
          <th>variety</th>
          <th>winery</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>US</td>
          <td>This tremendous 100% varietal wine hails from ...</td>
          <td>Martha's Vineyard</td>
          <td>96</td>
          <td>235.0</td>
          <td>California</td>
          <td>Napa Valley</td>
          <td>Napa</td>
          <td>Cabernet Sauvignon</td>
          <td>Heitz</td>
        </tr>
        <tr>
          <th>1</th>
          <td>Spain</td>
          <td>Ripe aromas of fig, blackberry and cassis are ...</td>
          <td>Carodorum Selección Especial Reserva</td>
          <td>96</td>
          <td>110.0</td>
          <td>Northern Spain</td>
          <td>Toro</td>
          <td>NaN</td>
          <td>Tinta de Toro</td>
          <td>Bodega Carmen Rodríguez</td>
        </tr>
        <tr>
          <th>2</th>
          <td>US</td>
          <td>Mac Watson honors the memory of a wine once ma...</td>
          <td>Special Selected Late Harvest</td>
          <td>96</td>
          <td>90.0</td>
          <td>California</td>
          <td>Knights Valley</td>
          <td>Sonoma</td>
          <td>Sauvignon Blanc</td>
          <td>Macauley</td>
        </tr>
        <tr>
          <th>3</th>
          <td>US</td>
          <td>This spent 20 months in 30% new French oak, an...</td>
          <td>Reserve</td>
          <td>96</td>
          <td>65.0</td>
          <td>Oregon</td>
          <td>Willamette Valley</td>
          <td>Willamette Valley</td>
          <td>Pinot Noir</td>
          <td>Ponzi</td>
        </tr>
        <tr>
          <th>4</th>
          <td>France</td>
          <td>This is the top wine from La Bégude, named aft...</td>
          <td>La Brûlade</td>
          <td>95</td>
          <td>66.0</td>
          <td>Provence</td>
          <td>Bandol</td>
          <td>NaN</td>
          <td>Provence red blend</td>
          <td>Domaine de la Bégude</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 32-34

For this example, we use the following subset of numerical and categorical
features in the data. The target are continuous values from 80 to 100:

.. GENERATED FROM PYTHON SOURCE LINES 34-50

.. code-block:: Python

    numerical_features = ["price"]
    categorical_features = [
        "country",
        "province",
        "region_1",
        "region_2",
        "variety",
        "winery",
    ]
    target_name = "points"

    X = df[numerical_features + categorical_features]
    y = df[target_name]

    _ = y.hist()




.. image-sg:: /auto_examples/preprocessing/images/sphx_glr_plot_target_encoder_001.png
   :alt: plot target encoder
   :srcset: /auto_examples/preprocessing/images/sphx_glr_plot_target_encoder_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 51-57

Training and Evaluating Pipelines with Different Encoders
=========================================================
In this section, we will evaluate pipelines with
:class:`~sklearn.ensemble.HistGradientBoostingRegressor` with different encoding
strategies. First, we list out the encoders we will be using to preprocess
the categorical features:

.. GENERATED FROM PYTHON SOURCE LINES 57-70

.. code-block:: Python

    from sklearn.compose import ColumnTransformer
    from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, TargetEncoder

    categorical_preprocessors = [
        ("drop", "drop"),
        ("ordinal", OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1)),
        (
            "one_hot",
            OneHotEncoder(handle_unknown="ignore", max_categories=20, sparse_output=False),
        ),
        ("target", TargetEncoder(target_type="continuous")),
    ]








.. GENERATED FROM PYTHON SOURCE LINES 71-72

Next, we evaluate the models using cross validation and record the results:

.. GENERATED FROM PYTHON SOURCE LINES 72-116

.. code-block:: Python

    from sklearn.ensemble import HistGradientBoostingRegressor
    from sklearn.model_selection import cross_validate
    from sklearn.pipeline import make_pipeline

    n_cv_folds = 3
    max_iter = 20
    results = []


    def evaluate_model_and_store(name, pipe):
        result = cross_validate(
            pipe,
            X,
            y,
            scoring="neg_root_mean_squared_error",
            cv=n_cv_folds,
            return_train_score=True,
        )
        rmse_test_score = -result["test_score"]
        rmse_train_score = -result["train_score"]
        results.append(
            {
                "preprocessor": name,
                "rmse_test_mean": rmse_test_score.mean(),
                "rmse_test_std": rmse_train_score.std(),
                "rmse_train_mean": rmse_train_score.mean(),
                "rmse_train_std": rmse_train_score.std(),
            }
        )


    for name, categorical_preprocessor in categorical_preprocessors:
        preprocessor = ColumnTransformer(
            [
                ("numerical", "passthrough", numerical_features),
                ("categorical", categorical_preprocessor, categorical_features),
            ]
        )
        pipe = make_pipeline(
            preprocessor, HistGradientBoostingRegressor(random_state=0, max_iter=max_iter)
        )
        evaluate_model_and_store(name, pipe)









.. GENERATED FROM PYTHON SOURCE LINES 117-123

Native Categorical Feature Support
==================================
In this section, we build and evaluate a pipeline that uses native categorical
feature support in :class:`~sklearn.ensemble.HistGradientBoostingRegressor`,
which only supports up to 255 unique categories. In our dataset, the most of
the categorical features have more than 255 unique categories:

.. GENERATED FROM PYTHON SOURCE LINES 123-126

.. code-block:: Python

    n_unique_categories = df[categorical_features].nunique().sort_values(ascending=False)
    n_unique_categories





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    winery      14810
    region_1     1236
    variety       632
    province      455
    country        48
    region_2       18
    dtype: int64



.. GENERATED FROM PYTHON SOURCE LINES 127-131

To workaround the limitation above, we group the categorical features into
low cardinality and high cardinality features. The high cardinality features
will be target encoded and the low cardinality features will use the native
categorical feature in gradient boosting.

.. GENERATED FROM PYTHON SOURCE LINES 131-161

.. code-block:: Python

    high_cardinality_features = n_unique_categories[n_unique_categories > 255].index
    low_cardinality_features = n_unique_categories[n_unique_categories <= 255].index
    mixed_encoded_preprocessor = ColumnTransformer(
        [
            ("numerical", "passthrough", numerical_features),
            (
                "high_cardinality",
                TargetEncoder(target_type="continuous"),
                high_cardinality_features,
            ),
            (
                "low_cardinality",
                OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1),
                low_cardinality_features,
            ),
        ],
        verbose_feature_names_out=False,
    )

    # The output of the of the preprocessor must be set to pandas so the
    # gradient boosting model can detect the low cardinality features.
    mixed_encoded_preprocessor.set_output(transform="pandas")
    mixed_pipe = make_pipeline(
        mixed_encoded_preprocessor,
        HistGradientBoostingRegressor(
            random_state=0, max_iter=max_iter, categorical_features=low_cardinality_features
        ),
    )
    mixed_pipe






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <style>#sk-container-id-64 {
      /* Definition of color scheme common for light and dark mode */
      --sklearn-color-text: black;
      --sklearn-color-line: gray;
      /* Definition of color scheme for unfitted estimators */
      --sklearn-color-unfitted-level-0: #fff5e6;
      --sklearn-color-unfitted-level-1: #f6e4d2;
      --sklearn-color-unfitted-level-2: #ffe0b3;
      --sklearn-color-unfitted-level-3: chocolate;
      /* Definition of color scheme for fitted estimators */
      --sklearn-color-fitted-level-0: #f0f8ff;
      --sklearn-color-fitted-level-1: #d4ebff;
      --sklearn-color-fitted-level-2: #b3dbfd;
      --sklearn-color-fitted-level-3: cornflowerblue;

      /* Specific color for light theme */
      --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));
      --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));
      --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));
      --sklearn-color-icon: #696969;

      @media (prefers-color-scheme: dark) {
        /* Redefinition of color scheme for dark theme */
        --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));
        --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));
        --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));
        --sklearn-color-icon: #878787;
      }
    }

    #sk-container-id-64 {
      color: var(--sklearn-color-text);
    }

    #sk-container-id-64 pre {
      padding: 0;
    }

    #sk-container-id-64 input.sk-hidden--visually {
      border: 0;
      clip: rect(1px 1px 1px 1px);
      clip: rect(1px, 1px, 1px, 1px);
      height: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
    }

    #sk-container-id-64 div.sk-dashed-wrapped {
      border: 1px dashed var(--sklearn-color-line);
      margin: 0 0.4em 0.5em 0.4em;
      box-sizing: border-box;
      padding-bottom: 0.4em;
      background-color: var(--sklearn-color-background);
    }

    #sk-container-id-64 div.sk-container {
      /* jupyter's `normalize.less` sets `[hidden] { display: none; }`
         but bootstrap.min.css set `[hidden] { display: none !important; }`
         so we also need the `!important` here to be able to override the
         default hidden behavior on the sphinx rendered scikit-learn.org.
         See: https://github.com/scikit-learn/scikit-learn/issues/21755 */
      display: inline-block !important;
      position: relative;
    }

    #sk-container-id-64 div.sk-text-repr-fallback {
      display: none;
    }

    div.sk-parallel-item,
    div.sk-serial,
    div.sk-item {
      /* draw centered vertical line to link estimators */
      background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));
      background-size: 2px 100%;
      background-repeat: no-repeat;
      background-position: center center;
    }

    /* Parallel-specific style estimator block */

    #sk-container-id-64 div.sk-parallel-item::after {
      content: "";
      width: 100%;
      border-bottom: 2px solid var(--sklearn-color-text-on-default-background);
      flex-grow: 1;
    }

    #sk-container-id-64 div.sk-parallel {
      display: flex;
      align-items: stretch;
      justify-content: center;
      background-color: var(--sklearn-color-background);
      position: relative;
    }

    #sk-container-id-64 div.sk-parallel-item {
      display: flex;
      flex-direction: column;
    }

    #sk-container-id-64 div.sk-parallel-item:first-child::after {
      align-self: flex-end;
      width: 50%;
    }

    #sk-container-id-64 div.sk-parallel-item:last-child::after {
      align-self: flex-start;
      width: 50%;
    }

    #sk-container-id-64 div.sk-parallel-item:only-child::after {
      width: 0;
    }

    /* Serial-specific style estimator block */

    #sk-container-id-64 div.sk-serial {
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: var(--sklearn-color-background);
      padding-right: 1em;
      padding-left: 1em;
    }


    /* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is
    clickable and can be expanded/collapsed.
    - Pipeline and ColumnTransformer use this feature and define the default style
    - Estimators will overwrite some part of the style using the `sk-estimator` class
    */

    /* Pipeline and ColumnTransformer style (default) */

    #sk-container-id-64 div.sk-toggleable {
      /* Default theme specific background. It is overwritten whether we have a
      specific estimator or a Pipeline/ColumnTransformer */
      background-color: var(--sklearn-color-background);
    }

    /* Toggleable label */
    #sk-container-id-64 label.sk-toggleable__label {
      cursor: pointer;
      display: block;
      width: 100%;
      margin-bottom: 0;
      padding: 0.5em;
      box-sizing: border-box;
      text-align: center;
    }

    #sk-container-id-64 label.sk-toggleable__label-arrow:before {
      /* Arrow on the left of the label */
      content: "▸";
      float: left;
      margin-right: 0.25em;
      color: var(--sklearn-color-icon);
    }

    #sk-container-id-64 label.sk-toggleable__label-arrow:hover:before {
      color: var(--sklearn-color-text);
    }

    /* Toggleable content - dropdown */

    #sk-container-id-64 div.sk-toggleable__content {
      max-height: 0;
      max-width: 0;
      overflow: hidden;
      text-align: left;
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-0);
    }

    #sk-container-id-64 div.sk-toggleable__content.fitted {
      /* fitted */
      background-color: var(--sklearn-color-fitted-level-0);
    }

    #sk-container-id-64 div.sk-toggleable__content pre {
      margin: 0.2em;
      border-radius: 0.25em;
      color: var(--sklearn-color-text);
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-0);
    }

    #sk-container-id-64 div.sk-toggleable__content.fitted pre {
      /* unfitted */
      background-color: var(--sklearn-color-fitted-level-0);
    }

    #sk-container-id-64 input.sk-toggleable__control:checked~div.sk-toggleable__content {
      /* Expand drop-down */
      max-height: 200px;
      max-width: 100%;
      overflow: auto;
    }

    #sk-container-id-64 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {
      content: "▾";
    }

    /* Pipeline/ColumnTransformer-specific style */

    #sk-container-id-64 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {
      color: var(--sklearn-color-text);
      background-color: var(--sklearn-color-unfitted-level-2);
    }

    #sk-container-id-64 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {
      background-color: var(--sklearn-color-fitted-level-2);
    }

    /* Estimator-specific style */

    /* Colorize estimator box */
    #sk-container-id-64 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-2);
    }

    #sk-container-id-64 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {
      /* fitted */
      background-color: var(--sklearn-color-fitted-level-2);
    }

    #sk-container-id-64 div.sk-label label.sk-toggleable__label,
    #sk-container-id-64 div.sk-label label {
      /* The background is the default theme color */
      color: var(--sklearn-color-text-on-default-background);
    }

    /* On hover, darken the color of the background */
    #sk-container-id-64 div.sk-label:hover label.sk-toggleable__label {
      color: var(--sklearn-color-text);
      background-color: var(--sklearn-color-unfitted-level-2);
    }

    /* Label box, darken color on hover, fitted */
    #sk-container-id-64 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {
      color: var(--sklearn-color-text);
      background-color: var(--sklearn-color-fitted-level-2);
    }

    /* Estimator label */

    #sk-container-id-64 div.sk-label label {
      font-family: monospace;
      font-weight: bold;
      display: inline-block;
      line-height: 1.2em;
    }

    #sk-container-id-64 div.sk-label-container {
      text-align: center;
    }

    /* Estimator-specific */
    #sk-container-id-64 div.sk-estimator {
      font-family: monospace;
      border: 1px dotted var(--sklearn-color-border-box);
      border-radius: 0.25em;
      box-sizing: border-box;
      margin-bottom: 0.5em;
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-0);
    }

    #sk-container-id-64 div.sk-estimator.fitted {
      /* fitted */
      background-color: var(--sklearn-color-fitted-level-0);
    }

    /* on hover */
    #sk-container-id-64 div.sk-estimator:hover {
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-2);
    }

    #sk-container-id-64 div.sk-estimator.fitted:hover {
      /* fitted */
      background-color: var(--sklearn-color-fitted-level-2);
    }

    /* Specification for estimator info (e.g. "i" and "?") */

    /* Common style for "i" and "?" */

    .sk-estimator-doc-link,
    a:link.sk-estimator-doc-link,
    a:visited.sk-estimator-doc-link {
      float: right;
      font-size: smaller;
      line-height: 1em;
      font-family: monospace;
      background-color: var(--sklearn-color-background);
      border-radius: 1em;
      height: 1em;
      width: 1em;
      text-decoration: none !important;
      margin-left: 1ex;
      /* unfitted */
      border: var(--sklearn-color-unfitted-level-1) 1pt solid;
      color: var(--sklearn-color-unfitted-level-1);
    }

    .sk-estimator-doc-link.fitted,
    a:link.sk-estimator-doc-link.fitted,
    a:visited.sk-estimator-doc-link.fitted {
      /* fitted */
      border: var(--sklearn-color-fitted-level-1) 1pt solid;
      color: var(--sklearn-color-fitted-level-1);
    }

    /* On hover */
    div.sk-estimator:hover .sk-estimator-doc-link:hover,
    .sk-estimator-doc-link:hover,
    div.sk-label-container:hover .sk-estimator-doc-link:hover,
    .sk-estimator-doc-link:hover {
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-3);
      color: var(--sklearn-color-background);
      text-decoration: none;
    }

    div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,
    .sk-estimator-doc-link.fitted:hover,
    div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,
    .sk-estimator-doc-link.fitted:hover {
      /* fitted */
      background-color: var(--sklearn-color-fitted-level-3);
      color: var(--sklearn-color-background);
      text-decoration: none;
    }

    /* Span, style for the box shown on hovering the info icon */
    .sk-estimator-doc-link span {
      display: none;
      z-index: 9999;
      position: relative;
      font-weight: normal;
      right: .2ex;
      padding: .5ex;
      margin: .5ex;
      width: min-content;
      min-width: 20ex;
      max-width: 50ex;
      color: var(--sklearn-color-text);
      box-shadow: 2pt 2pt 4pt #999;
      /* unfitted */
      background: var(--sklearn-color-unfitted-level-0);
      border: .5pt solid var(--sklearn-color-unfitted-level-3);
    }

    .sk-estimator-doc-link.fitted span {
      /* fitted */
      background: var(--sklearn-color-fitted-level-0);
      border: var(--sklearn-color-fitted-level-3);
    }

    .sk-estimator-doc-link:hover span {
      display: block;
    }

    /* "?"-specific style due to the `<a>` HTML tag */

    #sk-container-id-64 a.estimator_doc_link {
      float: right;
      font-size: 1rem;
      line-height: 1em;
      font-family: monospace;
      background-color: var(--sklearn-color-background);
      border-radius: 1rem;
      height: 1rem;
      width: 1rem;
      text-decoration: none;
      /* unfitted */
      color: var(--sklearn-color-unfitted-level-1);
      border: var(--sklearn-color-unfitted-level-1) 1pt solid;
    }

    #sk-container-id-64 a.estimator_doc_link.fitted {
      /* fitted */
      border: var(--sklearn-color-fitted-level-1) 1pt solid;
      color: var(--sklearn-color-fitted-level-1);
    }

    /* On hover */
    #sk-container-id-64 a.estimator_doc_link:hover {
      /* unfitted */
      background-color: var(--sklearn-color-unfitted-level-3);
      color: var(--sklearn-color-background);
      text-decoration: none;
    }

    #sk-container-id-64 a.estimator_doc_link.fitted:hover {
      /* fitted */
      background-color: var(--sklearn-color-fitted-level-3);
    }
    </style><div id="sk-container-id-64" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>Pipeline(steps=[(&#x27;columntransformer&#x27;,
                     ColumnTransformer(transformers=[(&#x27;numerical&#x27;, &#x27;passthrough&#x27;,
                                                      [&#x27;price&#x27;]),
                                                     (&#x27;high_cardinality&#x27;,
                                                      TargetEncoder(target_type=&#x27;continuous&#x27;),
                                                      Index([&#x27;winery&#x27;, &#x27;region_1&#x27;, &#x27;variety&#x27;, &#x27;province&#x27;], dtype=&#x27;object&#x27;)),
                                                     (&#x27;low_cardinality&#x27;,
                                                      OrdinalEncoder(handle_unknown=&#x27;use_encoded_value&#x27;,
                                                                     unknown_value=-1),
                                                      Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;))],
                                       verbose_feature_names_out=False)),
                    (&#x27;histgradientboostingregressor&#x27;,
                     HistGradientBoostingRegressor(categorical_features=Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;),
                                                   max_iter=20, random_state=0))])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class="sk-container" hidden><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-277" type="checkbox" ><label for="sk-estimator-id-277" class="sk-toggleable__label  sk-toggleable__label-arrow ">&nbsp;&nbsp;Pipeline<a class="sk-estimator-doc-link " rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.pipeline.Pipeline.html">?<span>Documentation for Pipeline</span></a><span class="sk-estimator-doc-link ">i<span>Not fitted</span></span></label><div class="sk-toggleable__content "><pre>Pipeline(steps=[(&#x27;columntransformer&#x27;,
                     ColumnTransformer(transformers=[(&#x27;numerical&#x27;, &#x27;passthrough&#x27;,
                                                      [&#x27;price&#x27;]),
                                                     (&#x27;high_cardinality&#x27;,
                                                      TargetEncoder(target_type=&#x27;continuous&#x27;),
                                                      Index([&#x27;winery&#x27;, &#x27;region_1&#x27;, &#x27;variety&#x27;, &#x27;province&#x27;], dtype=&#x27;object&#x27;)),
                                                     (&#x27;low_cardinality&#x27;,
                                                      OrdinalEncoder(handle_unknown=&#x27;use_encoded_value&#x27;,
                                                                     unknown_value=-1),
                                                      Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;))],
                                       verbose_feature_names_out=False)),
                    (&#x27;histgradientboostingregressor&#x27;,
                     HistGradientBoostingRegressor(categorical_features=Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;),
                                                   max_iter=20, random_state=0))])</pre></div> </div></div><div class="sk-serial"><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-278" type="checkbox" ><label for="sk-estimator-id-278" class="sk-toggleable__label  sk-toggleable__label-arrow ">&nbsp;columntransformer: ColumnTransformer<a class="sk-estimator-doc-link " rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.ColumnTransformer.html">?<span>Documentation for columntransformer: ColumnTransformer</span></a></label><div class="sk-toggleable__content "><pre>ColumnTransformer(transformers=[(&#x27;numerical&#x27;, &#x27;passthrough&#x27;, [&#x27;price&#x27;]),
                                    (&#x27;high_cardinality&#x27;,
                                     TargetEncoder(target_type=&#x27;continuous&#x27;),
                                     Index([&#x27;winery&#x27;, &#x27;region_1&#x27;, &#x27;variety&#x27;, &#x27;province&#x27;], dtype=&#x27;object&#x27;)),
                                    (&#x27;low_cardinality&#x27;,
                                     OrdinalEncoder(handle_unknown=&#x27;use_encoded_value&#x27;,
                                                    unknown_value=-1),
                                     Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;))],
                      verbose_feature_names_out=False)</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-279" type="checkbox" ><label for="sk-estimator-id-279" class="sk-toggleable__label  sk-toggleable__label-arrow ">numerical</label><div class="sk-toggleable__content "><pre>[&#x27;price&#x27;]</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-280" type="checkbox" ><label for="sk-estimator-id-280" class="sk-toggleable__label  sk-toggleable__label-arrow ">passthrough</label><div class="sk-toggleable__content "><pre>passthrough</pre></div> </div></div></div></div></div><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-281" type="checkbox" ><label for="sk-estimator-id-281" class="sk-toggleable__label  sk-toggleable__label-arrow ">high_cardinality</label><div class="sk-toggleable__content "><pre>Index([&#x27;winery&#x27;, &#x27;region_1&#x27;, &#x27;variety&#x27;, &#x27;province&#x27;], dtype=&#x27;object&#x27;)</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-282" type="checkbox" ><label for="sk-estimator-id-282" class="sk-toggleable__label  sk-toggleable__label-arrow ">&nbsp;TargetEncoder<a class="sk-estimator-doc-link " rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.TargetEncoder.html">?<span>Documentation for TargetEncoder</span></a></label><div class="sk-toggleable__content "><pre>TargetEncoder(target_type=&#x27;continuous&#x27;)</pre></div> </div></div></div></div></div><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-283" type="checkbox" ><label for="sk-estimator-id-283" class="sk-toggleable__label  sk-toggleable__label-arrow ">low_cardinality</label><div class="sk-toggleable__content "><pre>Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;)</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-284" type="checkbox" ><label for="sk-estimator-id-284" class="sk-toggleable__label  sk-toggleable__label-arrow ">&nbsp;OrdinalEncoder<a class="sk-estimator-doc-link " rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.OrdinalEncoder.html">?<span>Documentation for OrdinalEncoder</span></a></label><div class="sk-toggleable__content "><pre>OrdinalEncoder(handle_unknown=&#x27;use_encoded_value&#x27;, unknown_value=-1)</pre></div> </div></div></div></div></div></div></div><div class="sk-item"><div class="sk-estimator  sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-285" type="checkbox" ><label for="sk-estimator-id-285" class="sk-toggleable__label  sk-toggleable__label-arrow ">&nbsp;HistGradientBoostingRegressor<a class="sk-estimator-doc-link " rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.ensemble.HistGradientBoostingRegressor.html">?<span>Documentation for HistGradientBoostingRegressor</span></a></label><div class="sk-toggleable__content "><pre>HistGradientBoostingRegressor(categorical_features=Index([&#x27;country&#x27;, &#x27;region_2&#x27;], dtype=&#x27;object&#x27;),
                                  max_iter=20, random_state=0)</pre></div> </div></div></div></div></div></div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 162-163

Finally, we evaluate the pipeline using cross validation and record the results:

.. GENERATED FROM PYTHON SOURCE LINES 163-165

.. code-block:: Python

    evaluate_model_and_store("mixed_target", mixed_pipe)








.. GENERATED FROM PYTHON SOURCE LINES 166-169

Plotting the Results
====================
In this section, we display the results by plotting the test and train scores:

.. GENERATED FROM PYTHON SOURCE LINES 169-201

.. code-block:: Python

    import matplotlib.pyplot as plt
    import pandas as pd

    results_df = (
        pd.DataFrame(results).set_index("preprocessor").sort_values("rmse_test_mean")
    )

    fig, (ax1, ax2) = plt.subplots(
        1, 2, figsize=(12, 8), sharey=True, constrained_layout=True
    )
    xticks = range(len(results_df))
    name_to_color = dict(
        zip((r["preprocessor"] for r in results), ["C0", "C1", "C2", "C3", "C4"])
    )

    for subset, ax in zip(["test", "train"], [ax1, ax2]):
        mean, std = f"rmse_{subset}_mean", f"rmse_{subset}_std"
        data = results_df[[mean, std]].sort_values(mean)
        ax.bar(
            x=xticks,
            height=data[mean],
            yerr=data[std],
            width=0.9,
            color=[name_to_color[name] for name in data.index],
        )
        ax.set(
            title=f"RMSE ({subset.title()})",
            xlabel="Encoding Scheme",
            xticks=xticks,
            xticklabels=data.index,
        )




.. image-sg:: /auto_examples/preprocessing/images/sphx_glr_plot_target_encoder_002.png
   :alt: RMSE (Test), RMSE (Train)
   :srcset: /auto_examples/preprocessing/images/sphx_glr_plot_target_encoder_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 202-226

When evaluating the predictive performance on the test set, dropping the
categories perform the worst and the target encoders performs the best. This
can be explained as follows:

- Dropping the categorical features makes the pipeline less expressive and
  underfitting as a result;
- Due to the high cardinality and to reduce the training time, the one-hot
  encoding scheme uses `max_categories=20` which prevents the features from
  expanding too much, which can result in underfitting.
- If we had not set `max_categories=20`, the one-hot encoding scheme would have
  likely made the pipeline overfitting as the number of features explodes with rare
  category occurrences that are correlated with the target by chance (on the training
  set only);
- The ordinal encoding imposes an arbitrary order to the features which are then
  treated as numerical values by the
  :class:`~sklearn.ensemble.HistGradientBoostingRegressor`. Since this
  model groups numerical features in 256 bins per feature, many unrelated categories
  can be grouped together and as a result overall pipeline can underfit;
- When using the target encoder, the same binning happens, but since the encoded
  values are statistically ordered by marginal association with the target variable,
  the binning use by the :class:`~sklearn.ensemble.HistGradientBoostingRegressor`
  makes sense and leads to good results: the combination of smoothed target
  encoding and binning works as a good regularizing strategy against
  overfitting while not limiting the expressiveness of the pipeline too much.


.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 32.789 seconds)


.. _sphx_glr_download_auto_examples_preprocessing_plot_target_encoder.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/scikit-learn/scikit-learn/1.4.X?urlpath=lab/tree/notebooks/auto_examples/preprocessing/plot_target_encoder.ipynb
        :alt: Launch binder
        :width: 150 px

    .. container:: lite-badge

      .. image:: images/jupyterlite_badge_logo.svg
        :target: ../../lite/lab/?path=auto_examples/preprocessing/plot_target_encoder.ipynb
        :alt: Launch JupyterLite
        :width: 150 px

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_target_encoder.ipynb <plot_target_encoder.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_target_encoder.py <plot_target_encoder.py>`


.. include:: plot_target_encoder.recommendations


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_