{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Getting started with categorical data\n\nExperimental support for categorical data.\n\nIn before, users need to run an encoder themselves before passing the data into XGBoost,\nwhich creates a sparse matrix and potentially increase memory usage.  This demo\nshowcases the experimental categorical data support, more advanced features are planned.\n\n  .. versionadded:: 1.5.0\n\n## See Also\n- :doc:`Tutorial </tutorials/categorical>`\n- `sphx_glr_python_examples_cat_in_the_dat.py`\n- `sphx_glr_python_examples_cat_pipeline.py`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from typing import Tuple\n\nimport numpy as np\nimport pandas as pd\n\nimport xgboost as xgb\n\n\ndef make_categorical(\n    n_samples: int, n_features: int, n_categories: int, onehot: bool\n) -> Tuple[pd.DataFrame, pd.Series]:\n    \"\"\"Make some random data for demo.\"\"\"\n    rng = np.random.RandomState(1994)\n\n    pd_dict = {}\n    for i in range(n_features + 1):\n        c = rng.randint(low=0, high=n_categories, size=n_samples)\n        pd_dict[str(i)] = pd.Series(c, dtype=np.int64)\n\n    df = pd.DataFrame(pd_dict)\n    label = df.iloc[:, 0]\n    df = df.iloc[:, 1:]\n    for i in range(0, n_features):\n        label += df.iloc[:, i]\n    label += 1\n\n    df = df.astype(\"category\")\n    categories = np.arange(0, n_categories)\n    for col in df.columns:\n        df[col] = df[col].cat.set_categories(categories)\n\n    if onehot:\n        return pd.get_dummies(df), label\n    return df, label\n\n\ndef main() -> None:\n    # Use builtin categorical data support\n\n    # For scikit-learn interface, the input data should be pandas DataFrame or cudf\n    # DataFrame with categorical features. If an numpy/cupy array is used instead, the\n    # `feature_types` for `XGBRegressor` should be set accordingly.\n    X, y = make_categorical(100, 10, 4, False)\n    # Specify `enable_categorical` to True, also we use onehot-encoding-based split here\n    # for demonstration. For details see the document of `max_cat_to_onehot`.\n    reg = xgb.XGBRegressor(\n        tree_method=\"hist\", enable_categorical=True, max_cat_to_onehot=5, device=\"cuda\"\n    )\n    reg.fit(X, y, eval_set=[(X, y)])\n\n    # Pass in already encoded data\n    X_enc, y_enc = make_categorical(100, 10, 4, True)\n    reg_enc = xgb.XGBRegressor(tree_method=\"hist\", device=\"cuda\")\n    reg_enc.fit(X_enc, y_enc, eval_set=[(X_enc, y_enc)])\n\n    reg_results = np.array(reg.evals_result()[\"validation_0\"][\"rmse\"])\n    reg_enc_results = np.array(reg_enc.evals_result()[\"validation_0\"][\"rmse\"])\n\n    # Check that they have same results\n    np.testing.assert_allclose(reg_results, reg_enc_results)\n\n    # Convert to DMatrix for SHAP value\n    booster: xgb.Booster = reg.get_booster()\n    m = xgb.DMatrix(X, enable_categorical=True)  # specify categorical data support.\n    SHAP = booster.predict(m, pred_contribs=True)\n    margin = booster.predict(m, output_margin=True)\n    np.testing.assert_allclose(\n        np.sum(SHAP, axis=len(SHAP.shape) - 1), margin, rtol=1e-3\n    )\n\n\nif __name__ == \"__main__\":\n    main()"
      ]
    }
  ],
  "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
}