{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for training continuation\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nimport pickle\nimport tempfile\n\nfrom sklearn.datasets import load_breast_cancer\n\nimport xgboost\n\n\ndef training_continuation(tmpdir: str, use_pickle: bool) -> None:\n    \"\"\"Basic training continuation.\"\"\"\n    # Train 128 iterations in 1 session\n    X, y = load_breast_cancer(return_X_y=True)\n    clf = xgboost.XGBClassifier(n_estimators=128, eval_metric=\"logloss\")\n    clf.fit(X, y, eval_set=[(X, y)])\n    print(\"Total boosted rounds:\", clf.get_booster().num_boosted_rounds())\n\n    # Train 128 iterations in 2 sessions, with the first one runs for 32 iterations and\n    # the second one runs for 96 iterations\n    clf = xgboost.XGBClassifier(n_estimators=32, eval_metric=\"logloss\")\n    clf.fit(X, y, eval_set=[(X, y)])\n    assert clf.get_booster().num_boosted_rounds() == 32\n\n    # load back the model, this could be a checkpoint\n    if use_pickle:\n        path = os.path.join(tmpdir, \"model-first-32.pkl\")\n        with open(path, \"wb\") as fd:\n            pickle.dump(clf, fd)\n        with open(path, \"rb\") as fd:\n            loaded = pickle.load(fd)\n    else:\n        path = os.path.join(tmpdir, \"model-first-32.json\")\n        clf.save_model(path)\n        loaded = xgboost.XGBClassifier()\n        loaded.load_model(path)\n\n    clf = xgboost.XGBClassifier(n_estimators=128 - 32, eval_metric=\"logloss\")\n    clf.fit(X, y, eval_set=[(X, y)], xgb_model=loaded)\n\n    print(\"Total boosted rounds:\", clf.get_booster().num_boosted_rounds())\n\n    assert clf.get_booster().num_boosted_rounds() == 128\n\n\ndef training_continuation_early_stop(tmpdir: str, use_pickle: bool) -> None:\n    \"\"\"Training continuation with early stopping.\"\"\"\n    early_stopping_rounds = 5\n    early_stop = xgboost.callback.EarlyStopping(\n        rounds=early_stopping_rounds, save_best=True\n    )\n    n_estimators = 512\n\n    X, y = load_breast_cancer(return_X_y=True)\n    clf = xgboost.XGBClassifier(\n        n_estimators=n_estimators, eval_metric=\"logloss\", callbacks=[early_stop]\n    )\n    clf.fit(X, y, eval_set=[(X, y)])\n    print(\"Total boosted rounds:\", clf.get_booster().num_boosted_rounds())\n    best = clf.best_iteration\n\n    # Train 512 iterations in 2 sessions, with the first one runs for 128 iterations and\n    # the second one runs until early stop.\n    clf = xgboost.XGBClassifier(\n        n_estimators=128, eval_metric=\"logloss\", callbacks=[early_stop]\n    )\n    # Reinitialize the early stop callback\n    early_stop = xgboost.callback.EarlyStopping(\n        rounds=early_stopping_rounds, save_best=True\n    )\n    clf.set_params(callbacks=[early_stop])\n    clf.fit(X, y, eval_set=[(X, y)])\n    assert clf.get_booster().num_boosted_rounds() == 128\n\n    # load back the model, this could be a checkpoint\n    if use_pickle:\n        path = os.path.join(tmpdir, \"model-first-128.pkl\")\n        with open(path, \"wb\") as fd:\n            pickle.dump(clf, fd)\n        with open(path, \"rb\") as fd:\n            loaded = pickle.load(fd)\n    else:\n        path = os.path.join(tmpdir, \"model-first-128.json\")\n        clf.save_model(path)\n        loaded = xgboost.XGBClassifier()\n        loaded.load_model(path)\n\n    early_stop = xgboost.callback.EarlyStopping(\n        rounds=early_stopping_rounds, save_best=True\n    )\n    clf = xgboost.XGBClassifier(\n        n_estimators=n_estimators - 128, eval_metric=\"logloss\", callbacks=[early_stop]\n    )\n    clf.fit(\n        X,\n        y,\n        eval_set=[(X, y)],\n        xgb_model=loaded,\n    )\n\n    print(\"Total boosted rounds:\", clf.get_booster().num_boosted_rounds())\n    assert clf.best_iteration == best\n\n\nif __name__ == \"__main__\":\n    with tempfile.TemporaryDirectory() as tmpdir:\n        training_continuation_early_stop(tmpdir, False)\n        training_continuation_early_stop(tmpdir, True)\n\n        training_continuation(tmpdir, True)\n        training_continuation(tmpdir, False)"
      ]
    }
  ],
  "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
}