Skip to content

Commit

Permalink
Merge branch 'master' of ssh://github.com/dmlc/xgboost
Browse files Browse the repository at this point in the history
  • Loading branch information
tqchen committed May 8, 2015
2 parents 68444a0 + 0af5cfb commit 6942980
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 30 deletions.
16 changes: 12 additions & 4 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,16 @@ xgboost-0.3
* Add [Code Guide](src/README.md) for customizing objective function and evaluation
* Add R module

in progress version
in progress 0.4
=====
* Distributed version
* Feature importance visualization in R module, thanks to Michael Benesty
* Predict leaf inde
* Distributed version of xgboost that runs on YARN, scales to billions of examples
* Direct save/load data and model from/to S3 and HDFS
* Feature importance visualization in R module, by Michael Benesty
* Predict leaf index
* Poisson regression for counts data
* Early stopping option in training
* Native save load support in R and python
- xgboost models now can be saved using save/load in R
- xgboost python model is now pickable
* sklearn wrapper is supported in python module
* Experimental External memory version
53 changes: 29 additions & 24 deletions demo/kaggle-otto/understandingXGBoostModel.Rmd
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
---
title: "Understanding XGBoost Model on Otto Dataset"
author: "Michaël Benesty"
output: html_document
output:
rmarkdown::html_vignette:
css: ../../R-package/vignettes/vignette.css
number_sections: yes
toc: yes
---

Introduction
============

**XGBoost** is an implementation of the famous gradient boosting algorithm. This model is often described as a *blackbox*, meaning it works well but it is not trivial to understand how. Indeed, the model is made of hundreds (thousands?) of decision trees. You may wonder how possible a human would be able to have a general view of the model?

While XGBoost is known for its fast speed and accurate predictive power. It also comes with various functions to help you understand the model.
The purpose of this RMarkdown document is to demonstrate how we can leverage the functions already implemented in **XGBoost R** package for that purpose. Of course, everything showed below can be applied to the dataset you may have to manipulate at work or wherever!

First we will train a model on the **OTTO** dataset, then we will generate two vizualisations to get a clue of what is important to the model, finally, we will see how we can leverage these information.
While XGBoost is known for its fast speed and accurate predictive power, it also comes with various functions to help you understand the model.
The purpose of this RMarkdown document is to demonstrate how easily we can leverage the functions already implemented in **XGBoost R** package. Of course, everything showed below can be applied to the dataset you may have to manipulate at work or wherever!

First we will prepare the **Otto** dataset and train a model, then we will generate two vizualisations to get a clue of what is important to the model, finally, we will see how we can leverage these information.

Preparation of the data
=======================

This part is based on the tutorial example by [Tong He](https://github.com/dmlc/xgboost/blob/master/demo/kaggle-otto/otto_train_pred.R)
This part is based on the **R** tutorial example by [Tong He](https://github.com/dmlc/xgboost/blob/master/demo/kaggle-otto/otto_train_pred.R)

First, let's load the packages and the dataset.

Expand All @@ -30,9 +33,9 @@ require(magrittr)
train <- fread('data/train.csv', header = T, stringsAsFactors = F)
test <- fread('data/test.csv', header=TRUE, stringsAsFactors = F)
```
> `magrittr` and `data.table` are here to make the code cleaner and more rapid.
> `magrittr` and `data.table` are here to make the code cleaner and much more rapid.
Let's see what is in this dataset.
Let's explore the dataset.

```{r explore}
# Train dataset dimensions
Expand All @@ -49,10 +52,11 @@ test[1:6,1:5, with =F]
```
> We only display the 6 first rows and 5 first columns for convenience
Each column represents a feature measured by an integer. Each row is a product.
Each *column* represents a feature measured by an integer. Each *row* is an **Otto** product.

Obviously the first column (`ID`) doesn't contain any useful information.
To let the algorithm focus on real stuff, we will delete the column.

To let the algorithm focus on real stuff, we will delete it.

```{r clean, results='hide'}
# Delete ID column in training dataset
Expand All @@ -62,7 +66,7 @@ train[, id := NULL]
test[, id := NULL]
```

According to the `OTTO` challenge description, we have here a multi class classification challenge. We need to extract the labels (here the name of the different classes) from the dataset. We only have two files (test and training), it seems logical that the training file contains the class we are looking for. Usually the labels is in the first or the last column. Let's check the content of the last column.
According to its description, the **Otto** challenge is a multi class classification challenge. We need to extract the labels (here the name of the different classes) from the dataset. We only have two files (test and training), it seems logical that the training file contains the class we are looking for. Usually the labels is in the first or the last column. We already know what is in the first column, let's check the content of the last one.

```{r searchLabel}
# Check the content of the last column
Expand All @@ -71,7 +75,7 @@ train[1:6, ncol(train), with = F]
nameLastCol <- names(train)[ncol(train)]
```

The class are provided as character string in the **`r ncol(train)`**th column called **`r nameLastCol`**. As you may know, **XGBoost** doesn't support anything else than numbers. So we will convert classes to integers. Moreover, according to the documentation, it should start at 0.
The classes are provided as character string in the **`r ncol(train)`**th column called **`r nameLastCol`**. As you may know, **XGBoost** doesn't support anything else than numbers. So we will convert classes to integers. Moreover, according to the documentation, it should start at 0.

For that purpose, we will:

Expand All @@ -81,19 +85,19 @@ For that purpose, we will:
* remove 1 to the new value

```{r classToIntegers}
# Convert to classes to numbers
# Convert from classes to numbers
y <- train[, nameLastCol, with = F][[1]] %>% gsub('Class_','',.) %>% {as.integer(.) -1}
# Display the first 5 levels
y[1:5]
```

We remove label column from training dataset, otherwise XGBoost would use it to guess the labels!!!
We remove label column from training dataset, otherwise **XGBoost** would use it to guess the labels!

```{r deleteCols, results='hide'}
train[, nameLastCol:=NULL, with = F]
```

`data.table` is an awesome implementation of data.frame, unfortunately it is not a format supported natively by XGBoost. We need to convert both datasets (training and test) in numeric Matrix format.
`data.table` is an awesome implementation of data.frame, unfortunately it is not a format supported natively by **XGBoost**. We need to convert both datasets (training and test) in numeric Matrix format.

```{r convertToNumericMatrix}
trainMatrix <- train[,lapply(.SD,as.numeric)] %>% as.matrix
Expand All @@ -105,7 +109,7 @@ Model training

Before the learning we will use the cross validation to evaluate the our error rate.

Basically XGBoost will divide the training data in `nfold` parts, then XGBoost will retain the first part and use it as the test data. Then it will reintegrate the first part to the training dataset and retain the second part, do a training and so on...
Basically **XGBoost** will divide the training data in `nfold` parts, then **XGBoost** will retain the first part and use it as the test data. Then it will reintegrate the first part to the training dataset and retain the second part, do a training and so on...

Look at the function documentation for more information.

Expand Down Expand Up @@ -140,13 +144,13 @@ Feature importance

So far, we have built a model made of **`r nround`** trees.

To build a tree, the dataset is divided recursively several times. At the end of the process, you get groups of observations (here, these observations are properties regarding **OTTO** products).
To build a tree, the dataset is divided recursively several times. At the end of the process, you get groups of observations (here, these observations are properties regarding **Otto** products).

Each division operation is called a *split*.

Each group at each division level is called a branch and the deepest level is called a **leaf**.

In the final model, these leafs are supposed to be as pure as possible for each tree, meaning in our case that each leaf should be made of one class of **OTTO** product only (of course it is not true, but that's what we try to achieve in a minimum of splits).
In the final model, these leafs are supposed to be as pure as possible for each tree, meaning in our case that each leaf should be made of one class of **Otto** product only (of course it is not true, but that's what we try to achieve in a minimum of splits).

**Not all splits are equally important**. Basically the first split of a tree will have more impact on the purity that, for instance, the deepest split. Intuitively, we understand that the first split makes most of the work, and the following splits focus on smaller parts of the dataset which have been missclassified by the first tree.

Expand All @@ -168,13 +172,13 @@ Clearly, it is not easy to understand what it means.

Basically each line represents a branch, there is the tree ID, the feature ID, the point where it splits, and information regarding the next branches (left, right, when the row for this feature is N/A).

Hopefully, XGBoost offers a better representation: **feature importance**.
Hopefully, **XGBoost** offers a better representation: **feature importance**.

Feature importance is about averaging the gain of each feature for all split and all trees.

Then we can use the function `xgb.plot.importance`.

```{r importanceFeature}
```{r importanceFeature, fig.align='center', fig.height=5, fig.width=10}
# Get the feature real names
names <- dimnames(trainMatrix)[[2]]
Expand All @@ -184,6 +188,7 @@ importance_matrix <- xgb.importance(names, model = bst)
# Nice graph
xgb.plot.importance(importance_matrix[1:10,])
```

> To make it understandable we first extract the column names from the `Matrix`.
Interpretation
Expand All @@ -195,7 +200,7 @@ This function gives a color to each bar. Basically a K-means clustering is appl

From here you can take several actions. For instance you can remove the less important feature (feature selection process), or go deeper in the interaction between the most important features and labels.

Or you can just reason about why these features are so importat (in OTTO challenge we can't go this way because there is not enough information).
Or you can just reason about why these features are so importat (in **Otto** challenge we can't go this way because there is not enough information).

Tree graph
----------
Expand All @@ -204,19 +209,19 @@ Feature importance gives you feature weight information but not interaction betw

**XGBoost R** package have another useful function for that.

```{r treeGraph, dpi=300, fig.align='left'}
```{r treeGraph, dpi=1500, fig.align='left'}
xgb.plot.tree(feature_names = names, model = bst, n_first_tree = 2)
```

We are just displaying the first two trees here.

On simple models the first two trees may be enough. Here, it might not be the case. We can see from the size of the trees that the intersaction between features is complicated.
Besides, XGBoost generate `k` trees at each round for a `k`-classification problem. Therefore the two trees illustrated here are trying to classify data into different classes.
Besides, **XGBoost** generate `k` trees at each round for a `k`-classification problem. Therefore the two trees illustrated here are trying to classify data into different classes.

Going deeper
============

There are two documents you may want to check to go deeper:
There are 3 documents you may be interested in:

* [xgboostPresentation.Rmd](https://github.com/dmlc/xgboost/blob/master/R-package/vignettes/xgboostPresentation.Rmd): general presentation
* [discoverYourData.Rmd](https://github.com/dmlc/xgboost/blob/master/R-package/vignettes/discoverYourData.Rmd): explaining feature analysus
Expand Down
4 changes: 2 additions & 2 deletions wrapper/xgboost.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ def save_model(self, fname):
Parameters
----------
fname : string
Output file name or handle
Output file name
"""
if isinstance(fname, string_types): # assume file name
xglib.XGBoosterSaveModel(self.handle, c_str(fname))
Expand All @@ -507,7 +507,7 @@ def load_model(self, fname):
Parameters
----------
fname : string of file handle
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw)
"""
if isinstance(fname, str): # assume file name
Expand Down

0 comments on commit 6942980

Please sign in to comment.