{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for prediction using individual trees and model slices\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\n\nimport numpy as np\nfrom scipy.special import logit\nfrom sklearn.datasets import load_svmlight_file\n\nimport xgboost as xgb\n\nCURRENT_DIR = os.path.dirname(__file__)\ntrain = os.path.join(CURRENT_DIR, \"../data/agaricus.txt.train\")\ntest = os.path.join(CURRENT_DIR, \"../data/agaricus.txt.test\")\n\n\ndef individual_tree() -> None:\n    \"\"\"Get prediction from each individual tree and combine them together.\"\"\"\n    X_train, y_train = load_svmlight_file(train)\n    X_test, y_test = load_svmlight_file(test)\n    Xy_train = xgb.QuantileDMatrix(X_train, y_train)\n\n    n_rounds = 4\n    # Specify the base score, otherwise xgboost will estimate one from the training\n    # data.\n    base_score = 0.5\n    params = {\n        \"max_depth\": 2,\n        \"eta\": 1,\n        \"objective\": \"reg:logistic\",\n        \"tree_method\": \"hist\",\n        \"base_score\": base_score,\n    }\n    booster = xgb.train(params, Xy_train, num_boost_round=n_rounds)\n\n    # Use logit to inverse the base score back to raw leaf value (margin)\n    scores = np.full((X_test.shape[0],), logit(base_score))\n    for i in range(n_rounds):\n        # - Use output_margin to get raw leaf values\n        # - Use iteration_range to get prediction for only one tree\n        # - Use previous prediction as base marign for the model\n        Xy_test = xgb.DMatrix(X_test, base_margin=scores)\n\n        if i == n_rounds - 1:\n            # last round, get the transformed prediction\n            scores = booster.predict(\n                Xy_test, iteration_range=(i, i + 1), output_margin=False\n            )\n        else:\n            # get raw leaf value for accumulation\n            scores = booster.predict(\n                Xy_test, iteration_range=(i, i + 1), output_margin=True\n            )\n\n    full = booster.predict(xgb.DMatrix(X_test), output_margin=False)\n    np.testing.assert_allclose(scores, full)\n\n\ndef model_slices() -> None:\n    \"\"\"Inference with each individual tree using model slices.\"\"\"\n    X_train, y_train = load_svmlight_file(train)\n    X_test, y_test = load_svmlight_file(test)\n    Xy_train = xgb.QuantileDMatrix(X_train, y_train)\n\n    n_rounds = 4\n    # Specify the base score, otherwise xgboost will estimate one from the training\n    # data.\n    base_score = 0.5\n    params = {\n        \"max_depth\": 2,\n        \"eta\": 1,\n        \"objective\": \"reg:logistic\",\n        \"tree_method\": \"hist\",\n        \"base_score\": base_score,\n    }\n    booster = xgb.train(params, Xy_train, num_boost_round=n_rounds)\n    trees = [booster[t] for t in range(n_rounds)]\n\n    # Use logit to inverse the base score back to raw leaf value (margin)\n    scores = np.full((X_test.shape[0],), logit(base_score))\n    for i, t in enumerate(trees):\n        # Feed previous scores into base margin.\n        Xy_test = xgb.DMatrix(X_test, base_margin=scores)\n\n        if i == n_rounds - 1:\n            # last round, get the transformed prediction\n            scores = t.predict(Xy_test, output_margin=False)\n        else:\n            # get raw leaf value for accumulation\n            scores = t.predict(Xy_test, output_margin=True)\n\n    full = booster.predict(xgb.DMatrix(X_test), output_margin=False)\n    np.testing.assert_allclose(scores, full)\n\n\nif __name__ == \"__main__\":\n    individual_tree()\n    model_slices()"
      ]
    }
  ],
  "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
}