Debian Codegraph @

vignettes/xgboost_introduction.Rmd

raw
1 ---
2 title: "XGBoost for R introduction"
3 vignette: >
4 %\VignetteIndexEntry{XGBoost for R introduction}
5 %\VignetteEncoding{UTF-8}
6 %\VignetteEngine{knitr::rmarkdown}
7 output:
8 html_document:
9 theme: "spacelab"
10 highlight: "kate"
11 toc: true
12 toc_float: true
13 ---
14
15 XGBoost for R introduction
16 ==========================
17
18 ## Introduction
19
20 **XGBoost** is an optimized distributed gradient boosting library designed to be highly **efficient**, **flexible** and **portable**. It implements machine learning algorithms under the `gradient boosting` framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way. The same code runs on major distributed environment (Hadoop, SGE, MPI) and can solve problems beyond billions of examples.
21
22 For an introduction to the concept of gradient boosting, see the tutorial [Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/stable/tutorials/model.html) in XGBoost's online docs.
23
24 For more details about XGBoost's features and usage, see the [online documentation](https://xgboost.readthedocs.io/en/stable/) which contains more tutorials, examples, and details.
25
26 This short vignette outlines the basic usage of the R interface for XGBoost, assuming the reader has some familiarity with the underlying concepts behind statistical modeling with gradient-boosted decision trees.
27
28 ## Building a predictive model
29
30 At its core, XGBoost consists of a C++ library which offers bindings for different programming languages, including R. The R package for XGBoost provides an idiomatic interface similar to those of other statistical modeling packages using and x/y design, as well as a lower-level interface that interacts more directly with the underlying core library and which is similar to those of other language bindings like Python, plus various helpers to interact with its model objects such as by plotting their feature importances or converting them to other formats.
31
32 The main function of interest is `xgboost(x, y, ...)`, which calls the XGBoost model building procedure on observed data of covariates/features/predictors "x", and a response variable "y" - it should feel familiar to users of packages like `glmnet` or `ncvreg`:
33
34 ```{r}
35 library(xgboost)
36 data(ToothGrowth)
37
38 y <- ToothGrowth$supp # the response which we want to model/predict
39 x <- ToothGrowth[, c("len", "dose")] # the features from which we want to predict it
40 model <- xgboost(x, y, nthreads = 1, nrounds = 2)
41 model
42 ```
43
44 In this case, the "y" response variable that was supplied is a "factor" type with two classes ("OJ" and "VC") - hence, XGBoost builds a binary classification model for it based on the features "x", by finding a maximum likelihood estimate (similar to the `family="binomial"` model from R's `glm` function) through rule buckets obtained from the sum of two decision trees (from `nrounds=2`), from which we can then predict probabilities, log-odds, class with highest likelihood, among others:
45
46 ```{r}
47 predict(model, x[1:6, ], type = "response") # probabilities for y's last level ("VC")
48 predict(model, x[1:6, ], type = "raw") # log-odds
49 predict(model, x[1:6, ], type = "class") # class with highest probability
50 ```
51
52 Compared to R's `glm` function which follows the concepts of "families" and "links" from GLM theory to fit models for different kinds of response distributions, XGBoost follows the simpler concept of "objectives" which mix both of them into one, and which just like `glm`, allow modeling very different kinds of response distributions (e.g. discrete choices, real-valued numbers, counts, censored measurements, etc.) through a common framework.
53
54 XGBoost will automatically determine a suitable objective for the response given its object class (can pass factors for classification, numeric vectors for regression, `Surv` objects from the `survival` package for survival, etc. - see `?xgboost` for more details), but this can be controlled manually through an `objective` parameter based the kind of model that is desired:
55
56 ```{r}
57 data(mtcars)
58
59 y <- mtcars$mpg
60 x <- mtcars[, -1]
61 model_gaussian <- xgboost(x, y, nthreads = 1, nrounds = 2) # default is squared loss (Gaussian)
62 model_poisson <- xgboost(x, y, objective = "count:poisson", nthreads = 1, nrounds = 2)
63 model_abserr <- xgboost(x, y, objective = "reg:absoluteerror", nthreads = 1, nrounds = 2)
64 ```
65
66 _Note: the objective must match with the type of the "y" response variable - for example, classification objectives for discrete choices require "factor" types, while regression models for real-valued data require "numeric" types._
67
68 ## Model parameters
69
70 XGBoost models allow a large degree of control over how they are built. By their nature, gradient-boosted decision tree ensembles are able to capture very complex patterns between features in the data and a response variable, which also means they can suffer from overfitting if not controlled appropirately.
71
72 For best results, one needs to find suitable parameters for the data being modeled. Note that XGBoost does not adjust its default hyperparameters based on the data, and different datasets will require vastly different hyperparameters for optimal predictive performance.
73
74 For example, for a small dataset like "TootGrowth" which has only two features and 60 observations, the defaults from XGBoost are an overkill which lead to severe overfitting - for such data, one might want to have smaller trees (i.e. more convervative decision rules, capturing simpler patterns) and fewer of them, for example.
75
76 Parameters can be controlled by passing additional arguments to `xgboost()`. See `?xgb.params` for details about what parameters are available to control.
77
78 ```{r}
79 y <- ToothGrowth$supp
80 x <- ToothGrowth[, c("len", "dose")]
81 model_conservative <- xgboost(
82 x, y, nthreads = 1,
83 nrounds = 5,
84 max_depth = 2,
85 reg_lambda = 0.5,
86 learning_rate = 0.15
87 )
88 pred_conservative <- predict(
89 model_conservative,
90 x
91 )
92 pred_conservative[1:6] # probabilities are all closer to 0.5 now
93 ```
94
95 XGBoost also allows the possibility of calculating evaluation metrics for model quality over boosting rounds, with a wide variety of built-in metrics available to use. It's possible to automatically set aside a fraction of the data to use as evaluation set, from which one can then visually monitor progress and overfitting:
96
97 ```{r}
98 xgboost(
99 x, y, nthreads = 1,
100 eval_set = 0.2,
101 monitor_training = TRUE,
102 verbosity = 1,
103 eval_metric = c("auc", "logloss"),
104 nrounds = 5,
105 max_depth = 2,
106 reg_lambda = 0.5,
107 learning_rate = 0.15
108 )
109 ```
110
111 ## Examining model objects
112
113 XGBoost model objects for the most part consist of a pointer to a C++ object where most of the information is held and which is interfaced through the utility functions and methods in the package, but also contains some R attributes that can be retrieved (and new ones added) through `attributes()`:
114
115 ```{r}
116 attributes(model)
117 ```
118
119 In addition to R attributes (which can be arbitrary R objects), it may also keep some standardized C-level attributes that one can access and modify (but which can only be JSON-format):
120
121 ```{r}
122 xgb.attributes(model)
123 ```
124
125 (they are empty for this model)
126
127 ... but usually, when it comes to getting something out of a model object, one would typically want to do this through the built-in utility functions. Some examples:
128
129 ```{r}
130 xgb.importance(model)
131 ```
132
133 ```{r}
134 xgb.model.dt.tree(model)
135 ```
136
137 ## Other features
138
139 XGBoost supports many additional features on top of its traditional gradient-boosting framework, including, among others:
140
141 * Building decision tree models with characteristics such as per-feature monotonicity constraints or interaction constraints.
142 * Calculating feature contributions in individual predictions.
143 * Using custom objectives and custom evaluation metrics.
144 * Fitting linear models.
145 * Fitting models on GPUs and/or on data that doesn't fit in RAM ("external memory").
146
147 See the [online documentation](https://xgboost.readthedocs.io/en/stable/index.html) - particularly the [tutorials section](https://xgboost.readthedocs.io/en/stable/tutorials/index.html) - for a glimpse over further functionalities that XGBoost offers.
148
149 ## The low-level interface
150
151 In addition to the `xgboost(x, y, ...)` function, XGBoost also provides a lower-level interface for creating model objects through the function `xgb.train()`, which resembles the same `xgb.train` functions in other language bindings of XGBoost.
152
153 This `xgb.train()` interface exposes additional functionalities (such as user-supplied callbacks or external-memory data support) and performs fewer data validations and castings compared to the `xgboost()` function interface.
154
155 Some key differences between the two interfaces:
156
157 * Unlike `xgboost()` which takes R objects such as `matrix` or `data.frame` as inputs, the function `xgb.train()` uses XGBoost's own data container called "DMatrix", which can be created from R objects through the function `xgb.DMatrix()`. Note that there are other "DMatrix" constructors too, such as "xgb.QuantileDMatrix()", which might be more beneficial for some use-cases.
158 * A "DMatrix" object may contain a mixture of features/covariates, the response variable, observation weights, base margins, among others; and unlike `xgboost()`, requires its inputs to have already been encoded into the representation that XGBoost uses behind the scenes - for example, while `xgboost()` may take a `factor` object as "y", `xgb.DMatrix()` requires instead a binary response variable to be passed as a vector of zeros and ones.
159 * Hyperparameters are passed as function arguments in `xgboost()`, while they are passed as a named list to `xgb.train()`.
160 * The `xgb.train()` interface keeps less metadata about its inputs - for example, it will not add levels of factors as column names to estimated probabilities when calling `predict`.
161
162 Example usage of `xgb.train()`:
163
164 ```{r}
165 data("agaricus.train")
166 dmatrix <- xgb.DMatrix(
167 data = agaricus.train$data, # a sparse CSC matrix ('dgCMatrix')
168 label = agaricus.train$label, # zeros and ones
169 nthread = 1
170 )
171 booster <- xgb.train(
172 data = dmatrix,
173 nrounds = 10,
174 params = xgb.params(
175 objective = "binary:logistic",
176 nthread = 1,
177 max_depth = 3
178 )
179 )
180
181 data("agaricus.test")
182 dmatrix_test <- xgb.DMatrix(agaricus.test$data, nthread = 1)
183 pred_prob <- predict(booster, dmatrix_test)
184 pred_raw <- predict(booster, dmatrix_test, outputmargin = TRUE)
185 ```
186
187 Model objects produced by `xgb.train()` have class `xgb.Booster`, while model objects produced by `xgboost()` have class `xgboost`, which is a subclass of `xgb.Booster`. Their `predict` methods also take different arguments - for example, `predict.xgboost` has a `type` parameter, while `predict.xgb.Booster` controls this through binary arguments - but as `xgboost` is a subclass of `xgb.Booster`, methods for `xgb.Booster` can be called on `xgboost` objects if needed.
188
189 Utility functions in the XGBoost R package will work with both model classes - for example:
190
191 ```{r}
192 xgb.importance(model)
193 xgb.importance(booster)
194 ```
195
196 While `xgboost()` aims to provide a user-friendly interface, there are still many situations where one should prefer the `xgb.train()` interface - for example:
197
198 * For latency-sensitive applications (e.g. when serving models in real time), `xgb.train()` will have a speed advantage, as it performs fewer validations, conversions, and post-processings with metadata.
199 * If you are developing an R package that depends on XGBoost, `xgb.train()` will provide a more stable interface (less subject to changes) and will have lower time/memory overhead.
200 * If you need functionalities that are not exposed by the `xgboost()` interface - for example, if your dataset does not fit into the computer's RAM, it's still possible to construct a DMatrix from it if the data is loaded in batches through `xgb.ExtMemDMatrix()`.