1 Validation Set Approach

This example is from the ISLR text. It uses the auto data set to estimate a linear regression model for fuel efficiency (mpg).

library(ISLR) 
# randomly select observations to be included
# in the training set
set.seed(1)
train <- sample(392,196)
# Estimate the model using only training data
lmfit <- lm(mpg ~ horsepower,data = Auto, subset = train)
# estimate the prediction error using only test data 
train_auto <- Auto[train,]
test_auto <- Auto[-train,]
train_predict <- predict(lmfit, train_auto)
test_predict <- predict(lmfit, test_auto)
test_error <- test_auto$mpg - test_predict
mean(test_error^2)
## [1] 23.26601
#
# or in one line - but harder to grasp
# mean((Auto$mpg-predict(lmfit,Auto))[-train]^2)

Similarly, for quadratic and cubic regressions:

lm.fit2 <- lm(mpg~poly(horsepower,2),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit2,Auto))[-train]^2)
## [1] 18.71646
lm.fit3 <- lm(mpg~poly(horsepower,3),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit3,Auto))[-train]^2)
## [1] 18.79401

Choose another validation set and compute MSE

set.seed(2)
train <- sample(392,196)
lm.fit <- lm(mpg ~ horsepower, data=Auto, subset=train)
mean((Auto$mpg-predict(lm.fit,Auto))[-train]^2)
## [1] 25.72651
lm.fit2 <- lm(mpg~poly(horsepower,2),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit2,Auto))[-train]^2)
## [1] 20.43036
lm.fit3 <- lm(mpg~poly(horsepower,3),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit3,Auto))[-train]^2)
## [1] 20.38533
# replicate the validation set approach many times using Auto data 
library(tidyverse)
library(ISLR2)

dmax = 10 # max degree of the polynomial, the flexibility
nrep = 20 # number of replications
#
set.seed(1)
# create an empty tibble
mse <- tibble(rep = numeric(), d = numeric(), testmse = numeric())

for (i in 1:nrep){
  train <- sample(392,196)   # train-test splits
  train_auto <- Auto[train,] # train data 
  test_auto <- Auto[-train,] # test data 
  # loop over flexibility
  for (j in 1:dmax){
    lmfit <- lm(mpg ~ poly(horsepower,j), data = train_auto)
    test_predict <- predict(lmfit, test_auto)
    test_error <- test_auto$mpg - test_predict
    MSE = mean(test_error^2)
    mse <- add_row(mse, rep=i, d=j, testmse = MSE ) 
  }
}

mse |> 
  ggplot(aes(d,testmse,color=factor(rep))) + 
  geom_line() +
  geom_point() +
  scale_x_continuous(breaks=c(1:dmax)) +
  labs(x="Degree of the polynomial", 
       y="Test MSE") +
  theme(legend.position="none")

As we discussed class, the validation set approach produces high variability in test MSE values (here in 20 replications of random train-test splits).

Exercise: There are several pays of completing a task in R (in fact in any programming language). In the above I created an empty data frame (tibble) and then looped over both rep and d. Do the same but this time use a matrix to store MSE values. For example

dmax = 10
nrep = 20 

# create an empty matrix
MSE <- matrix(NA, nrow = nrep, ncol = dmax)
set.seed(1)
for (i in 1:nrep){
  train <- sample(392,196)   # train-test splits
  train_auto <- Auto[train,] # train data 
  test_auto <- Auto[-train,] # test data 
  # loop over flexibility
  for (j in 1:dmax){
    lmfit <- lm(mpg ~ poly(horsepower,j), data = train_auto)
    test_predict <- predict(lmfit, test_auto)
    test_error <- test_auto$mpg - test_predict
    MSE[i,j] <- mean(test_error^2)
  }
}
MSE
##           [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]
##  [1,] 23.26601 18.71646 18.79401 19.16017 19.40812 19.59465 19.03653 19.06868
##  [2,] 26.83974 19.56785 19.62272 19.98535 21.45656 21.82743 21.66279 21.66418
##  [3,] 23.85104 20.86163 21.12714 21.07310 20.54724 20.35866 20.19446 20.16360
##  [4,] 23.70971 19.49638 19.44968 19.40644 19.20144 19.41770 19.17429 19.28147
##  [5,] 24.50568 19.21836 19.16750 19.09215 18.44618 18.20995 18.11843 18.17960
##  [6,] 25.63588 21.16335 21.11183 21.03403 20.41739 20.53581 20.32289 20.40965
##  [7,] 22.26770 16.77149 16.90481 16.91783 16.48122 16.65584 16.66197 16.94877
##  [8,] 24.49664 19.28732 19.28326 19.24308 18.64834 18.71919 18.83622 18.71130
##  [9,] 24.80624 20.42469 21.42639 21.62462 21.11183 20.72257 20.51277 20.50840
## [10,] 24.80658 20.05391 20.87501 20.78631 19.96932 19.70204 19.80721 23.30814
## [11,] 25.63405 18.39892 18.68022 18.62222 17.96287 18.06022 17.99997 17.96847
## [12,] 24.21333 21.73344 22.05000 22.16369 21.63118 21.43581 21.24283 21.23928
## [13,] 21.82104 15.73574 15.77496 15.86977 15.77813 16.08795 15.70797 16.12084
## [14,] 23.54493 18.83198 18.78980 18.73325 18.34511 18.11102 17.92515 18.00169
## [15,] 24.01743 20.41814 21.51234 23.01838 22.71666 22.12853 21.28205 21.44804
## [16,] 21.48714 20.49265 20.58605 20.56596 20.20933 19.99512 20.06970 20.07481
## [17,] 25.79852 20.04906 20.28842 20.25418 20.16798 20.12697 20.20527 20.28159
## [18,] 26.65465 21.42694 21.42830 21.47695 21.00751 21.15037 21.29126 22.12747
## [19,] 22.68877 19.22944 19.25536 19.17817 18.84146 18.60931 18.40509 18.42331
## [20,] 26.53255 20.23741 20.27156 21.66869 21.78383 23.83275 22.31716 23.44257
##           [,9]    [,10]
##  [1,] 19.06046 22.86700
##  [2,] 21.59520 21.64677
##  [3,] 20.11838 20.99285
##  [4,] 19.43274 19.42095
##  [5,] 18.21522 18.65663
##  [6,] 20.75464 20.83173
##  [7,] 17.22209 17.19850
##  [8,] 18.46795 18.95310
##  [9,] 20.94036 20.96306
## [10,] 25.95037 26.75370
## [11,] 17.91681 18.08582
## [12,] 21.41154 22.23057
## [13,] 15.88710 16.34995
## [14,] 17.95053 18.13110
## [15,] 22.93423 22.73119
## [16,] 20.14523 20.20660
## [17,] 20.45815 23.40274
## [18,] 23.70054 24.74403
## [19,] 18.39377 18.48770
## [20,] 25.92727 21.98476

Now convert the matrix MSE into a data frame (tibble) and plot d and MSE.

2 Leave-one-out Cross-Validation (LOOCV)

In LOOCV we repeatedly estimate the model on the training set by leaving one observation out on at a time.

Here is an illustration of the LOOCV method using Auto data set:

data(Auto)
n = nrow(Auto)
loocv = numeric(n) # vector of zeros to be filled with test MSE
for (i in 1:n){
  testdata <- Auto[i,]
  traindata <- Auto[-i,]
  lmfit <- lm(mpg ~ poly(horsepower,1), # degree = 1
              data = traindata)
    test_predict <- predict(lmfit, testdata)
    test_error <- testdata$mpg - test_predict
    loocv[i] <- mean(test_error^2)
}
MSE_LOOCV_degree1 <- mean(loocv)
MSE_LOOCV_degree1
## [1] 24.23151

When d=1 (i.e., a linear regression of mpg on horsepower) the LOOCV produces an average MSE of 24.23151.

Let’s use a quadratic fit, d=2:

data(Auto)
n = nrow(Auto)
loocv = numeric(n) # vector of zeros to be filled with test MSE
for (i in 1:n){
  testdata <- Auto[i,]
  traindata <- Auto[-i,]
  lmfit <- lm(mpg ~ poly(horsepower,2),  # degree 2
              data = traindata)
    test_predict <- predict(lmfit, testdata)
    test_error <- testdata$mpg - test_predict
    loocv[i] <- mean(test_error^2)
}
MSE_LOOCV_degree2 <- mean(loocv)
MSE_LOOCV_degree2
## [1] 19.24821

We can do these in a loop over the flexibility of the model (degree d):

data(Auto)
n = nrow(Auto)
loocv = numeric(n) # vector of zeros to be filled with test MSE
dmax = 10
MSE_LOOCV = numeric(dmax)
for (d in 1:dmax){
for (i in 1:n){
  testdata <- Auto[i,]
  traindata <- Auto[-i,]
  lmfit <- lm(mpg ~ poly(horsepower,d),  # degree d
              data = traindata)
    test_predict <- predict(lmfit, testdata)
    test_error <- testdata$mpg - test_predict
    loocv[i] <- mean(test_error^2)
}
MSE_LOOCV[d] <- mean(loocv) 
}
MSE_LOOCV
##  [1] 24.23151 19.24821 19.33498 19.42443 19.03321 18.97864 18.83305 18.96115
##  [9] 19.06863 19.49093
tibble(MSE_LOOCV) |> 
  ggplot(aes(1:10,MSE_LOOCV)) + 
  geom_line() +
  geom_point() + 
  scale_x_continuous(breaks=c(1:dmax)) +
  labs(x="Degree of the polynomial", 
       y="Test MSE", 
       title="LOOCV test error") 

We can use cv.glm() function which is a part of the boot library together with glm() function to perform linear regression.

glm() function is similar to lm():

glm.fit <- glm(mpg ~ horsepower, data = Auto)
coef(glm.fit)
## (Intercept)  horsepower 
##  39.9358610  -0.1578447
lm.fit <- lm(mpg ~ horsepower, data = Auto)
coef(lm.fit)
## (Intercept)  horsepower 
##  39.9358610  -0.1578447

The usage of cv.glm():

library(boot)
glm.fit <- glm(mpg ~ horsepower, data=Auto)
cv.err <- cv.glm(Auto, glm.fit) # default is LOOCV i.e., K=n
cv.err$delta # raw and adjusted CV estimate
## [1] 24.23151 24.23114

cv.err contains cross-validation mean error (see equation 5.1 in the ISLR text). As the default, cv.glm() performs LOOCV. See below for K-fold Cross-Validation.

Let’s apply LOOCV for more complicated models (higher order polynomials) and compare the results:

dmax = 10
cv.error = rep(0,dmax)
for (i in 1:dmax){
  glm.fit <- glm(mpg ~ poly(horsepower,i), data = Auto)
  cv.error[i] <- cv.glm(Auto, glm.fit)$delta[1]
}
cv.error
##  [1] 24.23151 19.24821 19.33498 19.42443 19.03321 18.97864 18.83305 18.96115
##  [9] 19.06863 19.49093

3 K-fold Cross-Validation

data(Auto)
n = nrow(Auto)
k = 5
kfoldcv = numeric(k) # vector of zeros to be filled with test MSE
# create a loop over k
set.seed(17)
folds <- sample(1:k, n, replace=TRUE)
for (i in 1:k){
  testdata <- Auto[folds == i,]
  traindata <- Auto[folds != i,]
  lmfit <- lm(mpg ~ poly(horsepower,1), # degree = 1
              data = traindata)
    test_predict <- predict(lmfit, testdata)
    test_error <- testdata$mpg - test_predict
    kfoldcv[i] <- mean(test_error^2)
}
kfoldcv
## [1] 27.67133 28.91717 18.84783 29.76274 14.14999
MSE_kfoldcv_degree1 <- mean(kfoldcv)
MSE_kfoldcv_degree1
## [1] 23.86981
set.seed(17)
cv.error.10 <- rep(0,10)
for (i in 1:10){
  glm.fit <- glm(mpg ~ poly(horsepower,i), data = Auto)
  cv.error.10[i] <- cv.glm(Auto, glm.fit, K=10)$delta[1]
}
cv.error.10
##  [1] 24.27207 19.26909 19.34805 19.29496 19.03198 18.89781 19.12061 19.14666
##  [9] 18.87013 20.95520

4 Bootstrap

This example is from Efron, B. and R. Tibshrani “Bootstrap Methods for Standard Errors, Confidence Intervals and Other measures of Statisical Accuracy.” Statistical Science, 1(1986): 54-77.

The data set consists of average LSAT scores and GPAs from n=15 American law schools that are obtained for the 1973 entering class.

LSAT <- c(576, 635, 558, 578, 666, 580, 555, 661, 651, 605, 653, 575, 545, 572, 594)
GPA <- c(3.39, 3.30, 2.81, 3.03, 3.44, 3.07, 3.00, 3.43, 3.36, 3.13, 
        3.12, 2.74, 2.76, 2.88, 2.96)
data <- data.frame(LSAT,GPA)
plot(LSAT,GPA)

We are interested in estimating the standard error of the correlation coefficient. The sample correlation coefficient between LSAT and GPA is

cor(LSAT,GPA)
## [1] 0.7763745

What is the bootstrap standard error? To answer this question, we need to repeatedly sample from the data set and estimate (and save) the sample correlation coefficients. In the following code chunk, we implement this using the sample(n,n,replace=TRUE) function in a loop over B bootstrap replications.

set.seed(111)
B <- 1000 
bootsample <- rep(0,B)
for (i in 1:B){
  index <- sample(15,15,replace = TRUE)
  bootsample[i] <- cor(LSAT[index], GPA[index])
}
hist(bootsample)

sqrt(var(bootsample))
## [1] 0.127539
summary(bootsample)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.3128  0.7049  0.7955  0.7803  0.8772  0.9972

The bootstrap standard error estimate is 0.1275, practically the same as in the original publication. Efron and Tibshirani report a bootstrap standard error estimate of 0.127. Also, notice that the bootstrap mean is 0.7803, essentially the same as the sample correlation coefficient, 0.776.

The boot() function automates this. But we first need to define a function that returns the “statisic” for a given bootstrap sample indicated by “index”. See the help file for boot().

corboot <- function(data, index){
  X <- data[index,1]
  Y <- data[index,2]
  return(cor(X,Y))
}

library(boot)
set.seed(111)
boot(data = data, statistic = corboot, R=1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = data, statistic = corboot, R = 1000)
## 
## 
## Bootstrap Statistics :
##      original       bias    std. error
## t1* 0.7763745 0.0009153723   0.1311586

4.1 Estimating the Accuracy of a Linear Regression Model

boot.fn=function(data,index)
  return(coef(lm(mpg ~ horsepower, data=data, subset=index)))
boot.fn(Auto,1:392)
## (Intercept)  horsepower 
##  39.9358610  -0.1578447
set.seed(1)
boot.fn(Auto,sample(392,392,replace=T))
## (Intercept)  horsepower 
##  40.3404517  -0.1634868
boot.fn(Auto,sample(392,392,replace=T))
## (Intercept)  horsepower 
##  40.1186906  -0.1577063
boot(Auto,boot.fn,1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Auto, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##       original        bias    std. error
## t1* 39.9358610  0.0544513229 0.841289790
## t2* -0.1578447 -0.0006170901 0.007343073
summary(lm(mpg ~ horsepower, data=Auto))$coef
##               Estimate  Std. Error   t value      Pr(>|t|)
## (Intercept) 39.9358610 0.717498656  55.65984 1.220362e-187
## horsepower  -0.1578447 0.006445501 -24.48914  7.031989e-81
boot.fn=function(data,index)
  coefficients(lm(mpg ~ horsepower + I(horsepower^2), data=data, subset=index))
set.seed(1)
boot(Auto,boot.fn,1000)
## 
## ORDINARY NONPARAMETRIC BOOTSTRAP
## 
## 
## Call:
## boot(data = Auto, statistic = boot.fn, R = 1000)
## 
## 
## Bootstrap Statistics :
##         original        bias     std. error
## t1* 56.900099702  3.511640e-02 2.0300222526
## t2* -0.466189630 -7.080834e-04 0.0324241984
## t3*  0.001230536  2.840324e-06 0.0001172164
summary(lm(mpg ~ horsepower + I(horsepower^2), data=Auto))$coef
##                     Estimate   Std. Error   t value      Pr(>|t|)
## (Intercept)     56.900099702 1.8004268063  31.60367 1.740911e-109
## horsepower      -0.466189630 0.0311246171 -14.97816  2.289429e-40
## I(horsepower^2)  0.001230536 0.0001220759  10.08009  2.196340e-21

5 An Introduction to the Tidymodels

Tidymodels is a collection of R packages for machine learning modeling. Tidymodels follows the tidy data principles and easily integrates with packages in the Tidyverse. It consists of the following packages:

  • rsample: data resampling

  • recipes: feature engineering

  • parsnip: model fitting

  • tune, dials: model tuning

  • yardstick: model evaluation

Visit the website for a quick introduction to the Tidymodels: https://www.tidymodels.org/start/

# first install tidymodels 
# needs to be done once
# install.packages("tidymodels")

Let’s build a model using the Tidymodels. I will use the Auto data set.

The first step is to split the data set into training and testing sets. We can use initial_split() function from the {rsample} package. We want to predict mpg as a function of horsepower as we did above. We will use 75% of the data in the training part and 25% in the test part.

library(tidymodels)
library(ISLR)
set.seed(1)
auto_split <- initial_split(Auto, 
                           prop = 0.75, 
                           strata = mpg)

The input strata in the initial_split() function makes sure that the dependent variable is distributed similarly in both training and testing sets.

The training data set is

auto_train <- auto_split %>% training()
head(auto_train)
##   mpg cylinders displacement horsepower weight acceleration year origin
## 1  15         8          350        165   3693         11.5   70      1
## 2  16         8          304        150   3433         12.0   70      1
## 3  14         8          440        215   4312          8.5   70      1
## 4  14         8          455        225   4425         10.0   70      1
## 5  15         8          400        150   3761          9.5   70      1
## 6  14         8          455        225   3086         10.0   70      1
##                      name
## 1       buick skylark 320
## 2           amc rebel sst
## 3       plymouth fury iii
## 4        pontiac catalina
## 5   chevrolet monte carlo
## 6 buick estate wagon (sw)

And the test data set is

auto_test <- auto_split %>% testing()
head(auto_test)
##   mpg cylinders displacement horsepower weight acceleration year origin
## 1  17         8          302        140   3449         10.5   70      1
## 2  15         8          429        198   4341         10.0   70      1
## 3  14         8          454        220   4354          9.0   70      1
## 4  15         8          390        190   3850          8.5   70      1
## 5  15         8          383        170   3563         10.0   70      1
## 6  14         8          340        160   3609          8.0   70      1
##                  name
## 1         ford torino
## 2    ford galaxie 500
## 3    chevrolet impala
## 4  amc ambassador dpl
## 5 dodge challenger se
## 6  plymouth 'cuda 340

The auto_test data set will only be used in the model evaluation.

Now let’s run the regression of mpg on horsepower. We will use {parsnip} package for this purpose and follow these steps:

  1. Specify the model type. In this example this is regression, parsnip::linear_reg().

  2. Specify the engine. In this example we will use lm() function, parsnip::set_engine('lm').

  3. Specify the mode of the supervised learning problem. (regression or classification), parsnip::set_mode('regression').

Let’s call the object lm_model

lm_model <- linear_reg() %>%
  set_engine('lm') %>%
  set_mode('regression')
lm_model
## Linear Regression Model Specification (regression)
## 
## Computational engine: lm

Now we are ready to estimate the model using parsnip::fit() function:

auto_fit <- lm_model %>%
  fit(mpg ~ horsepower, data = auto_train)

Make a pretty table:

tidy(auto_fit)
## # A tibble: 2 × 5
##   term        estimate std.error statistic   p.value
##   <chr>          <dbl>     <dbl>     <dbl>     <dbl>
## 1 (Intercept)   39.9     0.844        47.2 3.38e-138
## 2 horsepower    -0.157   0.00759     -20.7 3.18e- 59

Now we trained our model. Let’s compute predictions from the model using new data set (i.e, test data):

auto_preds <- auto_fit %>%
  predict(new_data = auto_test)

Look at the components of auto_preds object:

head(auto_preds)
## # A tibble: 6 × 1
##   .pred
##   <dbl>
## 1 17.8 
## 2  8.71
## 3  5.25
## 4  9.97
## 5 13.1 
## 6 14.7

It has a single column named .pred computed using only the test data.

How can we evaluate model’s performance? Let’s create a new data set combining predictions and actual values of mpg and horsepower from the test data set.

auto_test_results <- auto_test %>%
  select(mpg, horsepower) %>%
  bind_cols(auto_preds)

Check out the data set:

head(auto_test_results)
##   mpg horsepower     .pred
## 1  17        140 17.841972
## 2  15        198  8.710310
## 3  14        220  5.246575
## 4  15        190  9.969849
## 5  15        170 13.118698
## 6  14        160 14.693123

We can use {yardstick} package to compute model evaluation metrics. For example rmse() computes the square of the mean squared error:

auto_test_results %>% 
  rmse(truth = mpg, estimate = .pred)
## # A tibble: 1 × 3
##   .metric .estimator .estimate
##   <chr>   <chr>          <dbl>
## 1 rmse    standard        4.66

Note that it requires two inputs, the truth and predictions.

Another metric we could use is the R-squared between truth and predictions.

auto_test_results %>%
  rsq(truth = mpg, estimate = .pred)  
## # A tibble: 1 × 3
##   .metric .estimator .estimate
##   <chr>   <chr>          <dbl>
## 1 rsq     standard       0.632

We can also plot the predictions and truth:

ggplot(auto_test_results, aes(x = mpg, y = .pred)) +
  geom_point() +
  geom_abline(color = 'blue', linetype = 2) +
  coord_obs_pred() +
  labs(title = 'R-Squared Plot',
       y = 'Predicted MPG',
       x = 'Actual MPG')

For a good prediction exercise, we’d expect the points to be scattered closely on the 45 degree line. But here in this example we see that this is not the case.

Let’s fit another model by adding the quadratic term.

auto_fit2 <- lm_model %>%
  fit(mpg ~ horsepower + I(horsepower^2), data = auto_train)

Make a pretty table:

tidy(auto_fit2)
## # A tibble: 3 × 5
##   term            estimate std.error statistic  p.value
##   <chr>              <dbl>     <dbl>     <dbl>    <dbl>
## 1 (Intercept)     57.1      2.14         26.7  4.04e-80
## 2 horsepower      -0.470    0.0369      -12.7  7.78e-30
## 3 I(horsepower^2)  0.00124  0.000144      8.62 4.37e-16

Now we trained our model. Let’s compute predictions from the model using new data set (i.e, test data):

auto_preds2 <- auto_fit2 %>%
  predict(new_data = auto_test)

Look at the components of auto_preds object:

auto_preds2
## # A tibble: 100 × 1
##    .pred
##    <dbl>
##  1  15.7
##  2  12.8
##  3  13.9
##  4  12.7
##  5  13.1
##  6  13.7
##  7  23.2
##  8  26.2
##  9  38.1
## 10  24.9
## # ℹ 90 more rows
auto_test_results2 <- auto_test %>%
  select(mpg, horsepower) %>%
  bind_cols(auto_preds2)

Check out the data set:

head(auto_test_results2)
##   mpg horsepower    .pred
## 1  17        140 15.69022
## 2  15        198 12.79238
## 3  14        220 13.87964
## 4  15        190 12.69516
## 5  15        170 13.14781
## 6  14        160 13.74682

We can use {yardstick} package to compute model evaluation metrics. For example rmse() computes the square of the mean squared error:

auto_test_results2 %>% 
  rmse(truth = mpg, estimate = .pred)
## # A tibble: 1 × 3
##   .metric .estimator .estimate
##   <chr>   <chr>          <dbl>
## 1 rmse    standard        4.12

This is better than the linear model without the quadratic term.

auto_test_results2 %>%
  rsq(truth = mpg, estimate = .pred)  
## # A tibble: 1 × 3
##   .metric .estimator .estimate
##   <chr>   <chr>          <dbl>
## 1 rsq     standard       0.712
ggplot(auto_test_results2, aes(x = mpg, y = .pred)) +
  geom_point() +
  geom_abline(color = 'blue', linetype = 2) +
  coord_obs_pred() +
  labs(title = 'R-Squared Plot',
       y = 'Predicted MPG',
       x = 'Actual MPG')

Also the R-squared is now higher.

The last_fit() function from the {tune} package can be used to streamline the model fitting after determining the final model. The last_fit() function takes a model specification, model formula, and data split object and performs the following:

  1. Creates training and test datasets

  2. Fits the model to the training data

  3. Calculates metrics and predictions on the test data

  4. Returns an object with all results

lm_last_fit <- lm_model %>%
  last_fit(mpg ~ horsepower + I(horsepower^2), 
           split = auto_split)

The tune::collect_metrics() function computes model evaluation metrics:

lm_last_fit %>% 
  collect_metrics()
## # A tibble: 2 × 4
##   .metric .estimator .estimate .config             
##   <chr>   <chr>          <dbl> <chr>               
## 1 rmse    standard       4.12  Preprocessor1_Model1
## 2 rsq     standard       0.712 Preprocessor1_Model1

The tune::collect_predictions() function creates a tibble containing predictions and actual values:

lm_last_fit %>% 
  collect_predictions()
## # A tibble: 100 × 5
##    .pred id                .row   mpg .config             
##    <dbl> <chr>            <int> <dbl> <chr>               
##  1  15.7 train/test split     5    17 Preprocessor1_Model1
##  2  12.8 train/test split     6    15 Preprocessor1_Model1
##  3  13.9 train/test split     7    14 Preprocessor1_Model1
##  4  12.7 train/test split    10    15 Preprocessor1_Model1
##  5  13.1 train/test split    11    15 Preprocessor1_Model1
##  6  13.7 train/test split    12    14 Preprocessor1_Model1
##  7  23.2 train/test split    17    18 Preprocessor1_Model1
##  8  26.2 train/test split    18    21 Preprocessor1_Model1
##  9  38.1 train/test split    20    26 Preprocessor1_Model1
## 10  24.9 train/test split    25    21 Preprocessor1_Model1
## # ℹ 90 more rows

Conducting k-fold cross-validation in the Tidymodels:

We first create folds. Here I use k=5:

set.seed(12)
folds <- vfold_cv(auto_train, v = 5)
folds
## #  5-fold cross-validation 
## # A tibble: 5 × 2
##   splits           id   
##   <list>           <chr>
## 1 <split [233/59]> Fold1
## 2 <split [233/59]> Fold2
## 3 <split [234/58]> Fold3
## 4 <split [234/58]> Fold4
## 5 <split [234/58]> Fold5

Then we create a model or workflow and estimate the model for each fold:

auto_wf <- workflow() %>% 
  add_model(lm_model) %>% 
  add_formula(mpg ~ horsepower + I(horsepower^2))
auto_wf
## ══ Workflow ════════════════════════════════════════════════════════════════════
## Preprocessor: Formula
## Model: linear_reg()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## mpg ~ horsepower + I(horsepower^2)
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Linear Regression Model Specification (regression)
## 
## Computational engine: lm
auto_fit_rs <- auto_wf %>% 
  fit_resamples(folds)
auto_fit_rs
## # Resampling results
## # 5-fold cross-validation 
## # A tibble: 5 × 4
##   splits           id    .metrics         .notes          
##   <list>           <chr> <list>           <list>          
## 1 <split [233/59]> Fold1 <tibble [2 × 4]> <tibble [0 × 3]>
## 2 <split [233/59]> Fold2 <tibble [2 × 4]> <tibble [0 × 3]>
## 3 <split [234/58]> Fold3 <tibble [2 × 4]> <tibble [0 × 3]>
## 4 <split [234/58]> Fold4 <tibble [2 × 4]> <tibble [0 × 3]>
## 5 <split [234/58]> Fold5 <tibble [2 × 4]> <tibble [0 × 3]>
collect_metrics(auto_fit_rs)
## # A tibble: 2 × 6
##   .metric .estimator  mean     n std_err .config             
##   <chr>   <chr>      <dbl> <int>   <dbl> <chr>               
## 1 rmse    standard   4.46      5  0.225  Preprocessor1_Model1
## 2 rsq     standard   0.689     5  0.0240 Preprocessor1_Model1

These are the average metrics over 5 folds.