{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Feature engineering pipeline for categorical data\n\nThe script showcases how to keep the categorical data encoding consistent across\ntraining and inference. There are many ways to attain the same goal, this script can be\nused as a starting point.\n\n.. versionchanged:: 3.1\n\n    Start with 3.1, users don't need this for most of the cases. See `cat-recode`\n    for more info.\n\n## See Also\n- :doc:`Tutorial </tutorials/categorical>`\n- `sphx_glr_python_examples_categorical.py`\n- `sphx_glr_python_examples_cat_in_the_dat.py`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from typing import List, Tuple\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.compose import make_column_selector, make_column_transformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import OrdinalEncoder\n\nimport xgboost as xgb\n\n\ndef make_example_data() -> Tuple[pd.DataFrame, pd.Series, List[str]]:\n    \"\"\"Generate data for demo.\"\"\"\n    n_samples = 2048\n    rng = np.random.default_rng(1994)\n\n    # We have three categorical features, while the rest are numerical.\n    categorical_features = [\"brand_id\", \"retailer_id\", \"category_id\"]\n\n    df = pd.DataFrame(\n        np.random.randint(32, 96, size=(n_samples, 3)),\n        columns=categorical_features,\n    )\n\n    df[\"price\"] = rng.integers(100, 200, size=(n_samples,))\n    df[\"stock_status\"] = rng.choice([True, False], n_samples)\n    df[\"on_sale\"] = rng.choice([True, False], n_samples)\n    df[\"label\"] = rng.normal(loc=0.0, scale=1.0, size=n_samples)\n\n    X = df.drop([\"label\"], axis=1)\n    y = df[\"label\"]\n\n    return X, y, categorical_features\n\n\ndef native() -> None:\n    \"\"\"Using the native XGBoost interface.\"\"\"\n    X, y, cat_feats = make_example_data()\n\n    X_train, X_test, y_train, y_test = train_test_split(\n        X, y, random_state=1994, test_size=0.2\n    )\n\n    # Create an encoder based on training data.\n    enc = OrdinalEncoder(handle_unknown=\"use_encoded_value\", unknown_value=np.nan)\n    enc.set_output(transform=\"pandas\")\n    enc = enc.fit(X_train[cat_feats])\n\n    def enc_transform(X: pd.DataFrame) -> pd.DataFrame:\n        # don't make change inplace so that we can have demonstrations for encoding\n        X = X.copy()\n        cat_cols = enc.transform(X[cat_feats])\n        for i, name in enumerate(cat_feats):\n            # create pd.Series based on the encoder\n            cat_cols[name] = pd.Categorical.from_codes(\n                codes=cat_cols[name].astype(np.int32), categories=enc.categories_[i]\n            )\n        X[cat_feats] = cat_cols\n        return X\n\n    # Encode the data based on fitted encoder.\n    X_train_enc = enc_transform(X_train)\n    X_test_enc = enc_transform(X_test)\n    # Train XGBoost model using the native interface.\n    Xy_train = xgb.QuantileDMatrix(X_train_enc, y_train, enable_categorical=True)\n    Xy_test = xgb.QuantileDMatrix(\n        X_test_enc, y_test, enable_categorical=True, ref=Xy_train\n    )\n    booster = xgb.train({}, Xy_train)\n    booster.predict(Xy_test)\n\n    # Following shows that data are encoded consistently.\n\n    # We first obtain result from newly encoded data\n    predt0 = booster.inplace_predict(enc_transform(X_train.head(16)))\n    # then we obtain result from already encoded data from training.\n    predt1 = booster.inplace_predict(X_train_enc.head(16))\n\n    np.testing.assert_allclose(predt0, predt1)\n\n\ndef pipeline() -> None:\n    \"\"\"Using the sklearn pipeline.\"\"\"\n    X, y, cat_feats = make_example_data()\n\n    X_train, X_test, y_train, y_test = train_test_split(\n        X, y, random_state=3, test_size=0.2\n    )\n\n    enc = make_column_transformer(\n        (\n            OrdinalEncoder(handle_unknown=\"use_encoded_value\", unknown_value=np.nan),\n            # all categorical feature names end with \"_id\"\n            make_column_selector(pattern=\".*_id\"),\n        ),\n        remainder=\"passthrough\",\n        verbose_feature_names_out=False,\n    )\n    # No need to set pandas output, we use `feature_types` to indicate the type of\n    # features.\n\n    # enc.set_output(transform=\"pandas\")\n\n    feature_types = [\"c\" if fn in cat_feats else \"q\" for fn in X_train.columns]\n    reg = xgb.XGBRegressor(\n        feature_types=feature_types, enable_categorical=True, n_estimators=10\n    )\n    p = make_pipeline(enc, reg)\n    p.fit(X_train, y_train)\n    # check XGBoost is using the feature type correctly.\n    model_types = reg.get_booster().feature_types\n    assert model_types is not None\n    for a, b in zip(model_types, feature_types):\n        assert a == b\n\n    # Following shows that data are encoded consistently.\n\n    # We first create a slice of data that doesn't contain all the categories\n    predt0 = p.predict(X_train.iloc[:16, :])\n    # Then we use the dataframe that contains all the categories\n    predt1 = p.predict(X_train)[:16]\n\n    # The resulting encoding is the same\n    np.testing.assert_allclose(predt0, predt1)\n\n\nif __name__ == \"__main__\":\n    pipeline()\n    native()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.17"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}