-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecision Trees Part 2.Rmd
265 lines (189 loc) · 10.6 KB
/
Decision Trees Part 2.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
---
title: "Decision Trees"
author: "Dr. Christian Haas"
date: "September 20, 2020"
output: html_document
editor_options:
chunk_output_type: console
---
This section covers various decision tree methodologies.
## Bagging and Random Forests
As discussed, Bagging is a powerful concept that creates multiple, large decision trees based on bootstrapped data sets and combines them for a prediction.
```{r random-forest}
# new: let's parallelize things. thanks to the caret package, we only need the following four lines to fully parallelize the model training
library(doParallel)
num_cores <- detectCores() #note: you can specify a smaller number if you want
cl <- makePSOCKcluster(num_cores)
registerDoParallel(cl)
# note: as always when creating parallel threads, we should close them before we leave the program:
# stopImplicitCluster() # call this when you're done with your code
library(randomForest)
library(pROC)
library(caret)
library(tidyverse)
library(tidymodels)
# set your working directory to the current file directory
tryCatch({
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
}, error=function(cond){message(paste("cannot change working directory"))
})
# first, let's load the util functions
source("../Utils.R")
set.seed(1)
# let's use the heart data set again
heart <- read_csv("Heart.csv")
dataset <- NULL
dataset <- prepare_heart(heart)
target_var <- 'AHD'
# note: we can specify the formula like this. if you specify individual predictors, they have to match the column names in the dataset
model_form <- AHD ~ Age + Sex + RestBP + Chol + Ca + Thal
model_type <- "rf"
positive_class <- "Yes"
negative_class <- "No"
trainIndex <- createDataPartition(dataset[[target_var]], p = 0.8, list = FALSE)
data_train <- dataset %>% slice(trainIndex)
data_test <- dataset %>% slice(-trainIndex)
model_recipe <- recipe(model_form, data = data_train) %>%
step_novel(all_predictors(), -all_numeric()) %>%
step_unknown(all_predictors(), -all_numeric()) %>%
step_dummy(all_nominal(), -all_outcomes()) %>%
step_zv(all_predictors())
# we will use a 10-fold cross validation on the training set
trControl <- trainControl(method = 'cv', savePredictions = TRUE, classProbs = TRUE, summaryFunction = twoClassSummary)
rf_heart <- train(model_recipe, data = data_train, method = model_type, trControl = trControl, metric = 'ROC')
rf_heart
# textual summary of the outcome
rf_heart$finalModel
confusionMatrix(rf_heart)
confusionMatrix(rf_heart$pred$pred, rf_heart$pred$obs)
rf_heart_pred <- rf_heart %>% predict(newdata = data_train)
cf <- confusionMatrix(rf_heart_pred, data_train[[target_var]])
cf$overall[1]
# for variable importance, we can look into following functions
importance(rf_heart$finalModel)
varImpPlot(rf_heart$finalModel)
# let's predict its performance on the validation / test data
rf_heart_pred <- rf_heart %>% predict(newdata = data_test, type = 'raw')
confusionMatrix(rf_heart_pred, data_test[[target_var]], positive = positive_class)
# alternatively, check other thresholds
threshold <- 0.5
rf_heart_probs <- rf_heart %>% predict(newdata = data_test, type = 'prob')
rf_heart_pred <- factor(ifelse(rf_heart_probs[, positive_class] > threshold, positive_class, negative_class) , levels = levels(dataset[[target_var]]))
confusionMatrix(rf_heart_pred, data_test[[target_var]], positive = positive_class)
# sidenote: for some model parameters, we can use the tuneGrid function of caret to include in the model building process. for allowed parameters that can be used for this, use modelLookop('model.name')
modelLookup('rf')
# option 1: random search
# we will use a 10-fold cross validation on the training set to select the best complexity parameter
trControl <- trainControl(method = 'cv', number = 10, savePredictions = TRUE, classProbs = TRUE, summaryFunction = twoClassSummary, search = 'random')
rf_heart_random <- train(model_recipe, data = data_train, method = model_type, trControl = trControl, metric = 'ROC', tuneLength = 10)
rf_heart_random
plot(rf_heart_random)
# let's predict its performance on the validation / test data
rf_heart_random_pred <- rf_heart_random %>% predict(newdata = data_test, type = 'raw')
confusionMatrix(rf_heart_random_pred, data_test[[target_var]], positive = positive_class)
# option 2: grid search
# we will use a 10-fold cross validation on the training set to select the best complexity parameter
trControl <- trainControl(method = 'cv', number = 10, savePredictions = TRUE, classProbs = TRUE, summaryFunction = twoClassSummary, search = 'grid')
# we also set up a grid search. note: you need to find valid values for the parameter in this case
tGrid <- expand.grid(mtry = c(1:10))
# sidenote: the randomForest package provides additional parameters that can be tuned, e.g., the number of trees
# we can include them here as well!
rf_heart_grid <- train(model_recipe, data = data_train, method = model_type, trControl = trControl, metric = 'ROC', tuneGrid = tGrid, ntree = 1000)
rf_heart_grid
# we can plot the results of the grid search (for the mtry parameter)
plot(rf_heart_grid)
# let's predict its performance on the validation / test data
rf_heart_grid_pred <- rf_heart_grid %>% predict(newdata = data_test, type = 'raw')
confusionMatrix(rf_heart_grid_pred, data_test[[target_var]], positive = positive_class)
# side note: we can evaluate the performance over different threshold
thresholds <- seq(0.1,0.9,0.1)
thresholder(rf_heart_grid, thresholds)
```
## Hands-on Session 1
Let's use a random forest to build a model for the titanic data set.
Use a split between training and test (or cross validation), try different parameters, and see how well you can predict whether a passenger survives or not.
```{r hands-on1}
titanic <- read_csv("titanic.csv")# read data
dataset <- NULL
dataset <- prepare_titanic(titanic)
target_var <- 'survived'
model_form <- survived ~ sex + age + sibsp + parch + fare + embarked
positive_class = 'Yes'
negative_class = 'No'
model_type <- 'rf'
```
## Boosting
Finally, let's try a gradient boosting tree (also called gradient boosting machine, gbm).
Note that gbms are often defined for numeric variables, not for categorical. When using gbms with categorical variables, the results might not be perfect.
```{r boosting}
library(xgboost)
heart <- read_csv("Heart.csv")
dataset <- NULL
dataset <- prepare_heart(heart)
target_var <- 'AHD'
# note: we can specify the formula like this. if you specify individual predictors, they have to match the column names in the dataset
model_form <- AHD ~ Age + Sex + RestBP + Chol + Ca
model_type <- 'xgbTree'
positive_class <- "Yes"
negative_class <- "No"
set.seed(1)
trainIndex <- createDataPartition(dataset[[target_var]], p = 0.8, list = FALSE)
data_train <- dataset %>% dplyr::slice(trainIndex)
data_test <- dataset %>% dplyr::slice(-trainIndex)
# we will use a 10-fold cross validation on the training set
trControl <- trainControl(method = 'cv', savePredictions = TRUE, classProbs = TRUE, summaryFunction = twoClassSummary)
model_recipe <- recipe(model_form, data = data_train) %>%
step_novel(all_predictors(), -all_numeric()) %>%
step_unknown(all_predictors(), -all_numeric()) %>%
step_dummy(all_nominal(), -all_outcomes()) %>%
step_zv(all_predictors())
xgb_heart <- train(model_recipe, data = data_train, method = model_type, trControl = trControl, metric = 'ROC')
# textual summary of the outcome
xgb_heart
summary(xgb_heart$finalModel)
# let's predict its performance on the validation / test data
xgb_heart_pred <- xgb_heart %>% predict(newdata = data_test, type = 'raw')
xgb_heart_probs <- xgb_heart %>% predict(newdata = data_test, type = 'prob')
confusionMatrix(xgb_heart_pred, data_test[[target_var]], positive = positive_class)
# ROC curve
roc(data_test[[target_var]], xgb_heart_probs[, positive_class], plot = TRUE, print.auc = TRUE, legacy.axes = TRUE, levels = c(negative_class, positive_class))
#
# # excursus 1: visualizing single trees (not very intuitive / recommended for Boosted Trees)
# library(DiagrammeR)
# xgb.plot.tree(model = xgb_heart$finalModel, tree = c(1)) # first tree
# xgb.plot.multi.trees(model = xgb_heart$finalModel) # representation of all trees
# then, let's add parameter tuning
modelLookup('xgbTree')
trControl <- trainControl(method = 'cv', number = 10, savePredictions = TRUE, classProbs = TRUE, search = 'grid')
tGrid <- expand.grid(nrounds = seq(10,100,10),
max_depth = c(1, 3, 5, 7),
eta = c(0.001,0.01,0.1),
gamma = c(0),
colsample_bytree = c(1),
min_child_weight = c(1),
subsample = c(1))
trControl <- trainControl(method = 'cv', savePredictions = TRUE, classProbs = TRUE, summaryFunction = twoClassSummary, search = 'grid')
xgb_heart <- train(model_recipe, data = data_train, method = model_type, trControl = trControl, metric = 'ROC', tuneGrid = tGrid, verbose = FALSE)
# alternative: random search
trControl <- trainControl(method = 'cv', savePredictions = TRUE, classProbs = TRUE, summaryFunction = twoClassSummary, search = 'random')
xgb_heart_randomSearch <- train(model_recipe, data = data_train, method = model_type, trControl = trControl, metric = 'ROC', tuneLength = 50, verbose = FALSE)
# textual summary of the outcome
xgb_heart
summary(xgb_heart$finalModel)
# let's predict its performance on the validation / test data
xgb_heart_pred <- xgb_heart %>% predict(newdata = data_test, type = 'raw')
xgb_heart_probs <- xgb_heart %>% predict(newdata = data_test, type = 'prob')
confusionMatrix(xgb_heart_pred, data_test[[target_var]], positive = positive_class)
# ROC curve
roc(data_test[[target_var]], xgb_heart_probs[, positive_class], plot = TRUE, print.auc = TRUE, legacy.axes = TRUE, levels = c(negative_class, positive_class))
# excursus 2: we can also compare it with another model, e.g. random forest
# re-create random forest:
rf_heart <- train(model_recipe, data = data_train, method = 'rf', trControl = trControl, metric = 'ROC')
# let's predict its performance on the validation / test data
rf_heart_probs <- rf_heart %>% predict(newdata = data_test, type = 'prob')
roc_heart <- plot(roc(data_test[[target_var]], rf_heart_probs[, positive_class]), print.auc = TRUE, col = "blue")
roc_heart <- plot(roc(data_test[[target_var]], xgb_heart_probs[, positive_class]), print.auc = TRUE,
col = "green", print.auc.y = .4, add = TRUE)
# we should close / stop the parallel clusters once we're done
stopImplicitCluster()
```