{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for creating customized multi-class objective function\n\nThis demo is only applicable after (excluding) XGBoost 1.0.0, as before this version\nXGBoost returns transformed prediction for multi-class objective function.  More details\nin comments.\n\nSee :doc:`/tutorials/custom_metric_obj` and :doc:`/tutorials/advanced_custom_obj` for\ndetailed tutorial and notes.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import argparse\nfrom typing import Dict, Tuple\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimport xgboost as xgb\n\nnp.random.seed(1994)\n\nkRows = 100\nkCols = 10\nkClasses = 4  # number of classes\n\nkRounds = 10  # number of boosting rounds.\n\n# Generate some random data for demo.\nX = np.random.randn(kRows, kCols)\ny = np.random.randint(0, 4, size=kRows)\n\nm = xgb.DMatrix(X, y)\n\n\ndef softmax(x: np.ndarray) -> np.ndarray:\n    \"\"\"Softmax function with x as input vector.\"\"\"\n    e = np.exp(x)\n    return e / np.sum(e)\n\n\ndef softprob_obj(predt: np.ndarray, data: xgb.DMatrix) -> Tuple[np.ndarray, np.ndarray]:\n    \"\"\"Loss function. Computing the gradient and upper bound on the\n    Hessian with a diagonal structure for XGBoost (note that this is\n    not the true Hessian).\n    Reimplements the `multi:softprob` inside XGBoost.\n\n    \"\"\"\n    labels = data.get_label()\n    if data.get_weight().size == 0:\n        # Use 1 as weight if we don't have custom weight.\n        weights = np.ones((kRows, 1), dtype=float)\n    else:\n        weights = data.get_weight()\n\n    # The prediction is of shape (rows, classes), each element in a row\n    # represents a raw prediction (leaf weight, hasn't gone through softmax\n    # yet).  In XGBoost 1.0.0, the prediction is transformed by a softmax\n    # function, fixed in later versions.\n    assert predt.shape == (kRows, kClasses)\n\n    grad = np.zeros((kRows, kClasses), dtype=float)\n    hess = np.zeros((kRows, kClasses), dtype=float)\n\n    eps = 1e-6\n\n    # compute the gradient and hessian upper bound, slow iterations in Python, only\n    # suitable for demo.  Also the one in native XGBoost core is more robust to\n    # numeric overflow as we don't do anything to mitigate the `exp` in\n    # `softmax` here.\n    for r in range(predt.shape[0]):\n        target = labels[r]\n        p = softmax(predt[r, :])\n        for c in range(predt.shape[1]):\n            assert target >= 0 or target <= kClasses\n            g = p[c] - 1.0 if c == target else p[c]\n            g = g * weights[r]\n            h = max((2.0 * p[c] * (1.0 - p[c]) * weights[r]).item(), eps)\n            grad[r, c] = g\n            hess[r, c] = h\n\n    # After 2.1.0, pass the gradient as it is.\n    return grad, hess\n\n\ndef predict(booster: xgb.Booster, X: xgb.DMatrix) -> np.ndarray:\n    \"\"\"A customized prediction function that converts raw prediction to\n    target class.\n\n    \"\"\"\n    # Output margin means we want to obtain the raw prediction obtained from\n    # tree leaf weight.\n    predt = booster.predict(X, output_margin=True)\n    out = np.zeros(kRows)\n    for r in range(predt.shape[0]):\n        # the class with maximum prob (not strictly prob as it haven't gone\n        # through softmax yet so it doesn't sum to 1, but result is the same\n        # for argmax).\n        i = np.argmax(predt[r])\n        out[r] = i\n    return out\n\n\ndef merror(predt: np.ndarray, dtrain: xgb.DMatrix) -> Tuple[str, np.float64]:\n    y = dtrain.get_label()\n    # Like custom objective, the predt is untransformed leaf weight when custom\n    # objective is provided.\n\n    # With the use of `custom_metric` parameter in train function, custom metric\n    # receives raw input only when custom objective is also being used.  Otherwise\n    # custom metric will receive transformed prediction.\n    assert predt.shape == (kRows, kClasses)\n    out = np.zeros(kRows)\n    for r in range(predt.shape[0]):\n        i = np.argmax(predt[r])\n        out[r] = i\n\n    assert y.shape == out.shape\n\n    errors = np.zeros(kRows)\n    errors[y != out] = 1.0\n    return \"PyMError\", np.sum(errors) / kRows\n\n\ndef plot_history(\n    custom_results: Dict[str, Dict], native_results: Dict[str, Dict]\n) -> None:\n    axs: np.ndarray\n    fig, axs = plt.subplots(2, 1)  # type: ignore\n    ax0 = axs[0]\n    ax1 = axs[1]\n\n    pymerror = custom_results[\"train\"][\"PyMError\"]\n    merror = native_results[\"train\"][\"merror\"]\n\n    x = np.arange(0, kRounds, 1)\n    ax0.plot(x, pymerror, label=\"Custom objective\")\n    ax0.legend()\n    ax1.plot(x, merror, label=\"multi:softmax\")\n    ax1.legend()\n\n    plt.show()\n\n\ndef main(args: argparse.Namespace) -> None:\n    # Since 3.1, XGBoost can estimate the base_score automatically for built-in\n    # multi-class objectives.\n    #\n    # We explicitly specify it here to disable the automatic estimation to have a proper\n    # comparison between the custom implementation and the built-in implementation.\n    intercept = np.full(shape=(kClasses,), fill_value=1 / kClasses)\n\n    custom_results: Dict[str, Dict] = {}\n    # Use our custom objective function\n    booster_custom = xgb.train(\n        {\n            \"num_class\": kClasses,\n            \"base_score\": intercept,\n            \"disable_default_eval_metric\": True,\n        },\n        m,\n        num_boost_round=kRounds,\n        obj=softprob_obj,\n        custom_metric=merror,\n        evals_result=custom_results,\n        evals=[(m, \"train\")],\n    )\n\n    predt_custom = predict(booster_custom, m)\n\n    native_results: Dict[str, Dict] = {}\n    # Use the same objective function defined in XGBoost.\n    booster_native = xgb.train(\n        {\n            \"num_class\": kClasses,\n            \"base_score\": intercept,\n            \"objective\": \"multi:softmax\",\n            \"eval_metric\": \"merror\",\n        },\n        m,\n        num_boost_round=kRounds,\n        evals_result=native_results,\n        evals=[(m, \"train\")],\n    )\n    predt_native = booster_native.predict(m)\n\n    # We are reimplementing the loss function in XGBoost, so it should\n    # be the same for normal cases.\n    assert np.all(predt_custom == predt_native)\n    np.testing.assert_allclose(\n        custom_results[\"train\"][\"PyMError\"], native_results[\"train\"][\"merror\"]\n    )\n\n    if args.plot != 0:\n        plot_history(custom_results, native_results)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(\n        description=\"Arguments for custom softmax objective function demo.\"\n    )\n    parser.add_argument(\n        \"--plot\",\n        type=int,\n        default=1,\n        help=\"Set to 0 to disable plotting the evaluation history.\",\n    )\n    args = parser.parse_args()\n    main(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
}