Skip to content

Commit 7f85484

Browse files
Update R docs based on deprecated parameters/behaviour (dmlc#9437)
1 parent f05294a commit 7f85484

File tree

2 files changed

+394
-423
lines changed

2 files changed

+394
-423
lines changed

R-package/vignettes/discoverYourData.Rmd

+36-69
Original file line numberDiff line numberDiff line change
@@ -51,24 +51,24 @@ A *categorical* variable has a fixed number of different values. For instance, i
5151
>
5252
> Type `?factor` in the console for more information.
5353
54-
To answer the question above we will convert *categorical* variables to `numeric` one.
54+
To answer the question above we will convert *categorical* variables to `numeric` ones.
5555

5656
### Conversion from categorical to numeric variables
5757

5858
#### Looking at the raw data
5959

60-
In this Vignette we will see how to transform a *dense* `data.frame` (*dense* = few zeroes in the matrix) with *categorical* variables to a very *sparse* matrix (*sparse* = lots of zero in the matrix) of `numeric` features.
60+
+In this Vignette we will see how to transform a *dense* `data.frame` (*dense* = the majority of the matrix is non-zero) with *categorical* variables to a very *sparse* matrix (*sparse* = lots of zero entries in the matrix) of `numeric` features.
6161

6262
The method we are going to see is usually called [one-hot encoding](https://en.wikipedia.org/wiki/One-hot).
6363

64-
The first step is to load `Arthritis` dataset in memory and wrap it with `data.table` package.
64+
The first step is to load the `Arthritis` dataset in memory and wrap it with the `data.table` package.
6565

6666
```{r, results='hide'}
6767
data(Arthritis)
6868
df <- data.table(Arthritis, keep.rownames = FALSE)
6969
```
7070

71-
> `data.table` is 100% compliant with **R** `data.frame` but its syntax is more consistent and its performance for large dataset is [best in class](https://stackoverflow.com/questions/21435339/data-table-vs-dplyr-can-one-do-something-well-the-other-cant-or-does-poorly) (`dplyr` from **R** and `Pandas` from **Python** [included](https://github.com/Rdatatable/data.table/wiki/Benchmarks-%3A-Grouping)). Some parts of **XGBoost** **R** package use `data.table`.
71+
> `data.table` is 100% compliant with **R** `data.frame` but its syntax is more consistent and its performance for large dataset is [best in class](https://stackoverflow.com/questions/21435339/data-table-vs-dplyr-can-one-do-something-well-the-other-cant-or-does-poorly) (`dplyr` from **R** and `Pandas` from **Python** [included](https://github.com/Rdatatable/data.table/wiki/Benchmarks-%3A-Grouping)). Some parts of **XGBoost's** **R** package use `data.table`.
7272
7373
The first thing we want to do is to have a look to the first few lines of the `data.table`:
7474

@@ -95,19 +95,19 @@ We will add some new *categorical* features to see if it helps.
9595

9696
##### Grouping per 10 years
9797

98-
For the first feature we create groups of age by rounding the real age.
98+
For the first features we create groups of age by rounding the real age.
9999

100-
Note that we transform it to `factor` so the algorithm treat these age groups as independent values.
100+
Note that we transform it to `factor` so the algorithm treats these age groups as independent values.
101101

102-
Therefore, 20 is not closer to 30 than 60. To make it short, the distance between ages is lost in this transformation.
102+
Therefore, 20 is not closer to 30 than 60. In other words, the distance between ages is lost in this transformation.
103103

104104
```{r}
105105
head(df[, AgeDiscret := as.factor(round(Age / 10, 0))])
106106
```
107107

108-
##### Random split into two groups
108+
##### Randomly split into two groups
109109

110-
Following is an even stronger simplification of the real age with an arbitrary split at 30 years old. We choose this value **based on nothing**. We will see later if simplifying the information based on arbitrary values is a good strategy (you may already have an idea of how well it will work...).
110+
The following is an even stronger simplification of the real age with an arbitrary split at 30 years old. I choose this value **based on nothing**. We will see later if simplifying the information based on arbitrary values is a good strategy (you may already have an idea of how well it will work...).
111111

112112
```{r}
113113
head(df[, AgeCat := as.factor(ifelse(Age > 30, "Old", "Young"))])
@@ -119,7 +119,7 @@ These new features are highly correlated to the `Age` feature because they are s
119119

120120
For many machine learning algorithms, using correlated features is not a good idea. It may sometimes make prediction less accurate, and most of the time make interpretation of the model almost impossible. GLM, for instance, assumes that the features are uncorrelated.
121121

122-
Fortunately, decision tree algorithms (including boosted trees) are very robust to these features. Therefore we have nothing to do to manage this situation.
122+
Fortunately, decision tree algorithms (including boosted trees) are very robust to these features. Therefore we don't have to do anything to manage this situation.
123123

124124
##### Cleaning data
125125

@@ -144,7 +144,7 @@ We will use the [dummy contrast coding](https://stats.oarc.ucla.edu/r/library/r-
144144

145145
The purpose is to transform each value of each *categorical* feature into a *binary* feature `{0, 1}`.
146146

147-
For example, the column `Treatment` will be replaced by two columns, `TreatmentPlacebo`, and `TreatmentTreated`. Each of them will be *binary*. Therefore, an observation which has the value `Placebo` in column `Treatment` before the transformation will have after the transformation the value `1` in the new column `TreatmentPlacebo` and the value `0` in the new column `TreatmentTreated`. The column `TreatmentPlacebo` will disappear during the contrast encoding, as it would be absorbed into a common constant intercept column.
147+
For example, the column `Treatment` will be replaced by two columns, `TreatmentPlacebo`, and `TreatmentTreated`. Each of them will be *binary*. Therefore, an observation which has the value `Placebo` in column `Treatment` before the transformation will have the value `1` in the new column `TreatmentPlacebo` and the value `0` in the new column `TreatmentTreated` after the transformation. The column `TreatmentPlacebo` will disappear during the contrast encoding, as it would be absorbed into a common constant intercept column.
148148

149149
Column `Improved` is excluded because it will be our `label` column, the one we want to predict.
150150

@@ -176,13 +176,9 @@ bst <- xgboost(data = sparse_matrix, label = output_vector, max_depth = 4,
176176
177177
```
178178

179-
You can see some `train-error: 0.XXXXX` lines followed by a number. It decreases. Each line shows how well the model explains your data. Lower is better.
179+
You can see some `train-logloss: 0.XXXXX` lines followed by a number. It decreases. Each line shows how well the model explains the data. Lower is better.
180180

181-
A small value for training error may be a symptom of [overfitting](https://en.wikipedia.org/wiki/Overfitting), meaning the model will not accurately predict the future values.
182-
183-
> Here you can see the numbers decrease until line 7 and then increase.
184-
>
185-
> It probably means we are overfitting. To fix that I should reduce the number of rounds to `nrounds = 4`. I will let things like that because I don't really care for the purpose of this example :-)
181+
A small value for training error may be a symptom of [overfitting](https://en.wikipedia.org/wiki/Overfitting), meaning the model will not accurately predict unseen values.
186182

187183
Feature importance
188184
------------------
@@ -199,64 +195,35 @@ importance <- xgb.importance(feature_names = colnames(sparse_matrix), model = bs
199195
head(importance)
200196
```
201197

202-
> The column `Gain` provide the information we are looking for.
198+
> The column `Gain` provides the information we are looking for.
203199
>
204200
> As you can see, features are classified by `Gain`.
205201
206-
`Gain` is the improvement in accuracy brought by a feature to the branches it is on. The idea is that before adding a new split on a feature X to the branch there was some wrongly classified elements, after adding the split on this feature, there are two new branches, and each of these branch is more accurate (one branch saying if your observation is on this branch then it should be classified as `1`, and the other branch saying the exact opposite).
202+
`Gain` is the improvement in accuracy brought by a feature to the branches it is on. The idea is that before adding a new split on a feature X to the branch there were some wrongly classified elements; after adding the split on this feature, there are two new branches, and each of these branches is more accurate (one branch saying if your observation is on this branch then it should be classified as `1`, and the other branch saying the exact opposite).
207203

208-
`Cover` measures the relative quantity of observations concerned by a feature.
204+
`Cover` is related to the second order derivative (or Hessian) of the loss function with respect to a particular variable; thus, a large value indicates a variable has a large potential impact on the loss function and so is important.
209205

210206
`Frequency` is a simpler way to measure the `Gain`. It just counts the number of times a feature is used in all generated trees. You should not use it (unless you know why you want to use it).
211207

212-
#### Improvement in the interpretability of feature importance data.table
213-
214-
We can go deeper in the analysis of the model. In the `data.table` above, we have discovered which features counts to predict if the illness will go or not. But we don't yet know the role of these features. For instance, one of the question we may want to answer would be: does receiving a placebo treatment helps to recover from the illness?
215-
216-
One simple solution is to count the co-occurrences of a feature and a class of the classification.
217-
218-
For that purpose we will execute the same function as above but using two more parameters, `data` and `label`.
219-
220-
```{r}
221-
importanceRaw <- xgb.importance(feature_names = colnames(sparse_matrix), model = bst, data = sparse_matrix, label = output_vector)
222-
223-
# Cleaning for better display
224-
importanceClean <- importanceRaw[, `:=`(Cover = NULL, Frequency = NULL)]
225-
226-
head(importanceClean)
227-
```
228-
229-
> In the table above we have removed two not needed columns and select only the first lines.
230-
231-
First thing you notice is the new column `Split`. It is the split applied to the feature on a branch of one of the tree. Each split is present, therefore a feature can appear several times in this table. Here we can see the feature `Age` is used several times with different splits.
232-
233-
How the split is applied to count the co-occurrences? It is always `<`. For instance, in the second line, we measure the number of persons under 61.5 years with the illness gone after the treatment.
234-
235-
The two other new columns are `RealCover` and `RealCover %`. In the first column it measures the number of observations in the dataset where the split is respected and the label marked as `1`. The second column is the percentage of the whole population that `RealCover` represents.
236-
237-
Therefore, according to our findings, getting a placebo doesn't seem to help but being younger than 61 years may help (seems logic).
238-
239-
> You may wonder how to interpret the `< 1.00001` on the first line. Basically, in a sparse `Matrix`, there is no `0`, therefore, looking for one hot-encoded categorical observations validating the rule `< 1.00001` is like just looking for `1` for this feature.
240-
241208
### Plotting the feature importance
242209

243-
244210
All these things are nice, but it would be even better to plot the results.
245211

246212
```{r, fig.width=8, fig.height=5, fig.align='center'}
247213
xgb.plot.importance(importance_matrix = importance)
248214
```
249215

250-
Feature have automatically been divided in 2 clusters: the interesting features... and the others.
216+
Running this line of code, you should get a bar chart showing the importance of the 6 features (containing the same data as the output we saw earlier, but displaying it visually for easier consumption). Note that `xgb.ggplot.importance` is also available for all the ggplot2 fans!
251217

252218
> Depending of the dataset and the learning parameters you may have more than two clusters. Default value is to limit them to `10`, but you can increase this limit. Look at the function documentation for more information.
253219
254220
According to the plot above, the most important features in this dataset to predict if the treatment will work are :
255221

256-
* the Age ;
257-
* having received a placebo or not ;
258-
* the sex is third but already included in the not interesting features group ;
259-
* then we see our generated features (AgeDiscret). We can see that their contribution is very low.
222+
* An individual's age;
223+
* Having received a placebo or not;
224+
* Gender;
225+
* Our generated feature AgeDiscret. We can see that its contribution is very low.
226+
260227

261228
### Do these results make sense?
262229

@@ -270,53 +237,53 @@ c2 <- chisq.test(df$Age, output_vector)
270237
print(c2)
271238
```
272239

273-
Pearson correlation between Age and illness disappearing is **`r round(c2$statistic, 2 )`**.
240+
The Pearson correlation between Age and illness disappearing is **`r round(c2$statistic, 2 )`**.
274241

275242
```{r, warning=FALSE, message=FALSE}
276243
c2 <- chisq.test(df$AgeDiscret, output_vector)
277244
print(c2)
278245
```
279246

280-
Our first simplification of Age gives a Pearson correlation is **`r round(c2$statistic, 2)`**.
247+
Our first simplification of Age gives a Pearson correlation of **`r round(c2$statistic, 2)`**.
281248

282249
```{r, warning=FALSE, message=FALSE}
283250
c2 <- chisq.test(df$AgeCat, output_vector)
284251
print(c2)
285252
```
286253

287-
The perfectly random split I did between young and old at 30 years old have a low correlation of **`r round(c2$statistic, 2)`**. It's a result we may expect as may be in my mind > 30 years is being old (I am 32 and starting feeling old, this may explain that), but for the illness we are studying, the age to be vulnerable is not the same.
254+
The perfectly random split we did between young and old at 30 years old has a low correlation of **2.36**. This suggests that, for the particular illness we are studying, the age at which someone is vulnerable to this disease is likely very different from 30.
288255

289-
Morality: don't let your *gut* lower the quality of your model.
256+
Moral of the story: don't let your *gut* lower the quality of your model.
290257

291-
In *data science* expression, there is the word *science* :-)
258+
In *data science*, there is the word *science* :-)
292259

293260
Conclusion
294261
----------
295262

296263
As you can see, in general *destroying information by simplifying it won't improve your model*. **Chi2** just demonstrates that.
297264

298-
But in more complex cases, creating a new feature based on existing one which makes link with the outcome more obvious may help the algorithm and improve the model.
265+
But in more complex cases, creating a new feature from an existing one may help the algorithm and improve the model.
299266

300-
The case studied here is not enough complex to show that. Check [Kaggle website](http://www.kaggle.com/) for some challenging datasets. However it's almost always worse when you add some arbitrary rules.
267+
+The case studied here is not complex enough to show that. Check [Kaggle website](https://www.kaggle.com/) for some challenging datasets.
301268

302-
Moreover, you can notice that even if we have added some not useful new features highly correlated with other features, the boosting tree algorithm have been able to choose the best one, which in this case is the Age.
269+
Moreover, you can see that even if we have added some new features which are not very useful/highly correlated with other features, the boosting tree algorithm was still able to choose the best one (which in this case is the Age).
303270

304-
Linear model may not be that smart in this scenario.
271+
Linear models may not perform as well.
305272

306273
Special Note: What about Random Forests™?
307274
-----------------------------------------
308275

309-
As you may know, [Random Forests](https://en.wikipedia.org/wiki/Random_forest) algorithm is cousin with boosting and both are part of the [ensemble learning](https://en.wikipedia.org/wiki/Ensemble_learning) family.
276+
As you may know, the [Random Forests](https://en.wikipedia.org/wiki/Random_forest) algorithm is cousin with boosting and both are part of the [ensemble learning](https://en.wikipedia.org/wiki/Ensemble_learning) family.
310277

311-
Both trains several decision trees for one dataset. The *main* difference is that in Random Forests, trees are independent and in boosting, the tree `N+1` focus its learning on the loss (<=> what has not been well modeled by the tree `N`).
278+
Both train several decision trees for one dataset. The *main* difference is that in Random Forests, trees are independent and in boosting, the `N+1`-st tree focuses its learning on the loss (<=> what has not been well modeled by the tree `N`).
312279

313-
This difference have an impact on a corner case in feature importance analysis: the *correlated features*.
280+
This difference can have an impact on a edge case in feature importance analysis: *correlated features*.
314281

315282
Imagine two features perfectly correlated, feature `A` and feature `B`. For one specific tree, if the algorithm needs one of them, it will choose randomly (true in both boosting and Random Forests).
316283

317-
However, in Random Forests this random choice will be done for each tree, because each tree is independent from the others. Therefore, approximatively, depending of your parameters, 50% of the trees will choose feature `A` and the other 50% will choose feature `B`. So the *importance* of the information contained in `A` and `B` (which is the same, because they are perfectly correlated) is diluted in `A` and `B`. So you won't easily know this information is important to predict what you want to predict! It is even worse when you have 10 correlated features...
284+
However, in Random Forests this random choice will be done for each tree, because each tree is independent from the others. Therefore, approximately (and depending on your parameters) 50% of the trees will choose feature `A` and the other 50% will choose feature `B`. So the *importance* of the information contained in `A` and `B` (which is the same, because they are perfectly correlated) is diluted in `A` and `B`. So you won't easily know this information is important to predict what you want to predict! It is even worse when you have 10 correlated features...
318285

319-
In boosting, when a specific link between feature and outcome have been learned by the algorithm, it will try to not refocus on it (in theory it is what happens, reality is not always that simple). Therefore, all the importance will be on feature `A` or on feature `B` (but not both). You will know that one feature have an important role in the link between the observations and the label. It is still up to you to search for the correlated features to the one detected as important if you need to know all of them.
286+
In boosting, when a specific link between feature and outcome have been learned by the algorithm, it will try to not refocus on it (in theory it is what happens, reality is not always that simple). Therefore, all the importance will be on feature `A` or on feature `B` (but not both). You will know that one feature has an important role in the link between the observations and the label. It is still up to you to search for the correlated features to the one detected as important if you need to know all of them.
320287

321288
If you want to try Random Forests algorithm, you can tweak XGBoost parameters!
322289

0 commit comments

Comments
 (0)