{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Demo for GLM\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\n\nimport xgboost as xgb\n\n##\n#  this script demonstrate how to fit generalized linear model in xgboost\n#  basically, we are using linear model, instead of tree for our boosters\n##\nCURRENT_DIR = os.path.dirname(__file__)\ndtrain = xgb.DMatrix(\n    os.path.join(CURRENT_DIR, \"../data/agaricus.txt.train?format=libsvm\")\n)\ndtest = xgb.DMatrix(\n    os.path.join(CURRENT_DIR, \"../data/agaricus.txt.test?format=libsvm\")\n)\n# change booster to gblinear, so that we are fitting a linear model\n# alpha is the L1 regularizer\n# lambda is the L2 regularizer\n# you can also set lambda_bias which is L2 regularizer on the bias term\nparam = {\n    \"objective\": \"binary:logistic\",\n    \"booster\": \"gblinear\",\n    \"alpha\": 0.0001,\n    \"lambda\": 1,\n}\n\n# normally, you do not need to set eta (step_size)\n# XGBoost uses a parallel coordinate descent algorithm (shotgun),\n# there could be affection on convergence with parallelization on certain cases\n# setting eta to be smaller value, e.g 0.5 can make the optimization more stable\n# param['eta'] = 1\n\n##\n# the rest of settings are the same\n##\nwatchlist = [(dtest, \"eval\"), (dtrain, \"train\")]\nnum_round = 4\nbst = xgb.train(param, dtrain, num_round, watchlist)\npreds = bst.predict(dtest)\nlabels = dtest.get_label()\nprint(\n    \"error=%f\"\n    % (\n        sum(1 for i in range(len(preds)) if int(preds[i] > 0.5) != labels[i])\n        / float(len(preds))\n    )\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
}