{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Visual demo for survival analysis (regression) with Accelerated Failure Time (AFT) model.\n\nThis demo uses 1D toy data and visualizes how XGBoost fits a tree ensemble. The ensemble\nmodel starts out as a flat line and evolves into a step function in order to account for\nall ranged labels.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport xgboost as xgb\n\nplt.rcParams.update({\"font.size\": 13})\n\n\n# Function to visualize censored labels\ndef plot_censored_labels(\n    X: np.ndarray, y_lower: np.ndarray, y_upper: np.ndarray\n) -> None:\n    def replace_inf(x: np.ndarray, target_value: float) -> np.ndarray:\n        x[np.isinf(x)] = target_value\n        return x\n\n    plt.plot(X, y_lower, \"o\", label=\"y_lower\", color=\"blue\")\n    plt.plot(X, y_upper, \"o\", label=\"y_upper\", color=\"fuchsia\")\n    plt.vlines(\n        X,\n        ymin=replace_inf(y_lower, 0.01),\n        ymax=replace_inf(y_upper, 1000.0),\n        label=\"Range for y\",\n        color=\"gray\",\n    )\n\n\n# Toy data\nX = np.array([1, 2, 3, 4, 5]).reshape((-1, 1))\nINF = np.inf\ny_lower = np.array([10, 15, -INF, 30, 100])\ny_upper = np.array([INF, INF, 20, 50, INF])\n\n# Visualize toy data\nplt.figure(figsize=(5, 4))\nplot_censored_labels(X, y_lower, y_upper)\nplt.ylim((6, 200))\nplt.legend(loc=\"lower right\")\nplt.title(\"Toy data\")\nplt.xlabel(\"Input feature\")\nplt.ylabel(\"Label\")\nplt.yscale(\"log\")\nplt.tight_layout()\nplt.show(block=True)\n\n# Will be used to visualize XGBoost model\ngrid_pts = np.linspace(0.8, 5.2, 1000).reshape((-1, 1))\n\n# Train AFT model using XGBoost\ndmat = xgb.DMatrix(X)\ndmat.set_float_info(\"label_lower_bound\", y_lower)\ndmat.set_float_info(\"label_upper_bound\", y_upper)\nparams = {\"max_depth\": 3, \"objective\": \"survival:aft\", \"min_child_weight\": 0}\n\naccuracy_history = []\n\n\nclass PlotIntermediateModel(xgb.callback.TrainingCallback):\n    \"\"\"Custom callback to plot intermediate models.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n\n    def after_iteration(\n        self,\n        model: xgb.Booster,\n        epoch: int,\n        evals_log: xgb.callback.TrainingCallback.EvalsLog,\n    ) -> bool:\n        \"\"\"Run after training is finished.\"\"\"\n        # Compute y_pred = prediction using the intermediate model, at current boosting\n        # iteration\n        y_pred = model.predict(dmat)\n        # \"Accuracy\" = the number of data points whose ranged label (y_lower, y_upper)\n        #              includes the corresponding predicted label (y_pred)\n        acc = np.sum(\n            np.logical_and(y_pred >= y_lower, y_pred <= y_upper) / len(X) * 100\n        )\n        accuracy_history.append(acc)\n\n        # Plot ranged labels as well as predictions by the model\n        plt.subplot(5, 3, epoch + 1)\n        plot_censored_labels(X, y_lower, y_upper)\n        y_pred_grid_pts = model.predict(xgb.DMatrix(grid_pts))\n        plt.plot(\n            grid_pts, y_pred_grid_pts, \"r-\", label=\"XGBoost AFT model\", linewidth=4\n        )\n        plt.title(\"Iteration {}\".format(epoch), x=0.5, y=0.8)\n        plt.xlim((0.8, 5.2))\n        plt.ylim((1 if np.min(y_pred) < 6 else 6, 200))\n        plt.yscale(\"log\")\n        return False\n\n\nres: xgb.callback.TrainingCallback.EvalsLog = {}\nplt.figure(figsize=(12, 13))\nbst = xgb.train(\n    params,\n    dmat,\n    num_boost_round=15,\n    evals=[(dmat, \"train\")],\n    evals_result=res,\n    callbacks=[PlotIntermediateModel()],\n)\nplt.tight_layout()\nplt.legend(\n    loc=\"lower center\",\n    ncol=4,\n    bbox_to_anchor=(0.5, 0),\n    bbox_transform=plt.gcf().transFigure,\n)\nplt.tight_layout()\n\n# Plot negative log likelihood over boosting iterations\nplt.figure(figsize=(8, 3))\nplt.subplot(1, 2, 1)\nplt.plot(res[\"train\"][\"aft-nloglik\"], \"b-o\", label=\"aft-nloglik\")\nplt.xlabel(\"# Boosting Iterations\")\nplt.legend(loc=\"best\")\n\n# Plot \"accuracy\" over boosting iterations\n# \"Accuracy\" = the number of data points whose ranged label (y_lower, y_upper) includes\n#              the corresponding predicted label (y_pred)\nplt.subplot(1, 2, 2)\nplt.plot(accuracy_history, \"r-o\", label=\"Accuracy (%)\")\nplt.xlabel(\"# Boosting Iterations\")\nplt.legend(loc=\"best\")\nplt.tight_layout()\n\nplt.show()"
      ]
    }
  ],
  "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
}