{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for using `process_type` with `prune` and `refresh`\n\nModifying existing trees is not a well established use for XGBoost, so feel free to\nexperiment.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from urllib.error import HTTPError\n\nimport numpy as np\nfrom sklearn.datasets import fetch_california_housing, make_regression\n\nimport xgboost as xgb\n\n\ndef main() -> None:\n    n_rounds = 32\n\n    try:\n        X, y = fetch_california_housing(return_X_y=True)\n    except HTTPError:\n        # Use a synthetic dataset instead if we couldn't\n        X, y = make_regression(n_samples=20640, n_features=8, random_state=1234)\n\n    # Train a model first\n    X_train = X[: X.shape[0] // 2]\n    y_train = y[: y.shape[0] // 2]\n    Xy = xgb.DMatrix(X_train, y_train)\n    evals_result: xgb.callback.EvaluationMonitor.EvalsLog = {}\n    booster = xgb.train(\n        {\"tree_method\": \"hist\", \"max_depth\": 6, \"device\": \"cuda\"},\n        Xy,\n        num_boost_round=n_rounds,\n        evals=[(Xy, \"Train\")],\n        evals_result=evals_result,\n    )\n    SHAP = booster.predict(Xy, pred_contribs=True)\n\n    # Refresh the leaf value and tree statistic\n    X_refresh = X[X.shape[0] // 2 :]\n    y_refresh = y[y.shape[0] // 2 :]\n    Xy_refresh = xgb.DMatrix(X_refresh, y_refresh)\n    # The model will adapt to other half of the data by changing leaf value (no change in\n    # split condition) with refresh_leaf set to True.\n    refresh_result: xgb.callback.EvaluationMonitor.EvalsLog = {}\n    refreshed = xgb.train(\n        {\"process_type\": \"update\", \"updater\": \"refresh\", \"refresh_leaf\": True},\n        Xy_refresh,\n        num_boost_round=n_rounds,\n        xgb_model=booster,\n        evals=[(Xy, \"Original\"), (Xy_refresh, \"Train\")],\n        evals_result=refresh_result,\n    )\n\n    # Refresh the model without changing the leaf value, but tree statistic including\n    # cover and weight are refreshed.\n    refresh_result = {}\n    refreshed = xgb.train(\n        {\"process_type\": \"update\", \"updater\": \"refresh\", \"refresh_leaf\": False},\n        Xy_refresh,\n        num_boost_round=n_rounds,\n        xgb_model=booster,\n        evals=[(Xy, \"Original\"), (Xy_refresh, \"Train\")],\n        evals_result=refresh_result,\n    )\n    # Without refreshing the leaf value, resulting trees should be the same with original\n    # model except for accumulated statistic.  The rtol is for floating point error in\n    # prediction.\n    np.testing.assert_allclose(\n        refresh_result[\"Original\"][\"rmse\"], evals_result[\"Train\"][\"rmse\"], rtol=1e-5\n    )\n    # But SHAP value is changed as cover in tree nodes are changed.\n    refreshed_SHAP = refreshed.predict(Xy, pred_contribs=True)\n    assert not np.allclose(SHAP, refreshed_SHAP, rtol=1e-3)\n\n    # Prune the trees with smaller max_depth\n    X_update = X_train\n    y_update = y_train\n    Xy_update = xgb.DMatrix(X_update, y_update)\n\n    prune_result: xgb.callback.EvaluationMonitor.EvalsLog = {}\n    pruned = xgb.train(\n        {\"process_type\": \"update\", \"updater\": \"prune\", \"max_depth\": 2},\n        Xy_update,\n        num_boost_round=n_rounds,\n        xgb_model=booster,\n        evals=[(Xy, \"Original\"), (Xy_update, \"Train\")],\n        evals_result=prune_result,\n    )\n    # Have a smaller model, but similar accuracy.\n    np.testing.assert_allclose(\n        np.array(prune_result[\"Original\"][\"rmse\"]),\n        np.array(prune_result[\"Train\"][\"rmse\"]),\n        atol=1e-5,\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
}