1 Classification Trees

We use tree package to grow classification and regression trees. This example uses Carseats data set. Sales is recorded as a categorical variable using 8 as the cutoff point.

library(tree)
library(ISLR)
Carseats$High <- factor(ifelse(Carseats$Sales<=8,"No","Yes")) 
tree.carseats <- tree(High ~ . -Sales, Carseats)
summary(tree.carseats) 
## 
## Classification tree:
## tree(formula = High ~ . - Sales, data = Carseats)
## Variables actually used in tree construction:
## [1] "ShelveLoc"   "Price"       "Income"      "CompPrice"   "Population" 
## [6] "Advertising" "Age"         "US"         
## Number of terminal nodes:  27 
## Residual mean deviance:  0.4575 = 170.7 / 373 
## Misclassification error rate: 0.09 = 36 / 400

The training error rate is 9%. The deviance is defined as:
\[-2\sum_m\sum_k n_{mk}log\hat{p}_{mk}\] where \(n_{mk}\), is the number of observations in class \(k\) and terminal node \(m\). Smaller deviance values imply more successful classification. In the output above, the Residual mean deviance is found by dividing the deviance by \(n-T_0\) (the number of observations minus the number of terminal nodes, 400-27).

plot(tree.carseats)
text(tree.carseats,pretty=0)

The most important indicator of Sales appears to be shelving location, since the first branch differentiates Good locations from Bad and Medium locations.

To see the details of the tree:

tree.carseats
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
##   1) root 400 541.500 No ( 0.59000 0.41000 )  
##     2) ShelveLoc: Bad,Medium 315 390.600 No ( 0.68889 0.31111 )  
##       4) Price < 92.5 46  56.530 Yes ( 0.30435 0.69565 )  
##         8) Income < 57 10  12.220 No ( 0.70000 0.30000 )  
##          16) CompPrice < 110.5 5   0.000 No ( 1.00000 0.00000 ) *
##          17) CompPrice > 110.5 5   6.730 Yes ( 0.40000 0.60000 ) *
##         9) Income > 57 36  35.470 Yes ( 0.19444 0.80556 )  
##          18) Population < 207.5 16  21.170 Yes ( 0.37500 0.62500 ) *
##          19) Population > 207.5 20   7.941 Yes ( 0.05000 0.95000 ) *
##       5) Price > 92.5 269 299.800 No ( 0.75465 0.24535 )  
##        10) Advertising < 13.5 224 213.200 No ( 0.81696 0.18304 )  
##          20) CompPrice < 124.5 96  44.890 No ( 0.93750 0.06250 )  
##            40) Price < 106.5 38  33.150 No ( 0.84211 0.15789 )  
##              80) Population < 177 12  16.300 No ( 0.58333 0.41667 )  
##               160) Income < 60.5 6   0.000 No ( 1.00000 0.00000 ) *
##               161) Income > 60.5 6   5.407 Yes ( 0.16667 0.83333 ) *
##              81) Population > 177 26   8.477 No ( 0.96154 0.03846 ) *
##            41) Price > 106.5 58   0.000 No ( 1.00000 0.00000 ) *
##          21) CompPrice > 124.5 128 150.200 No ( 0.72656 0.27344 )  
##            42) Price < 122.5 51  70.680 Yes ( 0.49020 0.50980 )  
##              84) ShelveLoc: Bad 11   6.702 No ( 0.90909 0.09091 ) *
##              85) ShelveLoc: Medium 40  52.930 Yes ( 0.37500 0.62500 )  
##               170) Price < 109.5 16   7.481 Yes ( 0.06250 0.93750 ) *
##               171) Price > 109.5 24  32.600 No ( 0.58333 0.41667 )  
##                 342) Age < 49.5 13  16.050 Yes ( 0.30769 0.69231 ) *
##                 343) Age > 49.5 11   6.702 No ( 0.90909 0.09091 ) *
##            43) Price > 122.5 77  55.540 No ( 0.88312 0.11688 )  
##              86) CompPrice < 147.5 58  17.400 No ( 0.96552 0.03448 ) *
##              87) CompPrice > 147.5 19  25.010 No ( 0.63158 0.36842 )  
##               174) Price < 147 12  16.300 Yes ( 0.41667 0.58333 )  
##                 348) CompPrice < 152.5 7   5.742 Yes ( 0.14286 0.85714 ) *
##                 349) CompPrice > 152.5 5   5.004 No ( 0.80000 0.20000 ) *
##               175) Price > 147 7   0.000 No ( 1.00000 0.00000 ) *
##        11) Advertising > 13.5 45  61.830 Yes ( 0.44444 0.55556 )  
##          22) Age < 54.5 25  25.020 Yes ( 0.20000 0.80000 )  
##            44) CompPrice < 130.5 14  18.250 Yes ( 0.35714 0.64286 )  
##              88) Income < 100 9  12.370 No ( 0.55556 0.44444 ) *
##              89) Income > 100 5   0.000 Yes ( 0.00000 1.00000 ) *
##            45) CompPrice > 130.5 11   0.000 Yes ( 0.00000 1.00000 ) *
##          23) Age > 54.5 20  22.490 No ( 0.75000 0.25000 )  
##            46) CompPrice < 122.5 10   0.000 No ( 1.00000 0.00000 ) *
##            47) CompPrice > 122.5 10  13.860 No ( 0.50000 0.50000 )  
##              94) Price < 125 5   0.000 Yes ( 0.00000 1.00000 ) *
##              95) Price > 125 5   0.000 No ( 1.00000 0.00000 ) *
##     3) ShelveLoc: Good 85  90.330 Yes ( 0.22353 0.77647 )  
##       6) Price < 135 68  49.260 Yes ( 0.11765 0.88235 )  
##        12) US: No 17  22.070 Yes ( 0.35294 0.64706 )  
##          24) Price < 109 8   0.000 Yes ( 0.00000 1.00000 ) *
##          25) Price > 109 9  11.460 No ( 0.66667 0.33333 ) *
##        13) US: Yes 51  16.880 Yes ( 0.03922 0.96078 ) *
##       7) Price > 135 17  22.070 No ( 0.64706 0.35294 )  
##        14) Income < 46 6   0.000 No ( 1.00000 0.00000 ) *
##        15) Income > 46 11  15.160 Yes ( 0.45455 0.54545 ) *

In the output above, R displays the split criterion (e.g. Price < 92.5), the number of observations in that branch, the deviance, the overall prediction for the branch (Yes or No), and the fraction of observations in that branch that take on values of Yes and No. Branches that lead to terminal nodes are indicated using asterisks.

Computing the test error:

set.seed(2)
train <- sample(1:nrow(Carseats), 200)
Carseats.test <- Carseats[-train,]
High.test <- Carseats$High[-train]
tree.carseats <- tree(High ~ . -Sales, Carseats, subset=train)
tree.pred <- predict(tree.carseats, Carseats.test, type="class")
table(tree.pred, High.test)
##          High.test
## tree.pred  No Yes
##       No  104  33
##       Yes  13  50
# correct prediction rate
(104+50)/200
## [1] 0.77

Pruning the tree using cross-validation using cv.tree() function:

set.seed(11)
cv.carseats <- cv.tree(tree.carseats, FUN=prune.misclass)
names(cv.carseats)
## [1] "size"   "dev"    "k"      "method"
cv.carseats
## $size
## [1] 21 19 14  9  8  5  3  2  1
## 
## $dev
## [1] 79 79 77 76 74 75 79 76 82
## 
## $k
## [1] -Inf  0.0  1.0  1.4  2.0  3.0  4.0  9.0 18.0
## 
## $method
## [1] "misclass"
## 
## attr(,"class")
## [1] "prune"         "tree.sequence"

In the output above, dev is the cross-validation error and k is the tuning parameter \(\alpha\) and size is the number of terminal nodes (tree size). The minimum cv error is 74 and achieved by the model with 8 terminal nodes.

par(mfrow=c(1,2))
plot(cv.carseats$size,cv.carseats$dev,type="b")
plot(cv.carseats$k,cv.carseats$dev,type="b")

We now apply the prune.misclass() function in order to prune the tree obtain the 8-node tree.

prune.carseats <- prune.misclass(tree.carseats, best=8)
plot(prune.carseats)
text(prune.carseats,pretty=0)

In the text book, a 9-node tree is fitted instead:

prune.carseats <- prune.misclass(tree.carseats, best=9)
plot(prune.carseats)
text(prune.carseats,pretty=0)

How well does this pruned tree perform on the test data set? Once again, we apply the predict() function.

tree.pred <- predict(prune.carseats, Carseats.test, type="class")
table(tree.pred,High.test)
##          High.test
## tree.pred No Yes
##       No  97  25
##       Yes 20  58
(97+58)/200
## [1] 0.775

2 Regression Trees

We fit a regression tree to the Boston data set. First, we create a training set, and fit the tree to the training data.

library(ISLR2)
set.seed(81)
train <- sample(1:nrow(Boston), nrow(Boston)/2)
tree.boston <- tree(medv ~ ., Boston, subset=train)
summary(tree.boston)
## 
## Regression tree:
## tree(formula = medv ~ ., data = Boston, subset = train)
## Variables actually used in tree construction:
## [1] "lstat" "rm"    "age"   "nox"   "crim" 
## Number of terminal nodes:  8 
## Residual mean deviance:  14.56 = 3568 / 245 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -14.5300  -1.7920  -0.1923   0.0000   1.9080  12.1700

Note that only 4 variables are used to construct the tree: “rm” “lstat” “crim” “age”

plot(tree.boston)
text(tree.boston,pretty=0)

The variable lstat measures the percentage of individuals with lower socioeconomic status. The tree indicates that lower values of lstat correspond to more expensive houses.

Variable definitions in Boston data set:

# ?Boston
crim
per capita crime rate by town.

zn
proportion of residential land zoned for lots over 25,000 sq.ft.

indus
proportion of non-retail business acres per town.

chas
Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).

nox
nitrogen oxides concentration (parts per 10 million).

rm
average number of rooms per dwelling.

age
proportion of owner-occupied units built prior to 1940.

dis
weighted mean of distances to five Boston employment centres.

rad
index of accessibility to radial highways.

tax
full-value property-tax rate per $10,000.

ptratio
pupil-teacher ratio by town.

lstat
lower status of the population (percent).

medv
median value of owner-occupied homes in $1000s.

Pruning the tree:

cv.boston <- cv.tree(tree.boston)
plot(cv.boston$size, cv.boston$dev, type='b')

In this case, the most complex tree is selected by cross-validation. However, if we wish to prune the tree, we could do so as follows, using the prune.tree() function:

prune.boston <- prune.tree(tree.boston, best=5)
plot(prune.boston)
text(prune.boston,pretty=0)

In keeping with the cross-validation results, we use the unpruned tree to make predictions on the test set.

yhat <- predict(tree.boston,newdata=Boston[-train,])
boston.test <- Boston[-train,"medv"]
plot(yhat,boston.test)
abline(0,1)

mean((yhat-boston.test)^2)
## [1] 18.92867

The test set MSE associated with the regression tree is 18.93. The square root of the MSE is therefore around 4.351, indicating that this model leads to test predictions that are within around $4351 of the true median home value for the suburb.

3 Bagging and Random Forests

Here we apply bagging and random forests to the Boston data, using the randomForest package in R.

Recall that bagging is simply a special case of a random forest with m = p. Therefore, the randomForest() function can be used to perform both random forests and bagging. We perform bagging as follows:

library(randomForest)
set.seed(1)
bag.boston <- randomForest(medv ~ ., data = Boston, 
                           subset = train, mtry=13, importance=TRUE)
bag.boston
## 
## Call:
##  randomForest(formula = medv ~ ., data = Boston, mtry = 13, importance = TRUE,      subset = train) 
##                Type of random forest: regression
##                      Number of trees: 500
## No. of variables tried at each split: 12
## 
##           Mean of squared residuals: 11.62921
##                     % Var explained: 86.37

The argument mtry=13 indicates that all 13 predictors should be considered for each split of the tree—in other words, that bagging should be done. How well does this bagged model perform on the test set

yhat.bag <- predict(bag.boston, newdata = Boston[-train,])
plot(yhat.bag, boston.test)
abline(0,1)

mean((yhat.bag-boston.test)^2)
## [1] 10.14149

Test MSE = 10.13872

We could change the number of trees grown by randomForest() using the ntree argument:

bag.boston <- randomForest(medv ~ ., data = Boston, 
                           subset = train, mtry = 13, ntree = 25)
yhat.bag <- predict(bag.boston,newdata=Boston[-train,])
mean((yhat.bag-boston.test)^2)
## [1] 10.08161

Growing a random forest proceeds in exactly the same way, except that we use a smaller value of the mtry argument. By default, randomForest() uses p/3 variables when building a random forest of regression trees, and \(\sqrt{p}\) variables when building a random forest of classification trees. Here we use mtry = 6.

set.seed(1)
rf.boston <- randomForest(medv ~ ., data = Boston, 
                          subset = train, mtry = 6, importance = TRUE)
yhat.rf <- predict(rf.boston, newdata = Boston[-train,])
mean((yhat.rf-boston.test)^2)
## [1] 9.767046

Random forest yields slight improvement.

Using the importance() function, we can view the importance of each variable.

importance(rf.boston)
##            %IncMSE IncNodePurity
## crim    12.3963632    1176.77154
## zn       0.2828879      39.39006
## indus    8.2924633     539.68381
## chas     1.4477478      86.95147
## nox     17.9315688     980.62287
## rm      32.4871323    6447.42744
## age      7.3497736     561.91044
## dis     16.6038728    1664.20501
## rad      6.0340280     141.39613
## tax      9.8697640     548.66647
## ptratio 11.5308715     912.44828
## lstat   32.3142107    8206.00486
varImpPlot(rf.boston)

The results indicate that across all of the trees considered in the random forest, the wealth level of the community (lstat) and the house size (rm) are by far the two most important variables.

4 Boosting

Here we use the gbm package, and within it the gbm() function, to fit boosted regression trees to the Boston data set. We run gbm() with the option distribution="gaussian" since this is a regression problem; if it were a binary classification problem, we would use distribution="bernoulli". The argument n.trees=5000 indicates that we want 5000 trees, and the option interaction.depth=4 limits the depth of each tree.

library(gbm)
set.seed(1)
boost.boston <- gbm(medv ~ ., data = Boston[train,], distribution = "gaussian", 
                    n.trees = 5000, interaction.depth = 4)
summary(boost.boston)

##             var    rel.inf
## lstat     lstat 42.7871005
## rm           rm 22.5711360
## dis         dis 14.0033039
## crim       crim  7.7586220
## nox         nox  3.8844102
## age         age  3.1733743
## tax         tax  1.9136013
## ptratio ptratio  1.5475300
## chas       chas  0.8726876
## indus     indus  0.7602431
## rad         rad  0.5607886
## zn           zn  0.1672025

The summary() function produces a relative influence plot and also outputs the relative influence statistics.

We see that lstat and rm are by far the most important variables. We can also produce partial dependence plots for these two variables. These plots illustrate the marginal effect of the selected variables on the response after integrating out the other variables. In this case, as we might expect, median house prices are increasing with rm and decreasing with lstat.

par(mfrow=c(1,2))
plot(boost.boston,i="rm")

plot(boost.boston,i="lstat")

We now use the boosted model to predict medv on the test set:

yhat.boost <- predict(boost.boston,newdata=Boston[-train,],n.trees=5000)
mean((yhat.boost-boston.test)^2)
## [1] 11.88697

The test MSE obtained is 11.8; similar to the test MSE for random forests and superior to that for bagging. If we want to, we can perform boosting with a different value of the shrinkage parameter λ in (8.10). The default value is 0.001, but this is easily modified. Here we take λ = 0.2.

boost.boston <- gbm(medv~.,data=Boston[train,],
                    distribution="gaussian",n.trees=5000,
                    interaction.depth=4,shrinkage=0.2,verbose=F)
yhat.boost <- predict(boost.boston,newdata=Boston[-train,],n.trees=5000)
mean((yhat.boost-boston.test)^2)
## [1] 14.0076

The MSE with λ = 0.2 is higher.

5 Using Tidymodels

We continue using Boston data set to illustrate the usage of Tidymodels tools to estimate regression trees.

First, load the packages and determine train and test sets using medv as the stratification variable.

library(ISLR2)
library(tidyverse)
library(tidymodels)

# determine training and test sets
# 75% train, 25% test, with stratified sampling based on medv

set.seed(135)
boston_split <- initial_split(Boston, 
                              prop = 0.75, 
                              strata = medv)

boston_train <- boston_split |>  training()

boston_test <- boston_split |>  testing()

Then set the engine and the tuning parameters:

# train a decision tree 
dt_model <- decision_tree() |> 
  set_engine('rpart') |>  
  set_mode('regression')

# lets do some parameter tuning 
dt_tune_model <- decision_tree(cost_complexity = tune(),
                               tree_depth = tune(),
                               min_n = tune()) |>
  set_engine('rpart') |> 
  set_mode('regression')

dt_tune_model
## Decision Tree Model Specification (regression)
## 
## Main Arguments:
##   cost_complexity = tune()
##   tree_depth = tune()
##   min_n = tune()
## 
## Computational engine: rpart

Let’s create a grid of hyperparameters:

# create a grid for hyperparameters
set.seed(12345)
dt_grid <- grid_random(parameters(dt_tune_model), size = 5)
dt_grid
## # A tibble: 5 × 3
##   cost_complexity tree_depth min_n
##             <dbl>      <int> <int>
## 1      0.000308            8     3
## 2      0.00762            10    23
## 3      0.000706           13    12
## 4      0.00944            11    39
## 5      0.00000128          8    40

Now we can use 5-fold cross-validation to select the best hyperparameters.

# determine CV folds
set.seed(12345)
boston_folds <- vfold_cv(boston_train,
                        v = 5,
                        strata = medv)
boston_folds
## #  5-fold cross-validation using stratification 
## # A tibble: 5 × 2
##   splits           id   
##   <list>           <chr>
## 1 <split [301/77]> Fold1
## 2 <split [302/76]> Fold2
## 3 <split [302/76]> Fold3
## 4 <split [303/75]> Fold4
## 5 <split [304/74]> Fold5

Define a recipe for the regression tree:

# use all variables without any transformation
boston_recipe <- recipe(medv ~ ., 
                        data = boston_train)
boston_recipe
# create workflow 
boston_wkfl <- workflow()  |> 
  add_model(dt_tune_model)  |> 
  add_recipe(boston_recipe)
# apply decision tree algorithm to all CV folds
dt_tuning <- boston_wkfl  |> 
  tune_grid(resamples = boston_folds,
            grid = dt_grid)

dt_tuning  |>  collect_metrics()
## # A tibble: 10 × 9
##    cost_complexity tree_depth min_n .metric .estimator  mean     n std_err
##              <dbl>      <int> <int> <chr>   <chr>      <dbl> <int>   <dbl>
##  1      0.000308            8     3 rmse    standard   4.02      5  0.398 
##  2      0.000308            8     3 rsq     standard   0.828     5  0.0230
##  3      0.00762            10    23 rmse    standard   4.41      5  0.199 
##  4      0.00762            10    23 rsq     standard   0.772     5  0.0241
##  5      0.000706           13    12 rmse    standard   4.28      5  0.233 
##  6      0.000706           13    12 rsq     standard   0.795     5  0.0234
##  7      0.00944            11    39 rmse    standard   4.41      5  0.324 
##  8      0.00944            11    39 rsq     standard   0.767     5  0.0355
##  9      0.00000128          8    40 rmse    standard   4.10      5  0.282 
## 10      0.00000128          8    40 rsq     standard   0.799     5  0.0305
## # ℹ 1 more variable: .config <chr>
# detailed information on hyperparameters
dt_tuning |> 
  collect_metrics(summarize = FALSE) |> 
  filter(.metric == 'rmse') |> 
  group_by(id) |> 
  summarize(min_rmse = min(.estimate),
            median_rmse = median(.estimate),
            max_rmse = max(.estimate))
## # A tibble: 5 × 4
##   id    min_rmse median_rmse max_rmse
##   <chr>    <dbl>       <dbl>    <dbl>
## 1 Fold1     3.96        4.27     5.14
## 2 Fold2     4.24        4.42     4.76
## 3 Fold3     3.00        3.68     3.93
## 4 Fold4     3.32        4.21     4.62
## 5 Fold5     3.25        4.98     5.34
# which one is the best?
dt_tuning |> 
  show_best(metric = 'rmse', n = 5)
## # A tibble: 5 × 9
##   cost_complexity tree_depth min_n .metric .estimator  mean     n std_err
##             <dbl>      <int> <int> <chr>   <chr>      <dbl> <int>   <dbl>
## 1      0.000308            8     3 rmse    standard    4.02     5   0.398
## 2      0.00000128          8    40 rmse    standard    4.10     5   0.282
## 3      0.000706           13    12 rmse    standard    4.28     5   0.233
## 4      0.00944            11    39 rmse    standard    4.41     5   0.324
## 5      0.00762            10    23 rmse    standard    4.41     5   0.199
## # ℹ 1 more variable: .config <chr>
dt_tuning |> 
  show_best(metric = 'rsq', n = 5)
## # A tibble: 5 × 9
##   cost_complexity tree_depth min_n .metric .estimator  mean     n std_err
##             <dbl>      <int> <int> <chr>   <chr>      <dbl> <int>   <dbl>
## 1      0.000308            8     3 rsq     standard   0.828     5  0.0230
## 2      0.00000128          8    40 rsq     standard   0.799     5  0.0305
## 3      0.000706           13    12 rsq     standard   0.795     5  0.0234
## 4      0.00762            10    23 rsq     standard   0.772     5  0.0241
## 5      0.00944            11    39 rsq     standard   0.767     5  0.0355
## # ℹ 1 more variable: .config <chr>

Minimum RMSE is obtained by the following tuning parameters:

best_dt_model <- dt_tuning |> 
  select_best(metric = 'rmse')
best_dt_model
## # A tibble: 1 × 4
##   cost_complexity tree_depth min_n .config             
##             <dbl>      <int> <int> <chr>               
## 1        0.000308          8     3 Preprocessor1_Model1
# finalize the workflow (fixes the hyperparameters)
final_boston_wkfl <- boston_wkfl |> 
  finalize_workflow(best_dt_model)
final_boston_wkfl
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Recipe
## Model: decision_tree()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## 0 Recipe Steps
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Decision Tree Model Specification (regression)
## 
## Main Arguments:
##   cost_complexity = 0.000307705363504858
##   tree_depth = 8
##   min_n = 3
## 
## Computational engine: rpart

Finally, obtain the test RMSE:

# train the decision tree 
boston_final_fit <- final_boston_wkfl |> 
  last_fit(split = boston_split)
boston_final_fit |> 
  collect_metrics()
## # A tibble: 2 × 4
##   .metric .estimator .estimate .config             
##   <chr>   <chr>          <dbl> <chr>               
## 1 rmse    standard       4.72  Preprocessor1_Model1
## 2 rsq     standard       0.740 Preprocessor1_Model1

Now, let’s fit a random forest model using Tidymodels.

# determine the number of cores for parallel computing
cores <- parallel::detectCores()
# set the engine and mode, also the tuning parameters
# mtry and min_n are set to be determined by CV
rf_model <- rand_forest() |> 
  set_args(mtry = tune(), 
           min_n = tune(), 
           trees = 1000) |>  
  set_engine("ranger", num.threads = cores) |>  
  set_mode('regression')
# use all variables without any transformation
boston_recipe <- recipe(medv ~ ., 
                        data = boston_train) 
# create a random forest workflow
rf_workflow <- workflow() |>  
  add_recipe(boston_recipe) |>  
  add_model(rf_model)
# perform cross-validation on a grid of hyperparameters
# boston_folds was created above
set.seed(255)
rf_tune_results <- rf_workflow |>  
  tune_grid(resamples = boston_folds,  # CV folds
            grid = 25,
            control = control_grid(save_pred = TRUE),
            metrics = metric_set(rmse))

rf_tune_results |>  show_best(metric = "rmse")
## # A tibble: 5 × 8
##    mtry min_n .metric .estimator  mean     n std_err .config              
##   <int> <int> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                
## 1     7     3 rmse    standard    2.93     5   0.200 Preprocessor1_Model06
## 2     8     9 rmse    standard    3.01     5   0.201 Preprocessor1_Model14
## 3     5    12 rmse    standard    3.02     5   0.199 Preprocessor1_Model18
## 4     7    16 rmse    standard    3.05     5   0.194 Preprocessor1_Model01
## 5     5    17 rmse    standard    3.06     5   0.204 Preprocessor1_Model04
# mtry = 7 min_n=3
# plot hyperparameter values 
autoplot(rf_tune_results)

rf_tune_results |>  collect_metrics()
## # A tibble: 25 × 8
##     mtry min_n .metric .estimator  mean     n std_err .config              
##    <int> <int> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                
##  1     7    16 rmse    standard    3.05     5   0.194 Preprocessor1_Model01
##  2     4    28 rmse    standard    3.33     5   0.236 Preprocessor1_Model02
##  3     4    30 rmse    standard    3.39     5   0.226 Preprocessor1_Model03
##  4     5    17 rmse    standard    3.06     5   0.204 Preprocessor1_Model04
##  5     2    31 rmse    standard    3.96     5   0.292 Preprocessor1_Model05
##  6     7     3 rmse    standard    2.93     5   0.200 Preprocessor1_Model06
##  7     1     8 rmse    standard    4.42     5   0.332 Preprocessor1_Model07
##  8     9    37 rmse    standard    3.35     5   0.208 Preprocessor1_Model08
##  9     7    26 rmse    standard    3.16     5   0.195 Preprocessor1_Model09
## 10     6    24 rmse    standard    3.14     5   0.190 Preprocessor1_Model10
## # ℹ 15 more rows
best_rf_model <- rf_tune_results |> 
  select_best(metric = 'rmse')
best_rf_model
## # A tibble: 1 × 3
##    mtry min_n .config              
##   <int> <int> <chr>                
## 1     7     3 Preprocessor1_Model06
final_rf_wkfl <- rf_workflow |> 
  finalize_workflow(best_rf_model)
final_rf_wkfl
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Recipe
## Model: rand_forest()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## 0 Recipe Steps
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Random Forest Model Specification (regression)
## 
## Main Arguments:
##   mtry = 7
##   trees = 1000
##   min_n = 3
## 
## Engine-Specific Arguments:
##   num.threads = cores
## 
## Computational engine: ranger
rf_final_fit <- final_rf_wkfl |> 
  last_fit(split = boston_split)

rf_final_fit |> 
  collect_metrics()
## # A tibble: 2 × 4
##   .metric .estimator .estimate .config             
##   <chr>   <chr>          <dbl> <chr>               
## 1 rmse    standard       4.53  Preprocessor1_Model1
## 2 rsq     standard       0.758 Preprocessor1_Model1
# last fit 
last_rf_model <- 
  rand_forest(mtry = 7, 
              min_n = 3, 
              trees = 1000) |>  
  set_engine("ranger", 
             num.threads = cores, 
             importance = "impurity") |>  
  set_mode("regression")

last_rf_workflow <- 
  rf_workflow |>  
  update_model(last_rf_model)

set.seed(678)
last_rf_fit <- 
  last_rf_workflow |>  
  last_fit(boston_split)

last_rf_fit
## # Resampling results
## # Manual resampling 
## # A tibble: 1 × 6
##   splits            id               .metrics .notes   .predictions .workflow 
##   <list>            <chr>            <list>   <list>   <list>       <list>    
## 1 <split [378/128]> train/test split <tibble> <tibble> <tibble>     <workflow>
last_rf_fit |>  collect_metrics()
## # A tibble: 2 × 4
##   .metric .estimator .estimate .config             
##   <chr>   <chr>          <dbl> <chr>               
## 1 rmse    standard       4.53  Preprocessor1_Model1
## 2 rsq     standard       0.757 Preprocessor1_Model1
# variable importance measures
library(vip) # for variable importance measures
last_rf_fit |>  
  pluck(".workflow", 1) |>    
  pull_workflow_fit() |>  
  vip(num_features = 13)

6 Example: Surviving the Titanic

In this exercise, we will attempt to predict who will survive in the Titanic accident which is one of the worst disasters at sea. On 14 April 1912, the RMS Titanic struck a large iceberg and approximately 1,500 passengers and crew died and 705 survived on 15 April. The Titanic disaster has led to significant improvements in safety regulations to prevent such calamities happening again.

We are interested in the following questions: What are the factors behind disproportionate number of deaths in this disaster? Which variables are relatively more important that influenced the likelihood of survival? We will start by building a classification tree to answer these questions.

First, read Titanic data into R:

library(tidyverse)
library(modelr)
library(broom)
set.seed(1234)

theme_set(theme_minimal())

library(titanic)
# use the training data 
titanic <- titanic_train |> 
  as_tibble()

titanic |> 
  head() |> 
  knitr::kable()
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
1 0 3 Braund, Mr. Owen Harris male 22 1 0 A/5 21171 7.2500 S
2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38 1 0 PC 17599 71.2833 C85 C
3 1 3 Heikkinen, Miss. Laina female 26 0 0 STON/O2. 3101282 7.9250 S
4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 0 113803 53.1000 C123 S
5 0 3 Allen, Mr. William Henry male 35 0 0 373450 8.0500 S
6 0 3 Moran, Mr. James male NA 0 0 330877 8.4583 Q
titanic_tree_data <- titanic |> 
  mutate(Survived = if_else(Survived == 1, "Survived", "Died"),
         Survived = as.factor(Survived),
         Sex = as.factor(Sex))
titanic_tree_data
## # A tibble: 891 × 12
##    PassengerId Survived Pclass Name   Sex     Age SibSp Parch Ticket  Fare Cabin
##          <int> <fct>     <int> <chr>  <fct> <dbl> <int> <int> <chr>  <dbl> <chr>
##  1           1 Died          3 Braun… male     22     1     0 A/5 2…  7.25 ""   
##  2           2 Survived      1 Cumin… fema…    38     1     0 PC 17… 71.3  "C85"
##  3           3 Survived      3 Heikk… fema…    26     0     0 STON/…  7.92 ""   
##  4           4 Survived      1 Futre… fema…    35     1     0 113803 53.1  "C12…
##  5           5 Died          3 Allen… male     35     0     0 373450  8.05 ""   
##  6           6 Died          3 Moran… male     NA     0     0 330877  8.46 ""   
##  7           7 Died          1 McCar… male     54     0     0 17463  51.9  "E46"
##  8           8 Died          3 Palss… male      2     3     1 349909 21.1  ""   
##  9           9 Survived      3 Johns… fema…    27     0     2 347742 11.1  ""   
## 10          10 Survived      2 Nasse… fema…    14     1     0 237736 30.1  ""   
## # ℹ 881 more rows
## # ℹ 1 more variable: Embarked <chr>
table(titanic_tree_data$Survived)
## 
##     Died Survived 
##      549      342

Construct a simple classification tree using only two features, age and sex, using partykit package.

library(partykit)
titanic_tree <- ctree(Survived ~ Age + Sex, data = titanic_tree_data)
titanic_tree
## 
## Model formula:
## Survived ~ Age + Sex
## 
## Fitted party:
## [1] root
## |   [2] Sex in female: Survived (n = 314, err = 25.8%)
## |   [3] Sex in male
## |   |   [4] Age <= 6: Survived (n = 35, err = 48.6%)
## |   |   [5] Age > 6: Died (n = 542, err = 16.8%)
## 
## Number of inner nodes:    2
## Number of terminal nodes: 3

The resulting tree has 3 terminal nodes and 2 inner nodes. Here is the plot of the tree

plot(titanic_tree)

Compute misclassification rate:

# compute predicted values
pred1 <- predict(titanic_tree) 
# true classifications
predsuccess1 <- (pred1 == titanic_tree_data$Survived)
# wrong classifications
prederror1 <- !predsuccess1
# average misclassification rate: 
mean(prederror1, na.rm = TRUE)
## [1] 0.2121212
# or just in one line: 
# 1 - mean(predict(titanic_tree) == titanic_tree_data$Survived, na.rm = TRUE)

Even with this simple tree, the error rate is 21%.

Let’s create a more complicated tree using additional features. First convert character variables into factor variables.

titanic_tree_full_data <- titanic |> 
  mutate(Survived = if_else(Survived == 1, "Survived",
                            if_else(Survived == 0, "Died", NA_character_))) |> 
  mutate_if(is.character, as.factor)

Construct the tree:

titanic_tree_full <- ctree(Survived ~ Pclass + Sex + Age + SibSp +
                             Parch + Fare + Embarked,
                           data = titanic_tree_full_data)
titanic_tree_full
## 
## Model formula:
## Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Embarked
## 
## Fitted party:
## [1] root
## |   [2] Sex in female
## |   |   [3] Pclass <= 2: Survived (n = 170, err = 5.3%)
## |   |   [4] Pclass > 2
## |   |   |   [5] Fare <= 23.25: Survived (n = 117, err = 41.0%)
## |   |   |   [6] Fare > 23.25: Died (n = 27, err = 11.1%)
## |   [7] Sex in male
## |   |   [8] Pclass <= 1
## |   |   |   [9] Age <= 52: Died (n = 98, err = 41.8%)
## |   |   |   [10] Age > 52: Died (n = 24, err = 16.7%)
## |   |   [11] Pclass > 1
## |   |   |   [12] Age <= 9
## |   |   |   |   [13] Pclass <= 2: Survived (n = 12, err = 25.0%)
## |   |   |   |   [14] Pclass > 2: Died (n = 29, err = 31.0%)
## |   |   |   [15] Age > 9: Died (n = 414, err = 11.1%)
## 
## Number of inner nodes:    7
## Number of terminal nodes: 8
plot(titanic_tree_full,  ip_args = list(pval = FALSE, id = FALSE),
     tp_args = list( id = FALSE) )

# error rate
1 - mean(predict(titanic_tree_full) == titanic_tree_data$Survived,
         na.rm = TRUE)
## [1] 0.1829405

Let’s build a random forest using caret package. We will use caret::train() function and plot the most important variables.

# drop the NA obs.
titanic_rf_data <- titanic_tree_full_data |> 
  select(Survived, Pclass, Sex, Age, SibSp, Parch, Fare, Embarked) |> 
  drop_na()
titanic_rf_data
## # A tibble: 714 × 8
##    Survived Pclass Sex      Age SibSp Parch  Fare Embarked
##    <fct>     <int> <fct>  <dbl> <int> <int> <dbl> <fct>   
##  1 Died          3 male      22     1     0  7.25 S       
##  2 Survived      1 female    38     1     0 71.3  C       
##  3 Survived      3 female    26     0     0  7.92 S       
##  4 Survived      1 female    35     1     0 53.1  S       
##  5 Died          3 male      35     0     0  8.05 S       
##  6 Died          1 male      54     0     0 51.9  S       
##  7 Died          3 male       2     3     1 21.1  S       
##  8 Survived      3 female    27     0     2 11.1  S       
##  9 Survived      2 female    14     1     0 30.1  C       
## 10 Survived      3 female     4     1     1 16.7  S       
## # ℹ 704 more rows
# build a random forest with ntree=200
library(caret)
library(e1071)
titanic_rf <- train(Survived ~ ., data = titanic_rf_data,
                    method = "rf",
                    ntree = 200,
                    trControl = trainControl(method = "oob"))
titanic_rf
## Random Forest 
## 
## 714 samples
##   7 predictor
##   2 classes: 'Died', 'Survived' 
## 
## No pre-processing
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##   2     0.8123249  0.5968889
##   5     0.8053221  0.5926564
##   9     0.7927171  0.5679450
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
str(titanic_rf, max.level = 1)
## List of 25
##  $ method      : chr "rf"
##  $ modelInfo   :List of 15
##  $ modelType   : chr "Classification"
##  $ results     :'data.frame':    3 obs. of  3 variables:
##  $ pred        : NULL
##  $ bestTune    :'data.frame':    1 obs. of  1 variable:
##  $ call        : language train.formula(form = Survived ~ ., data = titanic_rf_data, method = "rf",      ntree = 200, trControl = trainCont| __truncated__
##  $ dots        :List of 1
##  $ metric      : chr "Accuracy"
##  $ control     :List of 26
##  $ finalModel  :List of 23
##   ..- attr(*, "class")= chr "randomForest"
##  $ preProcess  : NULL
##  $ trainingData: tibble [714 × 8] (S3: tbl_df/tbl/data.frame)
##  $ ptype       : tibble [0 × 7] (S3: tbl_df/tbl/data.frame)
##  $ resample    : NULL
##  $ resampledCM : NULL
##  $ perfNames   : chr [1:2] "Accuracy" "Kappa"
##  $ maximize    : logi TRUE
##  $ yLimits     : NULL
##  $ times       :List of 3
##  $ levels      : chr [1:2] "Died" "Survived"
##   ..- attr(*, "ordered")= logi FALSE
##  $ terms       :Classes 'terms', 'formula'  language Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Embarked
##   .. ..- attr(*, "variables")= language list(Survived, Pclass, Sex, Age, SibSp, Parch, Fare, Embarked)
##   .. ..- attr(*, "factors")= int [1:8, 1:7] 0 1 0 0 0 0 0 0 0 0 ...
##   .. .. ..- attr(*, "dimnames")=List of 2
##   .. ..- attr(*, "term.labels")= chr [1:7] "Pclass" "Sex" "Age" "SibSp" ...
##   .. ..- attr(*, "order")= int [1:7] 1 1 1 1 1 1 1
##   .. ..- attr(*, "intercept")= int 1
##   .. ..- attr(*, "response")= int 1
##   .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. ..- attr(*, "predvars")= language list(Survived, Pclass, Sex, Age, SibSp, Parch, Fare, Embarked)
##   .. ..- attr(*, "dataClasses")= Named chr [1:8] "factor" "numeric" "factor" "numeric" ...
##   .. .. ..- attr(*, "names")= chr [1:8] "Survived" "Pclass" "Sex" "Age" ...
##  $ coefnames   : chr [1:9] "Pclass" "Sexmale" "Age" "SibSp" ...
##  $ contrasts   :List of 2
##  $ xlevels     :List of 2
##  - attr(*, "class")= chr [1:2] "train" "train.formula"
# Info on the final model: 
titanic_rf$finalModel
## 
## Call:
##  randomForest(x = x, y = y, ntree = 200, mtry = param$mtry) 
##                Type of random forest: classification
##                      Number of trees: 200
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 18.21%
## Confusion matrix:
##          Died Survived class.error
## Died      390       34  0.08018868
## Survived   96      194  0.33103448
# confusion table 
knitr::kable(titanic_rf$finalModel$confusion)
Died Survived class.error
Died 390 34 0.0801887
Survived 96 194 0.3310345
# look at an indiividual tree
randomForest::getTree(titanic_rf$finalModel, labelVar = TRUE)
##    left daughter right daughter split var split point status prediction
## 1              2              3 EmbarkedS     0.50000      1       <NA>
## 2              4              5   Sexmale     0.50000      1       <NA>
## 3              6              7   Sexmale     0.50000      1       <NA>
## 4              8              9 EmbarkedQ     0.50000      1       <NA>
## 5             10             11    Pclass     1.50000      1       <NA>
## 6             12             13    Pclass     2.50000      1       <NA>
## 7             14             15    Pclass     1.50000      1       <NA>
## 8              0              0      <NA>     0.00000     -1   Survived
## 9             16             17    Pclass     2.50000      1       <NA>
## 10            18             19      Fare    28.12500      1       <NA>
## 11            20             21       Age     1.50000      1       <NA>
## 12             0              0      <NA>     0.00000     -1   Survived
## 13            22             23     SibSp     0.50000      1       <NA>
## 14            24             25     SibSp     2.00000      1       <NA>
## 15            26             27       Age     9.50000      1       <NA>
## 16             0              0      <NA>     0.00000     -1   Survived
## 17            28             29      Fare    11.76460      1       <NA>
## 18             0              0      <NA>     0.00000     -1   Survived
## 19            30             31     Parch     1.50000      1       <NA>
## 20             0              0      <NA>     0.00000     -1   Survived
## 21            32             33 EmbarkedC     0.50000      1       <NA>
## 22            34             35     Parch     3.50000      1       <NA>
## 23            36             37     Parch     1.50000      1       <NA>
## 24            38             39       Age    28.50000      1       <NA>
## 25             0              0      <NA>     0.00000     -1       Died
## 26            40             41     SibSp     2.50000      1       <NA>
## 27            42             43       Age    17.50000      1       <NA>
## 28             0              0      <NA>     0.00000     -1   Survived
## 29             0              0      <NA>     0.00000     -1       Died
## 30            44             45     SibSp     0.50000      1       <NA>
## 31            46             47      Fare   161.19165      1       <NA>
## 32             0              0      <NA>     0.00000     -1       Died
## 33            48             49     SibSp     0.50000      1       <NA>
## 34            50             51       Age    27.50000      1       <NA>
## 35             0              0      <NA>     0.00000     -1       Died
## 36            52             53     Parch     0.50000      1       <NA>
## 37            54             55      Fare    31.33125      1       <NA>
## 38             0              0      <NA>     0.00000     -1   Survived
## 39             0              0      <NA>     0.00000     -1       Died
## 40             0              0      <NA>     0.00000     -1   Survived
## 41             0              0      <NA>     0.00000     -1       Died
## 42             0              0      <NA>     0.00000     -1       Died
## 43             0              0      <NA>     0.00000     -1       Died
## 44            56             57       Age    45.50000      1       <NA>
## 45            58             59       Age    55.00000      1       <NA>
## 46             0              0      <NA>     0.00000     -1   Survived
## 47             0              0      <NA>     0.00000     -1       Died
## 48             0              0      <NA>     0.00000     -1       Died
## 49             0              0      <NA>     0.00000     -1       Died
## 50             0              0      <NA>     0.00000     -1   Survived
## 51             0              0      <NA>     0.00000     -1       Died
## 52            60             61     SibSp     2.50000      1       <NA>
## 53            62             63       Age     4.50000      1       <NA>
## 54             0              0      <NA>     0.00000     -1       Died
## 55            64             65      Fare    32.88125      1       <NA>
## 56             0              0      <NA>     0.00000     -1   Survived
## 57             0              0      <NA>     0.00000     -1       Died
## 58            66             67       Age    21.50000      1       <NA>
## 59             0              0      <NA>     0.00000     -1   Survived
## 60             0              0      <NA>     0.00000     -1       Died
## 61             0              0      <NA>     0.00000     -1   Survived
## 62             0              0      <NA>     0.00000     -1   Survived
## 63             0              0      <NA>     0.00000     -1       Died
## 64             0              0      <NA>     0.00000     -1   Survived
## 65             0              0      <NA>     0.00000     -1       Died
## 66             0              0      <NA>     0.00000     -1       Died
## 67             0              0      <NA>     0.00000     -1       Died
# var importance plot 
randomForest::varImpPlot(titanic_rf$finalModel)