{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for gamma regression\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nimport xgboost as xgb\n\n#  this script demonstrates how to fit gamma regression model (with log link function)\n#  in xgboost, before running the demo you need to generate the autoclaims dataset\n#  by running gen_autoclaims.R located in xgboost/demo/data.\n\ndata = np.genfromtxt('../data/autoclaims.csv', delimiter=',')\ndtrain = xgb.DMatrix(data[0:4741, 0:34], data[0:4741, 34])\ndtest = xgb.DMatrix(data[4741:6773, 0:34], data[4741:6773, 34])\n\n# for gamma regression, we need to set the objective to 'reg:gamma', it also suggests\n# to set the base_score to a value between 1 to 5 if the number of iteration is small\nparam = {'objective':'reg:gamma', 'booster':'gbtree', 'base_score':3}\n\n# the rest of settings are the same\nwatchlist = [(dtest, 'eval'), (dtrain, 'train')]\nnum_round = 30\n\n# training and evaluation\nbst = xgb.train(param, dtrain, num_round, watchlist)\npreds = bst.predict(dtest)\nlabels = dtest.get_label()\nprint('test deviance=%f' % (2 * np.sum((labels - preds) / preds - np.log(labels) + np.log(preds))))"
      ]
    }
  ],
  "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
}