library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.3.3
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::select() masks MASS::select()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(class)
library(e1071)
## Warning: package 'e1071' was built under R version 4.3.3

Lab 5

Question 13: This question should be answered using the Weekly data set, which is part of the ISLR2 package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.

  1. Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
cor(Weekly[,-9])
##               Year         Lag1        Lag2        Lag3         Lag4
## Year    1.00000000 -0.032289274 -0.03339001 -0.03000649 -0.031127923
## Lag1   -0.03228927  1.000000000 -0.07485305  0.05863568 -0.071273876
## Lag2   -0.03339001 -0.074853051  1.00000000 -0.07572091  0.058381535
## Lag3   -0.03000649  0.058635682 -0.07572091  1.00000000 -0.075395865
## Lag4   -0.03112792 -0.071273876  0.05838153 -0.07539587  1.000000000
## Lag5   -0.03051910 -0.008183096 -0.07249948  0.06065717 -0.075675027
## Volume  0.84194162 -0.064951313 -0.08551314 -0.06928771 -0.061074617
## Today  -0.03245989 -0.075031842  0.05916672 -0.07124364 -0.007825873
##                Lag5      Volume        Today
## Year   -0.030519101  0.84194162 -0.032459894
## Lag1   -0.008183096 -0.06495131 -0.075031842
## Lag2   -0.072499482 -0.08551314  0.059166717
## Lag3    0.060657175 -0.06928771 -0.071243639
## Lag4   -0.075675027 -0.06107462 -0.007825873
## Lag5    1.000000000 -0.05851741  0.011012698
## Volume -0.058517414  1.00000000 -0.033077783
## Today   0.011012698 -0.03307778  1.000000000
pairs(Weekly)

  • Looking at the correlation matrix and the pairwise plots, it does not look like their are any significant relations other than between Year and Volume. Year and Volume have a correlation coefficient of .842 which means that there is a strong positive relationship between the two.
  1. Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically significant? If so, which ones?
log_model <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, family = binomial)
summary(log_model)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Weekly)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.26686    0.08593   3.106   0.0019 **
## Lag1        -0.04127    0.02641  -1.563   0.1181   
## Lag2         0.05844    0.02686   2.175   0.0296 * 
## Lag3        -0.01606    0.02666  -0.602   0.5469   
## Lag4        -0.02779    0.02646  -1.050   0.2937   
## Lag5        -0.01447    0.02638  -0.549   0.5833   
## Volume      -0.02274    0.03690  -0.616   0.5377   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1486.4  on 1082  degrees of freedom
## AIC: 1500.4
## 
## Number of Fisher Scoring iterations: 4
  • We only see one predictor that is statistically significant. This is Lag2 with a p-value of .0296.
  1. Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.
log_prob <- predict(log_model, type = "response")
log_pred <- rep("Down", length(log_prob))
log_pred[log_prob > 0.5] = "Up"
table(log_pred, Weekly$Direction)
##         
## log_pred Down  Up
##     Down   54  48
##     Up    430 557
  • This means that we had 54 correct predictions when the market had negative return, and 557 correct predictions for positive return. We also see that we had 48 false negative and 430 false positive predictions. This model mis-classifies 56.1% of the time ((48+430)/ (54+48+430+557)).
  1. Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010).
train_week <- (Weekly$Year < 2009)
Weekly.train <- Weekly[train_week,]
Weekly.test <- Weekly[!train_week,]

log_fit <- glm(Direction ~ Lag2, data = Weekly.train, family = binomial)
log_prob2 <- predict(log_fit, Weekly.test, type = "response")
log_pred2 <- rep("Down", length(log_prob2))
log_pred2[log_prob2> 0.5] = "Up"
direction_week <- Weekly$Direction[!train_week]
table(log_pred2, direction_week)
##          direction_week
## log_pred2 Down Up
##      Down    9  5
##      Up     34 56
#Logistic Regression Accuracy
mean(log_pred2 == direction_week)
## [1] 0.625
  1. Repeat (d) using LDA.
lda_fit <- lda(Direction ~ Lag2, data = Weekly, subset = train_week)
lda_prob <- predict(lda_fit, Weekly.test)
lda_class <- lda_prob$class
table(lda_class, Weekly.test$Direction)
##          
## lda_class Down Up
##      Down    9  5
##      Up     34 56
#LDA Accuracy
mean(lda_class == direction_week)
## [1] 0.625
  1. Repeat (d) using QDA.
qda_fit <- qda(Direction ~ Lag2, data = Weekly, subset = train_week)
qda_prob <- predict(qda_fit, Weekly.test)$class
table(qda_prob, Weekly.test$Direction)
##         
## qda_prob Down Up
##     Down    0  0
##     Up     43 61
#QDA Accuracy
mean(qda_prob == direction_week)
## [1] 0.5865385
  1. Repeat (d) using KNN with K = 1.
train_data <- as.matrix(Weekly$Lag2[train_week])
test_data <- as.matrix(Weekly$Lag2[!train_week])
train_direction <- Weekly$Direction[train_week]
set.seed(1)
knn_pred <- knn(train_data, test_data, train_direction, k = 1)
table(knn_pred, Weekly.test$Direction)
##         
## knn_pred Down Up
##     Down   21 30
##     Up     22 31
#KNN Accuracy
mean(knn_pred == direction_week)
## [1] 0.5
  1. Repeat (d) using naive Bayes.
nb_fit <- naiveBayes(Direction ~ Lag2, data = Weekly,
subset = train_week)
nb_class <- predict(nb_fit, Weekly.test)
table(nb_class, Weekly.test$Direction)
##         
## nb_class Down Up
##     Down    0  0
##     Up     43 61
#Naive Bayes Accuracy
mean(nb_class == direction_week)
## [1] 0.5865385
  1. Which of these methods appears to provide the best results on this data?
  • Based on the created models and calculated accuracys, we see that none of the models perform great. All accuracies are close to 0.5 which is what we could expect by random chance. The second logistic regression and LDA model perform the best with 62.5% accuracy. This is not great, but one of these would be the best option of those calculated.
  1. Experiment with the different combinations of predictors, including possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Note that you should also experiment with the values for K in the KNN classifier.
#Log Regression with interaction between Lag1 and Lag2
log_fits_3 <- glm(Direction~Lag1 + Lag2 + Lag1:Lag2, data = Weekly.train, family = binomial)
log_probs_3 <- predict(log_fits_3, Weekly.test, type = 'response')
log_pred_3 <- rep('Down', length(log_probs_3))
log_pred_3[log_probs_3>0.5] = "Up"
table(log_pred_3, Weekly.test$Direction)
##           
## log_pred_3 Down Up
##       Down    7  8
##       Up     36 53
mean(log_pred_3 == direction_week)
## [1] 0.5769231
#Log Regression with Lag1 and Lag 2 squared
log_fits_4 <- glm(Direction~Lag1**2+Lag2**2, data = Weekly.train, family = binomial)
log_probs_4 <- predict(log_fits_4, Weekly.test, type = 'response')
log_pred_4 <- rep('Down', length(log_probs_4))
log_pred_4[log_probs_4>0.5] = "Up"
table(log_pred_4, Weekly.test$Direction)
##           
## log_pred_4 Down Up
##       Down    7  8
##       Up     36 53
mean(log_pred_4 == direction_week)
## [1] 0.5769231
#LDA with 5 predictors
lda_fits_5 <- lda(Direction~Lag1+Lag2+Lag3+Lag4+Lag5, data = Weekly, subset = train_week)
lda_prob_5 <- predict(lda_fits_5, Weekly.test)
lda_class_5 <- lda_prob_5$class
table(lda_class_5, Weekly.test$Direction)
##            
## lda_class_5 Down Up
##        Down    9 13
##        Up     34 48
mean(lda_class_5 == direction_week)
## [1] 0.5480769
#QDA with 3 predictors
qda_fits_6 <- qda(Direction~Lag1+Lag2+Lag3, data = Weekly, subset = train_week)
qda_prob_6 <- predict(qda_fits_6, Weekly.test)
qda_class_6 <- qda_prob_6$class
table(qda_class_6, Weekly.test$Direction)
##            
## qda_class_6 Down Up
##        Down    6 10
##        Up     37 51
mean(qda_class_6 == direction_week)
## [1] 0.5480769
#K=3
set.seed(1)
knn_pred_7 <- knn(train_data, test_data, train_direction, k=3)
table(knn_pred_7, Weekly.test$Direction)
##           
## knn_pred_7 Down Up
##       Down   16 20
##       Up     27 41
mean(knn_pred_7 == direction_week)
## [1] 0.5480769
#K=5
set.seed(1)
knn_pred_8 <- knn(train_data, test_data, train_direction, k=5)
table(knn_pred_8, Weekly.test$Direction)
##           
## knn_pred_8 Down Up
##       Down   16 21
##       Up     27 40
mean(knn_pred_8 == direction_week)
## [1] 0.5384615
  • Based on these models, the two logistic regression models performed the best at 57.69% accuracy.

Question 14: In this problem you will develop a model to predict whether a given car gets high or low gas mileage based on the Auto data set.

  1. Create a binary variable, mpg01, that contains a 1 if mpg contains a value above its median, and a 0 if mpg contains a value below its median. You can compute the median using the median() function. Note you may find it helpful to use the data.frame() function to create a single data set containing both mpg01 and the other Auto variables.
data("Auto")
mpg01 <- rep(0, length(Auto$mpg))
mpg01[Auto$mpg > median(Auto$mpg)] <- 1
Auto <- data.frame(Auto, mpg01)
summary(Auto)
##       mpg          cylinders      displacement     horsepower        weight    
##  Min.   : 9.00   Min.   :3.000   Min.   : 68.0   Min.   : 46.0   Min.   :1613  
##  1st Qu.:17.00   1st Qu.:4.000   1st Qu.:105.0   1st Qu.: 75.0   1st Qu.:2225  
##  Median :22.75   Median :4.000   Median :151.0   Median : 93.5   Median :2804  
##  Mean   :23.45   Mean   :5.472   Mean   :194.4   Mean   :104.5   Mean   :2978  
##  3rd Qu.:29.00   3rd Qu.:8.000   3rd Qu.:275.8   3rd Qu.:126.0   3rd Qu.:3615  
##  Max.   :46.60   Max.   :8.000   Max.   :455.0   Max.   :230.0   Max.   :5140  
##                                                                                
##   acceleration        year           origin                      name    
##  Min.   : 8.00   Min.   :70.00   Min.   :1.000   amc matador       :  5  
##  1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000   ford pinto        :  5  
##  Median :15.50   Median :76.00   Median :1.000   toyota corolla    :  5  
##  Mean   :15.54   Mean   :75.98   Mean   :1.577   amc gremlin       :  4  
##  3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000   amc hornet        :  4  
##  Max.   :24.80   Max.   :82.00   Max.   :3.000   chevrolet chevette:  4  
##                                                  (Other)           :365  
##      mpg01    
##  Min.   :0.0  
##  1st Qu.:0.0  
##  Median :0.5  
##  Mean   :0.5  
##  3rd Qu.:1.0  
##  Max.   :1.0  
## 
  1. Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seems most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.
cor(Auto[, -9])
##                     mpg  cylinders displacement horsepower     weight
## mpg           1.0000000 -0.7776175   -0.8051269 -0.7784268 -0.8322442
## cylinders    -0.7776175  1.0000000    0.9508233  0.8429834  0.8975273
## displacement -0.8051269  0.9508233    1.0000000  0.8972570  0.9329944
## horsepower   -0.7784268  0.8429834    0.8972570  1.0000000  0.8645377
## weight       -0.8322442  0.8975273    0.9329944  0.8645377  1.0000000
## acceleration  0.4233285 -0.5046834   -0.5438005 -0.6891955 -0.4168392
## year          0.5805410 -0.3456474   -0.3698552 -0.4163615 -0.3091199
## origin        0.5652088 -0.5689316   -0.6145351 -0.4551715 -0.5850054
## mpg01         0.8369392 -0.7591939   -0.7534766 -0.6670526 -0.7577566
##              acceleration       year     origin      mpg01
## mpg             0.4233285  0.5805410  0.5652088  0.8369392
## cylinders      -0.5046834 -0.3456474 -0.5689316 -0.7591939
## displacement   -0.5438005 -0.3698552 -0.6145351 -0.7534766
## horsepower     -0.6891955 -0.4163615 -0.4551715 -0.6670526
## weight         -0.4168392 -0.3091199 -0.5850054 -0.7577566
## acceleration    1.0000000  0.2903161  0.2127458  0.3468215
## year            0.2903161  1.0000000  0.1815277  0.4299042
## origin          0.2127458  0.1815277  1.0000000  0.5136984
## mpg01           0.3468215  0.4299042  0.5136984  1.0000000
pairs(Auto)

par(mfrow=c(2,3))
boxplot(cylinders ~ mpg01, data = Auto, main = "Cylinders vs mpg01")
boxplot(displacement ~ mpg01, data = Auto, main = "Displacement vs mpg01")
boxplot(horsepower ~ mpg01, data = Auto, main = "Horsepower vs mpg01")
boxplot(weight ~ mpg01, data = Auto, main = "Weight vs mpg01")
boxplot(acceleration ~ mpg01, data = Auto, main = "Acceleration vs mpg01")
boxplot(year ~ mpg01, data = Auto, main = "Year vs mpg01")

  • The graphs indicate that the strongest predictors of mpg01 are cylinders, displacement, and weight which all have negative relationships around -0.75.
  1. Split the data into a training set and a test set.
set.seed(123)
train <- sample(1:dim(Auto)[1], dim(Auto)[1]*.7, rep=FALSE)
test <- -train
training_data<- Auto[train, ]
testing_data= Auto[test, ]
mpg01.test <- mpg01[test]
  1. Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
lda_model <- lda(mpg01 ~ cylinders + displacement + weight, data = training_data)
pred_lda <- predict(lda_model, testing_data)
table(pred_lda$class, mpg01.test)
##    mpg01.test
##      0  1
##   0 50  4
##   1 10 54
#LDA Test Error
mean(pred_lda$class != mpg01.test)
## [1] 0.1186441
  • The test error of this model is 11.86%.
  1. Perform QDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
qda_model <- qda(mpg01 ~ cylinders + displacement + weight, data = training_data)
pred_qda <- predict(qda_model, testing_data)
table(pred_qda$class, mpg01.test)
##    mpg01.test
##      0  1
##   0 54  4
##   1  6 54
#QDA Test Error
mean(pred_qda$class != mpg01.test)
## [1] 0.08474576
  • The test error of this model is 8.47%.
  1. Perform logistic regression on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
glm_model <- glm(mpg01 ~ cylinders + displacement + weight, data = training_data, family = binomial)
probs <- predict(glm_model, testing_data, type = "response")
pred_glm <- rep(0, length(probs))
pred_glm[probs > 0.5] <- 1
table(pred_glm, mpg01.test)
##         mpg01.test
## pred_glm  0  1
##        0 52  5
##        1  8 53
#Logistic Regression Test Error
mean(pred_glm != mpg01.test)
## [1] 0.1101695
  • The test error of this model is 11.02%.
  1. Perform naive Bayes on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?
nb_model <- naiveBayes(mpg01 ~ cylinders + displacement + weight, data = training_data)
nb_pred <- predict(nb_model, testing_data)
table(nb_pred, mpg01.test)
##        mpg01.test
## nb_pred  0  1
##       0 52  4
##       1  8 54
#Naive Bayes Test Error
mean(nb_pred != mpg01.test)
## [1] 0.1016949
  • The test error of this model is 10.17%.
  1. perform KNN on the training data, with several values of K, in order to predict mpg01. Use only the variables that seemed most associated with mpg01 in (b). What test errors do you obtain? Which value of K seems to perform the best on this data set?
data = scale(Auto[,-c(9,10)])
set.seed(1234)
train <- sample(1:dim(Auto)[1], 392*.7, rep=FALSE)
test <- -train
training_data = data[train,c("cylinders","displacement","weight")]
testing_data = data[test, c("cylinders", "displacement","weight")]
train.mpg01 = Auto$mpg01[train]
test.mpg01= Auto$mpg01[test]

set.seed(1234)
knn_pred_y = knn(training_data, testing_data, train.mpg01, k = 1)
table(knn_pred_y, test.mpg01)
##           test.mpg01
## knn_pred_y  0  1
##          0 55  8
##          1  9 46
#KNN Test Error with K = 1
mean(knn_pred_y != test.mpg01)
## [1] 0.1440678
  • The test error for this model is 14.41%.
knn_pred_y = NULL
error_rate = NULL
for(i in 1:dim(testing_data)[1]){
set.seed(1234)
knn_pred_y = knn(training_data,testing_data,train.mpg01,k=i)
error_rate[i] = mean(test.mpg01 != knn_pred_y)
}
min_error_rate = min(error_rate)
print(min_error_rate)
## [1] 0.1101695
K = which(error_rate == min_error_rate)
print(K)
## [1]  10 112 113
  • The lowest test error is 11.02% when K = 10.