{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Example of using callbacks with Dask\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from typing import Any\n\nimport numpy as np\nfrom dask.distributed import Client, LocalCluster\nfrom dask_ml.datasets import make_regression\nfrom dask_ml.model_selection import train_test_split\n\nimport xgboost as xgb\nimport xgboost.dask as dxgb\nfrom xgboost.dask import DaskDMatrix\n\n\ndef probability_for_going_backward(epoch: int) -> float:\n    return 0.999 / (1.0 + 0.05 * np.log(1.0 + epoch))\n\n\n# All callback functions must inherit from TrainingCallback\nclass CustomEarlyStopping(xgb.callback.TrainingCallback):\n    \"\"\"A custom early stopping class where early stopping is determined stochastically.\n    In the beginning, allow the metric to become worse with a probability of 0.999.\n    As boosting progresses, the probability should be adjusted downward\"\"\"\n\n    def __init__(\n        self, *, validation_set: str, target_metric: str, maximize: bool, seed: int\n    ) -> None:\n        self.validation_set = validation_set\n        self.target_metric = target_metric\n        self.maximize = maximize\n        self.seed = seed\n        self.rng = np.random.default_rng(seed=seed)\n        if maximize:\n            self.better = lambda x, y: x > y\n        else:\n            self.better = lambda x, y: x < y\n\n    def after_iteration(\n        self, model: Any, epoch: int, evals_log: xgb.callback.TrainingCallback.EvalsLog\n    ) -> bool:\n        metric_history = evals_log[self.validation_set][self.target_metric]\n        if len(metric_history) < 2 or self.better(\n            metric_history[-1], metric_history[-2]\n        ):\n            return False  # continue training\n        p = probability_for_going_backward(epoch)\n        go_backward = self.rng.choice(2, size=(1,), replace=True, p=[1 - p, p]).astype(\n            np.bool_\n        )[0]\n        print(\n            \"The validation metric went into the wrong direction. \"\n            + f\"Stopping training with probability {1 - p}...\"\n        )\n        if go_backward:\n            return False  # continue training\n        else:\n            return True  # stop training\n\n\ndef main(client: Client) -> None:\n    m = 100000\n    n = 100\n    X, y = make_regression(n_samples=m, n_features=n, chunks=200, random_state=0)\n    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n    dtrain = DaskDMatrix(client, X_train, y_train)\n    dtest = DaskDMatrix(client, X_test, y_test)\n\n    output = dxgb.train(\n        client,\n        {\n            \"verbosity\": 1,\n            \"tree_method\": \"hist\",\n            \"objective\": \"reg:squarederror\",\n            \"eval_metric\": \"rmse\",\n            \"max_depth\": 6,\n            \"learning_rate\": 1.0,\n        },\n        dtrain,\n        num_boost_round=1000,\n        evals=[(dtrain, \"train\"), (dtest, \"test\")],\n        callbacks=[\n            CustomEarlyStopping(\n                validation_set=\"test\", target_metric=\"rmse\", maximize=False, seed=0\n            )\n        ],\n    )\n\n\nif __name__ == \"__main__\":\n    # or use other clusters for scaling\n    with LocalCluster(n_workers=4, threads_per_worker=1) as cluster:\n        with Client(cluster) as client:\n            main(client)"
      ]
    }
  ],
  "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
}