-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path01 decision trees.R
More file actions
339 lines (260 loc) · 9.75 KB
/
01 decision trees.R
File metadata and controls
339 lines (260 loc) · 9.75 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
library(tidymodels)
# library(rpart)
library(rpart.plot) # For plotting the decision trees
mirai::daemons(4) # For parallel processing
# Classification trees -----------------------------------------------
data("OJ", package = "ISLR")
?ISLR::OJ
glimpse(OJ)
# Which brand of orange juice was purchased?
# Base rate:
table(OJ$Purchase) |> proportions()
# There's a preference for CH!
# Split the data:
set.seed(20251201)
splits <- initial_split(OJ, prop = 0.6)
OJ.train <- training(splits)
# Splitting
OJ.comp_splits <- vfold_cv(OJ.train, v = 10) # Make 10-folds for tuning
OJ.tune_splits <- vfold_cv(OJ.train, v = 10) # Make 10-folds for comparisons
# We will use these metric:
# (For some reason, recall of MM is more important than sensitivity/precision.)
f2_meas <- metric_tweak("f2_meas", f_meas, beta = 2)
OJ_metrics <- metric_set(bal_accuracy, f2_meas, roc_auc)
# Our recipe:
rec <- recipe(Purchase ~ ., data = OJ.train) |>
step_rm(STORE)
# Decision Trees don't require dummy coding or predictor standardization (unless
# you want to do something...)
## Fitting a basic classification tree ---------------------------
OJ.tree_spec <- decision_tree(
mode = "classification",
engine = "rpart",
# Control tree depth
cost_complexity = 0,
tree_depth = 30, # Max values is 30 (default)
min_n = 5 # Default is 2
)
# All the hyperparameters control the complexity and depth of the tree:
# - cost_complexity (cp) is the complexity parameter. If set to 0, no pruning is
# done.
# - tree_depth is the maximum number of splits ALONG EACH BRANCH.
# - min_n is the minimum number of observations in a node that can be split
?details_decision_tree_rpart
translate(OJ.tree_spec)
OJ.tree_wf <- workflow(preprocessor = rec, spec = OJ.tree_spec)
OJ.tree_fit <- fit(OJ.tree_wf, data = OJ.train)
# One of the most attractive properties of trees is that they can be graphically
# displayed:
extract_fit_engine(OJ.tree_fit) |> rpart.plot(uniform = FALSE)
# The color of the nodes indicates the class prediction at that node, and it's
# saturation indicates how "pure" it is.
# It is quite hard to understand this tree - we need to prune it!
## Tree Pruning-------------------------------------------------------------
# Next, we consider whether pruning the tree might lead to improved results.
pruned.OJ.tree_spec <- decision_tree(
mode = "classification",
engine = "rpart",
cost_complexity = tune(),
tree_depth = 30,
min_n = 5
)
pruned.OJ.tree_wf <- workflow(preprocessor = rec, spec = pruned.OJ.tree_spec)
# For finding the best size for the tree using CV change the possible cp
# values for complexity parameters in the tune grid.
pruned.OJ.tree_grid <- grid_regular(
cost_complexity(range = c(-5, 0)),
levels = 30
)
pruned.OJ.tree_grid[c(1, 30), ] # We have a wide range of values
# cp specifies how the cost of a tree is penalized by the number of terminal
# nodes, resulting in a regularized cost for each tress. Small cp results in
# larger trees and potential overfitting (variance), large cp - small trees and
# potential underfitting (bias).
pruned.OJ.tree_tuner <- tune_grid(
pruned.OJ.tree_wf,
resamples = OJ.tune_splits,
grid = pruned.OJ.tree_grid,
metrics = OJ_metrics
)
autoplot(pruned.OJ.tree_tuner) +
scale_x_continuous(
transform = scales::transform_log10(),
breaks = scales::breaks_log(base = 10, n = 10),
labels = scales::label_number()
)
# See the drop in performance when cp gets too big.
(pruned.OJ.tree_params <-
select_by_one_std_err(
pruned.OJ.tree_tuner,
desc(cost_complexity),
# smaller values of cp lead to more complex models
metric = "roc_auc"
))
# Fit the final model:
pruned.OJ.tree_fit <- pruned.OJ.tree_wf |>
finalize_workflow(parameters = pruned.OJ.tree_params) |>
fit(data = OJ.train)
## Let's explore the tree:
pruned.OJ.tree_eng <- extract_fit_engine(pruned.OJ.tree_fit)
pruned.OJ.tree_eng
# In each row in the output we see:
# 1. Node index number (where node 1 is the total sample - the ROOT)
# 2. the split criterion
# 3. num. of observations under that node
# (see how nodes (2) and (3) complete each other)
# 4. the deviance - the number of obs. within the node that deviate from
# the overall prediction for that node (trees aren't perfect...)
# 5. the overall prediction for the node (MM/ CH)
# 6. in parenthesis - the proportion of observations in that node that take on
# values of No (first) or Yes (second) which actually can be calculated using
# n and deviance.
# * Branches that lead to terminal nodes are indicated using asterisks.
summary(pruned.OJ.tree_eng) # more detailed results
# We can now plot a MUCH smaller tree:
rpart.plot(
pruned.OJ.tree_eng,
type = 2,
extra = 104,
# Should the length of the branches NOT be spaced proportionally to
# the fit improvement?
uniform = TRUE
)
# In each node we get:
# - Predicted class (also corresponds to the color)
# - Class proportions in the node (also corresponds to the saturation of color)
# - % of sample in that node/branch
# (When uniform = FALSE) we also get a visual indication of the value of each
# split in improving the model's fit.
# We can summarize this information by predictor, using an variable importance
# plot (VIP):
vip::vip(pruned.OJ.tree_eng, method = "model", num_features = 20)
# A variable's importance is the sum of the goodness of split measures for each
# split for which it was the primary variable + (goodness * agreement) for all
# splits in which it was a surrogate (=when it was correlated with a different
# split on another variable).
# We will discuss a general framework for estimating variables' importance later
# in the semester.
## Select a model ---------------------------------
# Let's use CV to compare the trees:
OJ.tree_resamps <- fit_resamples(
OJ.tree_wf,
resamples = OJ.comp_splits,
metrics = OJ_metrics
)
pruned.OJ.tree_resamps <- fit_resamples(
pruned.OJ.tree_fit,
resamples = OJ.comp_splits,
metrics = OJ_metrics
)
OJ_resamps_metrics <- bind_rows(
"tree" = collect_metrics(OJ.tree_resamps, summarize = FALSE),
"pruned" = collect_metrics(pruned.OJ.tree_resamps, summarize = FALSE),
.id = "Model"
) |>
group_by(id, .metric) |>
mutate(
best_is = Model[which.max(.estimate)]
) |>
ungroup()
ggplot(OJ_resamps_metrics, aes(Model, .estimate, color = Model)) +
facet_wrap(~.metric, scales = "free") +
geom_line(aes(group = id, color = best_is)) +
geom_point() +
stat_summary(
aes(fill = Model),
geom = "point",
size = 3,
shape = 21,
color = "black"
)
# We can see that the pruned tree was better across most folds/metrics!
## Test set -----------------------------------
OJ.test_predictions.pruned.tree <- augment(
pruned.OJ.tree_fit,
new_data = testing(splits) # Get the test set
)
OJ.test_predictions.pruned.tree |> conf_mat(Purchase, .pred_class)
# Models seem to give different predictions...
OJ.test_predictions.pruned.tree |>
OJ_metrics(Purchase, estimate = .pred_class, .pred_CH)
OJ.test_predictions.pruned.tree |>
roc_curve(Purchase, .pred_CH) |>
autoplot()
# Regression trees --------------------------------------------------
# we also have regression problems!
data(Boston, package = "MASS")
?MASS::Boston
glimpse(Boston)
# We won't be splitting the data into test/train for this example.
# Split for CV (tune)
Boston.folds <- vfold_cv(Boston, v = 10) # Make 10-folds for CV
# The data records medv (median house value) for 506 neighborhoods around
# Boston. We will seek to predict medv using 13 predictors such as:
# rm = average number of rooms per house;
# age = average age of houses;
# lstat = percent of households with low socioeconomic status.
rec <- recipe(medv ~ ., data = Boston)
## Tune ----------------------------------------------------------------
# The processes fitting and Evaluation of a Regression Tree are essentially the
# same.
Boston.tree_spec <- decision_tree(
mode = "regression",
engine = "rpart",
cost_complexity = tune(),
tree_depth = 30,
min_n = 5
)
Boston.tree_wf <- workflow(preprocessor = rec, spec = Boston.tree_spec)
Boston.tree_grid <- grid_regular(
cost_complexity(range = c(-5, 0)),
levels = 20
)
Boston.tree_tuned <- tune_grid(
Boston.tree_wf,
resamples = Boston.folds,
grid = Boston.tree_grid
)
autoplot(Boston.tree_tuned) +
scale_x_continuous(
transform = scales::transform_log10(),
breaks = scales::breaks_log(base = 10),
labels = scales::label_number()
)
# Fit the final model:
Boston.tree_fit <- Boston.tree_wf |>
finalize_workflow(
parameters = select_best(Boston.tree_tuned, metric = "rmse")
) |>
fit(data = Boston)
## Explore the pruned tree ---------------------------------
Boston.tree_eng <- extract_fit_engine(Boston.tree_fit)
Boston.tree_eng
# In each row in the output we see:
# 1. Node index number (where node 1 is the total sample - the ROOT)
# 2. the split criterion
# 3. num. of observations under that node
# (see how nodes (2) and (3) complete each other)
# 4. the deviance (variance) within that node (trees aren't perfect...)
# 5. the overall prediction for the node (Yes/ No)
# * Branches that lead to terminal nodes are indicated using asterisks.
summary(Boston.tree_eng) # more detailed results
# We can now plot a MUCH smaller tree:
rpart.plot(
Boston.tree_eng,
type = 2,
extra = 101,
# Should the length of the branches NOT be spaced proportionally to
# the fit improvement?
uniform = TRUE
)
# In each node we get:
# - Predicted class (also corresponds to the color)
# - % of sample in that node/branch
# Again, (when uniform = FALSE) we also get a visual indication of the value of
# each split in improving the model's fit.
# We can summarize this information by predictor, using an variable importance
# plot (VIP):
vip::vip(Boston.tree_eng, method = "model")
# The most important splits occur along the "rm" predictor.
# Note that not all 13 predictors appear.