{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Quantile Regression\n\n    .. versionadded:: 2.0.0\n\nThe script is inspired by this awesome example in sklearn:\nhttps://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>The feature is only supported using the Python, R, and C packages. In addition, quantile\n    crossing can happen due to limitation in the algorithm.</p></div>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import argparse\nfrom typing import Dict\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nimport xgboost as xgb\n\n\ndef f(x: np.ndarray) -> np.ndarray:\n    \"\"\"The function to predict.\"\"\"\n    return x * np.sin(x)\n\n\ndef quantile_loss(args: argparse.Namespace) -> None:\n    \"\"\"Train a quantile regression model.\"\"\"\n    rng = np.random.RandomState(1994)\n    # Generate a synthetic dataset for demo, the generate process is from the sklearn\n    # example.\n    X = np.atleast_2d(rng.uniform(0, 10.0, size=1000)).T\n    expected_y = f(X).ravel()\n\n    sigma = 0.5 + X.ravel() / 10.0\n    noise = rng.lognormal(sigma=sigma) - np.exp(sigma**2.0 / 2.0)\n    y = expected_y + noise\n\n    # Train on 0.05 and 0.95 quantiles. The model is similar to multi-class and\n    # multi-target models.\n    alpha = np.array([0.05, 0.5, 0.95])\n    evals_result: Dict[str, Dict] = {}\n\n    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=rng)\n    # We will be using the `hist` tree method, quantile DMatrix can be used to preserve\n    # memory (which has nothing to do with quantile regression itself, see its document\n    # for details).\n    # Do not use the `exact` tree method for quantile regression, otherwise the\n    # performance might drop.\n    Xy = xgb.QuantileDMatrix(X_train, y_train)\n    # use Xy as a reference\n    Xy_test = xgb.QuantileDMatrix(X_test, y_test, ref=Xy)\n\n    booster = xgb.train(\n        {\n            # Use the quantile objective function.\n            \"objective\": \"reg:quantileerror\",\n            \"tree_method\": \"hist\",\n            \"quantile_alpha\": alpha,\n            # Let's try not to overfit.\n            \"learning_rate\": 0.04,\n            \"max_depth\": 5,\n            \"multi_strategy\": args.multi_strategy,\n            \"device\": args.device,\n        },\n        Xy,\n        num_boost_round=32,\n        early_stopping_rounds=2,\n        # The evaluation result is a weighted average across multiple quantiles.\n        evals=[(Xy, \"Train\"), (Xy_test, \"Test\")],\n        evals_result=evals_result,\n    )\n    xx = np.atleast_2d(np.linspace(0, 10, 1000)).T\n    scores = booster.inplace_predict(xx)\n    # dim 1 is the quantiles\n    assert scores.shape[0] == xx.shape[0]\n    assert scores.shape[1] == alpha.shape[0]\n\n    y_lower = scores[:, 0]  # alpha=0.05\n    y_med = scores[:, 1]  # alpha=0.5, median\n    y_upper = scores[:, 2]  # alpha=0.95\n\n    # Train a mse model for comparison\n    booster = xgb.train(\n        {\n            \"objective\": \"reg:squarederror\",\n            \"tree_method\": \"hist\",\n            # Let's try not to overfit.\n            \"learning_rate\": 0.04,\n            \"max_depth\": 5,\n        },\n        Xy,\n        num_boost_round=32,\n        early_stopping_rounds=2,\n        evals=[(Xy, \"Train\"), (Xy_test, \"Test\")],\n        evals_result=evals_result,\n    )\n    xx = np.atleast_2d(np.linspace(0, 10, 1000)).T\n    y_pred = booster.inplace_predict(xx)\n\n    if args.plot:\n        from matplotlib import pyplot as plt\n\n        fig = plt.figure(figsize=(10, 10))\n        plt.plot(xx, f(xx), \"g:\", linewidth=3, label=r\"$f(x) = x\\,\\sin(x)$\")\n        plt.plot(X_test, y_test, \"b.\", markersize=10, label=\"Test observations\")\n        plt.plot(xx, y_med, \"r-\", label=\"Predicted median\")\n        plt.plot(xx, y_pred, \"m-\", label=\"Predicted mean\")\n        plt.plot(xx, y_upper, \"k-\")\n        plt.plot(xx, y_lower, \"k-\")\n        plt.fill_between(\n            xx.ravel(), y_lower, y_upper, alpha=0.4, label=\"Predicted 90% interval\"\n        )\n        plt.xlabel(\"$x$\")\n        plt.ylabel(\"$f(x)$\")\n        plt.ylim(-10, 25)\n        plt.legend(loc=\"upper left\")\n        plt.show()\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--plot\",\n        action=\"store_true\",\n        help=\"Specify it to enable plotting the outputs.\",\n    )\n    parser.add_argument(\n        \"--multi_strategy\",\n        choices=[\"multi_output_tree\", \"one_output_per_tree\"],\n        default=\"one_output_per_tree\",\n        help=\"See the parameter `multi_strategy` for more info. (Experimental)\",\n    )\n    parser.add_argument(\"--device\", choices=[\"cpu\", \"cuda\"], default=\"cpu\")\n    args = parser.parse_args()\n    quantile_loss(args)"
      ]
    }
  ],
  "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
}