4.10 An application I
We will use the Hitters data set from the ISL book and predict the salary of a Baseball player based on various covariates.
Then we randomly split the data into a train and a test set. We keep 70% of the observations in the training set and the rest in the test set.
set.seed(3)
training.samples <- caret::createDataPartition(Hitters$Salary,
p = 0.7,
list = FALSE)
train.data <- Hitters[training.samples, ]
test.data <- Hitters[-training.samples, ]We then do linear regression and calculate the out-of-sample error
ls <- lm(Salary ~., data = train.data)
predictions <- predict(ls, test.data)
sqrt(mean((predictions - test.data$Salary)^2))## [1] 367.6942
Next we fit a lasso using 10-fold CV.
lambda.grid <- 10^seq(-2, 2, length = 100)
set.seed(42)
lasso <- train(
Salary ~., data = train.data, method = "glmnet",
trControl = trainControl("repeatedcv", number = 10, repeats = 5),
tuneGrid = expand.grid(alpha = 1, lambda = lambda.grid)
)We may plot the cross-validated error against the regularization parameter.
Figure 4.22: Cross-validated error against the regularization parameter for Lasso.
If we print the parameters, we see that some of them have been set to 0.
## 20 x 1 sparse Matrix of class "dgCMatrix"
## s=17.07353
## (Intercept) -66.88333624
## AtBat .
## Hits 2.00894789
## HmRun .
## Runs .
## RBI 0.63610478
## Walks 3.46312810
## Years .
## CAtBat .
## CHits .
## CHmRun 0.01178261
## CRuns 0.08620313
## CRBI 0.51517895
## CWalks .
## LeagueN 29.48507342
## DivisionW -100.72607403
## PutOuts 0.17109758
## Assists -0.06283794
## Errors .
## NewLeagueN .
We calculate the out-of-sample error.
## [1] 358.6614
An improvement over least squares. We might also try elastic-net.
lambda <- 10^seq(-2, 2.5, length = 100)
alpha <- seq(0, 0.5, length = 10)
set.seed(42)
e.net <- train(
Salary ~., data = train.data, method = "glmnet",
trControl = trainControl("repeatedcv", number = 10, repeats = 5),
tuneGrid = expand.grid(alpha = alpha, lambda = lambda)
)
Figure 4.23: Cross-validated error against the regularization parameter for elastic net
## [1] 361.3435
We get a worse out-of-sample error. But we need to keep in mind that the number of observations in the test-set is not very large.