{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for using cross validation\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nfrom typing import Any, Dict, Tuple\n\nimport numpy as np\n\nimport xgboost as xgb\n\n# load data in do training\nCURRENT_DIR = os.path.dirname(__file__)\ndtrain = xgb.DMatrix(\n    os.path.join(CURRENT_DIR, \"../data/agaricus.txt.train?format=libsvm\")\n)\nparam = {\"max_depth\": 2, \"eta\": 1, \"objective\": \"binary:logistic\"}\nnum_round = 2\n\nprint(\"running cross validation\")\n# do cross validation, this will print result out as\n# [iteration]  metric_name:mean_value+std_value\n# std_value is standard deviation of the metric\nxgb.cv(\n    param,\n    dtrain,\n    num_round,\n    nfold=5,\n    metrics={\"error\"},\n    seed=0,\n    callbacks=[xgb.callback.EvaluationMonitor(show_stdv=True)],\n)\n\nprint(\"running cross validation, disable standard deviation display\")\n# do cross validation, this will print result out as\n# [iteration]  metric_name:mean_value\nres = xgb.cv(\n    param,\n    dtrain,\n    num_boost_round=10,\n    nfold=5,\n    metrics={\"error\"},\n    seed=0,\n    callbacks=[\n        xgb.callback.EvaluationMonitor(show_stdv=False),\n        xgb.callback.EarlyStopping(3),\n    ],\n)\nprint(res)\nprint(\"running cross validation, with preprocessing function\")\n\n\n# define the preprocessing function\n# used to return the preprocessed training, test data, and parameter\n# we can use this to do weight rescale, etc.\n# as a example, we try to set scale_pos_weight\ndef fpreproc(\n    dtrain: xgb.DMatrix, dtest: xgb.DMatrix, param: Any\n) -> Tuple[xgb.DMatrix, xgb.DMatrix, Dict[str, Any]]:\n    label = dtrain.get_label()\n    ratio = float(np.sum(label == 0)) / np.sum(label == 1)\n    param[\"scale_pos_weight\"] = ratio\n    return (dtrain, dtest, param)\n\n\n# do cross validation, for each fold\n# the dtrain, dtest, param will be passed into fpreproc\n# then the return value of fpreproc will be used to generate\n# results of that fold\nxgb.cv(param, dtrain, num_round, nfold=5, metrics={\"auc\"}, seed=0, fpreproc=fpreproc)\n\n###\n# you can also do cross validation with customized loss function\n# See custom_objective.py\n##\nprint(\"running cross validation, with customized loss function\")\n\n\ndef logregobj(preds: np.ndarray, dtrain: xgb.DMatrix) -> Tuple[np.ndarray, np.ndarray]:\n    labels = dtrain.get_label()\n    preds = 1.0 / (1.0 + np.exp(-preds))\n    grad = preds - labels\n    hess = preds * (1.0 - preds)\n    return grad, hess\n\n\ndef evalerror(preds: np.ndarray, dtrain: xgb.DMatrix) -> Tuple[str, float]:\n    labels = dtrain.get_label()\n    preds = 1.0 / (1.0 + np.exp(-preds))\n    return \"error\", float(sum(labels != (preds > 0.0))) / len(labels)\n\n\nparam = {\"max_depth\": 2, \"eta\": 1}\n# train with customized objective\nxgb.cv(\n    param, dtrain, num_round, nfold=5, seed=0, obj=logregobj, custom_metric=evalerror\n)"
      ]
    }
  ],
  "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
}