<style type="text/css"> 
body{
  background-color: #FAFAFA;
  font-size: 18px;
  line-height: 1.8; 
}
code.r{
  font-size: 12pt;
}
</style>

```{r setup, include=FALSE}
# knitr::opts_chunk$set(echo = TRUE, results = 'asis', fig.show = 'asis')
knitr::opts_chunk$set(echo = TRUE, message=FALSE, warning=FALSE)
``` 

<br/>
<br/>



# 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). 

```{r}
library(ISLR) 
# randomly select observations to be included
# in the training set
set.seed(1)
train <- sample(392,196)
```

```{r}
# Estimate the model using only training data
lmfit <- lm(mpg ~ horsepower,data = Auto, subset = train)
```

```{r}
# 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)
#
# or in one line - but harder to grasp
# mean((Auto$mpg-predict(lmfit,Auto))[-train]^2)
```

Similarly, for quadratic and cubic regressions: 
```{r}
lm.fit2 <- lm(mpg~poly(horsepower,2),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit2,Auto))[-train]^2)
```

```{r}
lm.fit3 <- lm(mpg~poly(horsepower,3),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit3,Auto))[-train]^2)
```

Choose another validation set and compute MSE
```{r}
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)

```

```{r}
lm.fit2 <- lm(mpg~poly(horsepower,2),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit2,Auto))[-train]^2)

```

```{r}
lm.fit3 <- lm(mpg~poly(horsepower,3),data=Auto,subset=train)
mean((Auto$mpg-predict(lm.fit3,Auto))[-train]^2)
```

```{r message=FALSE, warning=FALSE}
# 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
```{r}
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
```

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


# 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: 
```{r}
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
```

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: 
```{r}
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
```

We can do these in a loop over the flexibility of the model (degree d): 
```{r}
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
```

```{r}
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()`: 
```{r}
glm.fit <- glm(mpg ~ horsepower, data = Auto)
coef(glm.fit)
```


```{r}
lm.fit <- lm(mpg ~ horsepower, data = Auto)
coef(lm.fit)
```

The usage of `cv.glm()`:
```{r}
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
```

`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: 

```{r}
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
```

# K-fold Cross-Validation

```{r}
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
MSE_kfoldcv_degree1 <- mean(kfoldcv)
MSE_kfoldcv_degree1
```



```{r}
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
```

# 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.  
```{r}
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 
```{r}
cor(LSAT,GPA)
```

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. 

```{r}
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))
summary(bootsample)
```

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()`.

```{r}

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)
```


## Estimating the Accuracy of a Linear Regression Model


```{r}
boot.fn=function(data,index)
  return(coef(lm(mpg ~ horsepower, data=data, subset=index)))
boot.fn(Auto,1:392)
```

```{r}
set.seed(1)
boot.fn(Auto,sample(392,392,replace=T))
boot.fn(Auto,sample(392,392,replace=T))
```

```{r}
boot(Auto,boot.fn,1000)
summary(lm(mpg ~ horsepower, data=Auto))$coef
```

```{r}
boot.fn=function(data,index)
  coefficients(lm(mpg ~ horsepower + I(horsepower^2), data=data, subset=index))
set.seed(1)
boot(Auto,boot.fn,1000)
summary(lm(mpg ~ horsepower + I(horsepower^2), data=Auto))$coef
```


# An Introduction to the Tidymodels


[Tidymodels](https://www.tidymodels.org/) 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 

![](img/tidymodels1.PNG) 

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


```{r}
# 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. 

```{r}
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
```{r}
auto_train <- auto_split %>% training()
head(auto_train)
```

And the test data set is 
```{r}
auto_test <- auto_split %>% testing()
head(auto_test)
```
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`
```{r}
lm_model <- linear_reg() %>%
  set_engine('lm') %>%
  set_mode('regression')
```

```{r}
lm_model
```

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

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


Make a pretty table: 
```{r}
tidy(auto_fit)
```


Now we trained our model. Let's compute predictions from the model using new data set (i.e, test data): 
```{r}
auto_preds <- auto_fit %>%
  predict(new_data = auto_test)
```

Look at the components of `auto_preds` object: 
```{r}
head(auto_preds)
```

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. 

```{r}
auto_test_results <- auto_test %>%
  select(mpg, horsepower) %>%
  bind_cols(auto_preds)
```

Check out the data set: 
```{r}
head(auto_test_results)
```

We can use `{yardstick}` package to compute model evaluation metrics. For example `rmse()` computes the square of the mean squared error: 
```{r}
auto_test_results %>% 
  rmse(truth = mpg, estimate = .pred)
```

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

Another metric we could use is the R-squared between truth and predictions. 
```{r}
auto_test_results %>%
  rsq(truth = mpg, estimate = .pred)  
```

We can also plot the predictions and truth: 
```{r}
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. 


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


Make a pretty table: 
```{r}
tidy(auto_fit2)
```


Now we trained our model. Let's compute predictions from the model using new data set (i.e, test data): 
```{r}
auto_preds2 <- auto_fit2 %>%
  predict(new_data = auto_test)
```

Look at the components of `auto_preds` object: 
```{r}
auto_preds2
```

```{r}
auto_test_results2 <- auto_test %>%
  select(mpg, horsepower) %>%
  bind_cols(auto_preds2)
```

Check out the data set: 
```{r}
head(auto_test_results2)
```

We can use `{yardstick}` package to compute model evaluation metrics. For example `rmse()` computes the square of the mean squared error: 
```{r}
auto_test_results2 %>% 
  rmse(truth = mpg, estimate = .pred)
```
This is better than the linear model without the quadratic term.   

```{r}
auto_test_results2 %>%
  rsq(truth = mpg, estimate = .pred)  
```
 
```{r}
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

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

The `tune::collect_metrics()` function computes model evaluation metrics: 
```{r}
lm_last_fit %>% 
  collect_metrics()
```

The `tune::collect_predictions()` function creates a tibble containing predictions and actual values: 
```{r}
lm_last_fit %>% 
  collect_predictions()
```


Conducting k-fold cross-validation in the Tidymodels: 

![](img/cv0-1.png) 

![](img/cv1-1.png)




We first create folds. Here I use k=5: 
```{r}
set.seed(12)
folds <- vfold_cv(auto_train, v = 5)
folds
```

Then we create a model or workflow and estimate the model for each fold: 
```{r}
auto_wf <- workflow() %>% 
  add_model(lm_model) %>% 
  add_formula(mpg ~ horsepower + I(horsepower^2))
auto_wf
```

```{r}
auto_fit_rs <- auto_wf %>% 
  fit_resamples(folds)
auto_fit_rs
```

```{r}
collect_metrics(auto_fit_rs)
```
These are the average metrics over 5 folds. 




<div class="tocify-extend-page" data-unique="tocify-extend-page" style="height: 0;"></div>

