5.2 An application II

In this section we demonstrate how to use boosting to predict the salary of baseball players using the Hitters dataset.

We start by loading the required packages and splitting the data into a training and test set

library(caret)
## Warning: package 'ggplot2' was built under R version 4.6.1
library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.6.1
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.6.1
library(gbm)
## Warning: package 'gbm' was built under R version 4.6.1
Hitters <- na.omit(Hitters)

set.seed(3)
training.samples <- caret::createDataPartition(Hitters$Salary, 
                                               p = 0.7, 
                                               list = FALSE)
train.data  <- Hitters[training.samples, ]
test.data <- Hitters[-training.samples, ]

Boosting has a number of different parameters and we use a grid search and cross-validation to find the best choice.

gbmGrid <- expand.grid(interaction.depth = c(1, 2, 3),
                       n.trees = (1:20)*2000,
                       shrinkage = 0.001,
                       n.minobsinnode = 5)

fitControl <- trainControl(
  method = "repeatedcv",
  number = 5,
  repeats = 5
  )

The performance of the model is usually better the smaller the shrinkage parameter, or learning rate, is chosen. But with a small shrinkage we need many iterations, i.e. trees. So there is a tradeof between performance and the time it takes to train the model and the amount of storage required.

To speed up the training we use parallel processes.

library(doParallel)
## Warning: package 'doParallel' was built under R version 4.6.1
cl <- makePSOCKcluster(4)
registerDoParallel(cl)

Now we fit the model

gbmFit <- train(
  Salary ~ ., 
  data = train.data, 
  method = "gbm", 
  trControl = fitControl,
  verbose = FALSE,
  distribution = "gaussian",
  tuneGrid = gbmGrid
  )

Here, gaussian means that we are doing regression that minimizes the square error.

We may know predict the observations in the test set and calculate the out-of-sample error.

predictions <- predict(gbmFit, test.data)
sqrt(mean((predictions - test.data$Salary)^2))
## [1] 308.2421

This is an improvement over the regularized linear regression we did previously.

We can also see the importance of each variable.

ggplot(varImp(gbmFit, scale = FALSE)) +
  theme_minimal()

By making a partial dependence plot we can illustrate how each variable affect the prediction on average.

gbmFit$finalModel %>%
  pdp::partial(
    pred.var = "CHmRun", 
    n.trees = gbmFit$finalModel$n.trees, 
    grid.resolution = 100,
    train = train.data,
    plot = TRUE,
    rug = TRUE,
    plot.engine = "ggplot2") +
  theme_minimal()