Xgboost is short for eXtreme Gradient Boosting package.
It supports various objective functions, including regression, classification and ranking. The package is made to be extendible, so that users are also allowed to define their own objective functions easily.
It has several features:
- Speed: it can automatically do parallel computation on Windows and Linux, with OpenMP. It is generally over 10 times faster than the classical
gbm
. - Input Type: it takes several types of input data:
- Dense Matrix: R‘s dense matrix, i.e.
matrix
; - Sparse Matrix: R‘s sparse matrix, i.e.
Matrix::dgCMatrix
; - Data File: local data files ;
xgb.DMatrix
: its own class (recommended).
- Dense Matrix: R‘s dense matrix, i.e.
- Sparsity: it accepts sparse input for both tree booster and linear booster, and is optimized for sparseinput ;
- Customization: it supports customized objective functions and evaluation functions.
Installation
Github version
For weekly updated version (highly recommended), install from Github:
Windows user will need to install Rtools first.
CRAN version
The version 0.4-2 is on CRAN, and you can install it by:
Formerly available versions can be obtained from the CRAN archive
Learning
For the purpose of this tutorial we will load XGBoost package.
Dataset presentation
In this example, we are aiming to predict whether a mushroom can be eaten or not (like in many tutorials, example data are the same as you will use on in your every day life :-).
Mushroom data is cited from UCI Machine Learning Repository. @Bache+Lichman:2013.
Dataset loading
We will load the
agaricus
datasets embedded with the package and will link them to variables.
The datasets are already split in:
train
: will be used to build the model ;test
: will be used to assess the quality of our model.
Why split the dataset in two parts?
In the first part we will build our model. In the second part we will want to test it and assess its quality. Without dividing the dataset we would test the model on the data which the algorithm have already seen.
In the real world, it would be up to you to make this division betweentrain
andtest
data. The way to do it is out of the purpose of this article, howevercaret
package may help.
Each variable is a
list
containing two things, label
and data
:label
is the outcome of our dataset meaning it is the binary classification we will try to predict.
Let’s discover the dimensionality of our datasets.
This dataset is very small to not make the R package too heavy, however XGBoost is built to manage huge dataset very efficiently.
As seen below, the
data
are stored in a dgCMatrix
which is a sparse matrix and label
vector is a numeric
vector ({0,1}
):Basic Training using XGBoost
This step is the most critical part of the process for the quality of our model.
Basic training
We are using the
train
data. As explained above, both data
and label
are stored in a list
.
In a sparse matrix, cells containing
0
are not stored in memory. Therefore, in a dataset mainly made of 0
, memory size is reduced. It is very usual to have such dataset.
We will train decision tree model using the following parameters:
objective = "binary:logistic"
: we will train a binary classification model ;max.deph = 2
: the trees won’t be deep, because our case is very simple ;nthread = 2
: the number of cpu threads we are going to use;nround = 2
: there will be two passes on the data, the second one will enhance the model by further reducing the difference between ground truth and prediction.
More complex the relationship between your features and yourlabel
is, more passes you need.
Parameter variations
Dense matrix
Alternatively, you can put your dataset in a dense matrix, i.e. a basic R matrix.
xgb.DMatrix
XGBoost offers a way to group them in a
xgb.DMatrix
. You can even add other meta data in it. It will be useful for the most advanced features we will discover later.Verbose option
XGBoost has several features to help you to view how the learning progress internally. The purpose is to help you to set the best parameters, which is the key of your model quality.
One of the simplest way to see the training progress is to set the
verbose
option (see below for more advanced technics).Basic prediction using XGBoost
Perform the prediction
The purpose of the model we have built is to classify new data. As explained before, we will use the
test
dataset for this step.
These numbers doesn’t look like binary classification
{0,1}
. We need to perform a simple transformation before being able to use these results.Transform the regression in a binary classification
The only thing that XGBoost does is a regression. XGBoost is using
label
vector to build its regressionmodel.
How can we use a regression model to perform a binary classification?
If we think about the meaning of a regression applied to our data, the numbers we get are probabilities that a datum will be classified as
1
. Therefore, we will set the rule that if this probability for a specific datum is >0.5
then the observation is classified as 1
(or 0
otherwise).Measuring model performance
To measure the model performance, we will compute a simple metric, the average error.
Note that the algorithm has not seen thetest
data during the model construction.
Steps explanation:
as.numeric(pred > 0.5)
applies our rule that when the probability (<=> regression <=> prediction) is>0.5
the observation is classified as1
and0
otherwise ;probabilityVectorPreviouslyComputed != test$label
computes the vector of error between true data and computed probabilities ;mean(vectorOfErrors)
computes the average error itself.
The most important thing to remember is that to do a classification, you just do a regression to the
label
and then apply a threshold.
Multiclass classification works in a similar way.
This metric is 0.02 and is pretty low: our yummly mushroom model works well!
Advanced features
Most of the features below have been implemented to help you to improve your model by offering a better understanding of its content.
Dataset preparation
For the following advanced features, we need to put data in
xgb.DMatrix
as explained above.Measure learning progress with xgb.train
Both
xgboost
(simple) and xgb.train
(advanced) functions train models.
One of the special feature of
xgb.train
is the capacity to follow the progress of the learning after each round. Because of the way boosting works, there is a time when having too many rounds lead to an overfitting. You can see this feature as a cousin of cross-validation method. The following techniques will help you to avoid overfitting or optimizing the learning time in stopping it as soon as possible.
One way to measure progress in learning of a model is to provide to XGBoost a second dataset already classified. Therefore it can learn on the first dataset and test its model on the second one. Some metrics are measured after each round during the learning.
in some way it is similar to what we have done above with the average error. The main difference is that below it was after building the model, and now it is during the construction that we measure errors.
For the purpose of this example, we use
watchlist
parameter. It is a list of xgb.DMatrix
, each of them tagged with a name.
XGBoost has computed at each round the same average error metric than seen above (we set
nround
to 2, that is why we have two lines). Obviously, the train-error
number is related to the training dataset (the one the algorithm learns from) and the test-error
number to the test dataset.
Both training and test error related metrics are very similar, and in some way, it makes sense: what we have learned from the training dataset matches the observations from the test dataset.
If with your own dataset you have not such results, you should think about how you divided your dataset in training and test. May be there is something to fix. Again,
caret
package may help.
For a better understanding of the learning progression, you may want to have some specific metric or even use multiple evaluation metrics.
eval.metric
allows us to monitor two new metrics for each round,logloss
anderror
.
Linear boosting
Until now, all the learnings we have performed were based on boosting trees. XGBoost implements a second algorithm, based on linear boosting. The only difference with previous command is
booster = "gblinear"
parameter (and removing eta
parameter).
In this specific case, linear boosting gets slightly better performance metrics than decision trees based algorithm.
In simple cases, it will happen because there is nothing better than a linear algorithm to catch a linear link. However, decision trees are much better to catch a non linear link between predictors and outcome. Because there is no silver bullet, we advise you to check both algorithms with your own datasets to have an idea of what to use.
Manipulating xgb.DMatrix
Save / Load
Like saving models,
xgb.DMatrix
object (which groups both dataset and outcome) can also be saved using xgb.DMatrix.save
function.Information extraction
Information can be extracted from
xgb.DMatrix
using getinfo
function. Hereafter we will extract label
data.View feature importance/influence from the learnt model
Feature importance is similar to R gbm package’s relative influence (rel.inf).
View the trees from a model
You can dump the tree you learned using
xgb.dump
into a text file.
You can plot the trees from your model using ```xgb.plot.tree``
if you provide a path tofname
parameter you can save the trees to your hard drive.
Save and load models
Maybe your dataset is big, and it takes time to train a model on it? May be you are not a big fan of losing time in redoing the same task again and again? In these very rare cases, you will want to save your model and load it when required.
Hopefully for you, XGBoost implements such functions.
xgb.save
function should return TRUE if everything goes well and crashes otherwise.
An interesting test to see how identical our saved model is to the original one would be to compare the two predictions.
result is0
? We are good!
In some very specific cases, like when you want to pilot XGBoost from
caret
package, you will want to save the model as a R binary vector. See below how to do it.Again0
? It seems thatXGBoost
works pretty well!
No comments:
Post a Comment