library(ISLR2)
library(corrplot)
## corrplot 0.92 loaded
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✔ ggplot2 3.3.5     ✔ purrr   0.3.4
## ✔ tibble  3.1.6     ✔ dplyr   1.0.7
## ✔ tidyr   1.2.0     ✔ stringr 1.4.0
## ✔ readr   2.1.2     ✔ forcats 0.5.1
## Warning: package 'tidyr' was built under R version 4.0.5
## Warning: package 'readr' was built under R version 4.0.5
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(openintro)
## Loading required package: airports
## Loading required package: cherryblossom
## Loading required package: usdata
library(MASS)
## 
## Attaching package: 'MASS'
## The following objects are masked from 'package:openintro':
## 
##     housing, mammals
## The following object is masked from 'package:dplyr':
## 
##     select
## The following object is masked from 'package:ISLR2':
## 
##     Boston
library(class)
library(e1071)

 

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.

summary(Weekly)
##       Year           Lag1               Lag2               Lag3         
##  Min.   :1990   Min.   :-18.1950   Min.   :-18.1950   Min.   :-18.1950  
##  1st Qu.:1995   1st Qu.: -1.1540   1st Qu.: -1.1540   1st Qu.: -1.1580  
##  Median :2000   Median :  0.2410   Median :  0.2410   Median :  0.2410  
##  Mean   :2000   Mean   :  0.1506   Mean   :  0.1511   Mean   :  0.1472  
##  3rd Qu.:2005   3rd Qu.:  1.4050   3rd Qu.:  1.4090   3rd Qu.:  1.4090  
##  Max.   :2010   Max.   : 12.0260   Max.   : 12.0260   Max.   : 12.0260  
##       Lag4               Lag5              Volume            Today         
##  Min.   :-18.1950   Min.   :-18.1950   Min.   :0.08747   Min.   :-18.1950  
##  1st Qu.: -1.1580   1st Qu.: -1.1660   1st Qu.:0.33202   1st Qu.: -1.1540  
##  Median :  0.2380   Median :  0.2340   Median :1.00268   Median :  0.2410  
##  Mean   :  0.1458   Mean   :  0.1399   Mean   :1.57462   Mean   :  0.1499  
##  3rd Qu.:  1.4090   3rd Qu.:  1.4050   3rd Qu.:2.05373   3rd Qu.:  1.4050  
##  Max.   : 12.0260   Max.   : 12.0260   Max.   :9.32821   Max.   : 12.0260  
##  Direction 
##  Down:484  
##  Up  :605  
##            
##            
##            
## 

 

(a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?

pairs(Weekly)

cor(subset(Weekly, select = -Direction))
##               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

 

(b) 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.reg<- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,data = Weekly,family = binomial)
summary(log.reg)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Weekly)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6949  -1.2565   0.9913   1.0849   1.4579  
## 
## 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

 

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

Weekly.prob= predict(log.reg, type='response')
Weekly.pred =rep("Down", length(Weekly.prob))
Weekly.pred[Weekly.prob > 0.5] = "Up"
table(Weekly.pred, Weekly$Direction)
##            
## Weekly.pred Down  Up
##        Down   54  48
##        Up    430 557
mean(Weekly.pred == Weekly$Direction)
## [1] 0.5610652

 

(d) 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 <- (Weekly$Year < 2009)
train_set <- Weekly[train, ]
test_set <- Weekly[!train, ]
train.logit <- glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = train)
predict_glm_direction <- function(model, newdata = NULL) {
  predictions <- predict(model, newdata, type="response")
  return(as.factor(ifelse(predictions < 0.5, "Down", "Up")))
}
direction.pred <- predict_glm_direction(train.logit, test_set)
table(direction.pred, test_set$Direction)
##               
## direction.pred Down Up
##           Down    9  5
##           Up     34 56
mean(direction.pred == test_set$Direction)
## [1] 0.625

 

(e) Repeat (d) using LDA.

weekly.lda <- lda(Direction ~ Lag2, data = Weekly, subset = train)
weekly.lda
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
## 
## Coefficients of linear discriminants:
##            LD1
## Lag2 0.4414162
lda.pred = predict(weekly.lda, Weekly[!train, ])
table(lda.pred$class, Weekly[!train, ]$Direction)
##       
##        Down Up
##   Down    9  5
##   Up     34 56
mean(lda.pred$class == Weekly[!train, ]$Direction)
## [1] 0.625

 

(f) Repeat (d) using QDA.

weekly.qda = qda(Direction ~ Lag2, data = Weekly, subset = train)
weekly.qda
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
qda.pred = predict(weekly.qda, Weekly[!train, ])
table(qda.pred$class, Weekly[!train, ]$Direction)
##       
##        Down Up
##   Down    0  0
##   Up     43 61
mean(qda.pred$class == Weekly[!train, ]$Direction)
## [1] 0.5865385

 

(g) Repeat (d) using KNN with K = 1.

train.knn= data.frame(Weekly[train, ]$Lag2)
test.knn= data.frame(Weekly[!train, ]$Lag2)
direction.train = Weekly[train, ]$Direction
set.seed(1)
knn.pred = knn(train.knn, test.knn, direction.train, k = 1)
table(knn.pred, Weekly[!train, ]$Direction)
##         
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred == Weekly[!train, ]$Direction)
## [1] 0.5

 

(h) Repeat (d) using naive Bayes.

weekly.nbayes = naiveBayes(Direction~Lag2 ,data=Weekly ,subset=train)
weekly.nbayes
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Conditional probabilities:
##       Lag2
## Y             [,1]     [,2]
##   Down -0.03568254 2.199504
##   Up    0.26036581 2.317485
nbayes.pred=predict(weekly.nbayes ,Weekly[!train ,])
table(nbayes.pred ,Weekly$Direction[!train])
##            
## nbayes.pred Down Up
##        Down    0  0
##        Up     43 61
mean(nbayes.pred == Weekly[!train, ]$Direction)
## [1] 0.5865385

 

(i) Which of these methods appears to provide the best results on this data?

 

(j) Experiment with 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 values for K in the KNN classifier.

train.knn= data.frame(Weekly[train, ]$Lag2)
test.knn= data.frame(Weekly[!train, ]$Lag2)
direction.train = Weekly[train, ]$Direction
set.seed(1)
knn.pred2 = knn(train.knn, test.knn, direction.train, k = 10)
table(knn.pred2, Weekly[!train, ]$Direction)
##          
## knn.pred2 Down Up
##      Down   17 21
##      Up     26 40
mean(knn.pred == Weekly[!train, ]$Direction)
## [1] 0.5

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.

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

 

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

Auto$mpg01 <- Auto$mpg > median(Auto$mpg)
head(Auto$mpg01, n = 20)
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE  TRUE
head(Auto[,c(1,10)],5)
##   mpg mpg01
## 1  18 FALSE
## 2  15 FALSE
## 3  18 FALSE
## 4  16 FALSE
## 5  17 FALSE

 

(b) Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.

cor(subset(Auto, select = -name))
##                     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)

- based on these results: cylinders, weight, displacement, horsepower, and mpg seem to be most likely to be useful in predicting mpg01.

 

(c) Split the data into a training set and a test set.

train <- sample(nrow(Auto) * 0.7)
train_set <- Auto[train, ]
test_set <- Auto[-train, ]

Auto.lda <- lda(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto,subset = train)

 

(d) 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?

show_model_performance <- function(predicted_status, observed_status) {
  confusion_matrix <- table(predicted_status, 
                            observed_status, 
                            dnn = c("Predicted Status", "Observed Status"))
  print(confusion_matrix)
  
  error_rate <- mean(predicted_status != observed_status)

  cat("\n") # \n means newline so it just prints a blank line
  cat("         Error Rate:", 100 * error_rate, "%\n")
  cat("Correctly Predicted:", 100 * (1-error_rate), "%\n")
  cat("False Positive Rate:", 100 * confusion_matrix[2,1] / sum(confusion_matrix[,1]), "%\n")
  cat("False Negative Rate:", 100 * confusion_matrix[1,2] / sum(confusion_matrix[,2]), "%\n")
}
predictions <- predict(Auto.lda, test_set)
show_model_performance(predictions$class, test_set$mpg01)
##                 Observed Status
## Predicted Status FALSE TRUE
##            FALSE    18   16
##            TRUE      2   82
## 
##          Error Rate: 15.25424 %
## Correctly Predicted: 84.74576 %
## False Positive Rate: 10 %
## False Negative Rate: 16.32653 %

 

(e) 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?

Auto.qda <- qda(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto, subset = train)
predictions <- predict(Auto.qda, test_set)
show_model_performance(predictions$class, test_set$mpg01)
##                 Observed Status
## Predicted Status FALSE TRUE
##            FALSE    18   19
##            TRUE      2   79
## 
##          Error Rate: 17.79661 %
## Correctly Predicted: 82.20339 %
## False Positive Rate: 10 %
## False Negative Rate: 19.38776 %

 

(f) 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?

Auto.logit <- glm(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto, family = binomial, subset =train)
predictions <- predict(Auto.logit, test_set, type = "response")
show_model_performance(predictions > 0.5, test_set$mpg01)
##                 Observed Status
## Predicted Status FALSE TRUE
##            FALSE    20   21
##            TRUE      0   77
## 
##          Error Rate: 17.79661 %
## Correctly Predicted: 82.20339 %
## False Positive Rate: 0 %
## False Negative Rate: 21.42857 %

 

(g) 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?

Auto.nb <- naiveBayes(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto, family = binomial, subset =train)
predictions.nb <- predict(Auto.nb, test_set)
table(predictions.nb, test_set$mpg01)
##               
## predictions.nb FALSE TRUE
##          FALSE    18   14
##          TRUE      2   84
mean(predictions.nb == test_set$mpg01)
## [1] 0.8644068

-86.44% correctly predicted.

 

(h) 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(55)
train.auto <- sample(1:dim(Auto)[1], 392*.7, rep=FALSE)
test.auto <- -train
training_data = data[train.auto,c("cylinders","horsepower","weight","acceleration")]
testing_data = data[test.auto, c("cylinders", "horsepower","weight","acceleration")]

train.mpg01 = Auto$mpg01[train.auto]

test.mpg01= Auto$mpg01[test.auto]
set.seed(50)
knn.auto.pred = knn(training_data, testing_data, train.mpg01, k = 1)
table(knn.auto.pred, test.mpg01)
##              test.mpg01
## knn.auto.pred FALSE TRUE
##         FALSE    18    8
##         TRUE      2   90
mean(knn.auto.pred != test.mpg01)
## [1] 0.08474576
set.seed(50)
knn.auto.pred2 = knn(training_data, testing_data, train.mpg01, k = 10)
table(knn.auto.pred2, test.mpg01)
##               test.mpg01
## knn.auto.pred2 FALSE TRUE
##          FALSE    18   15
##          TRUE      2   83
mean(knn.auto.pred2 != test.mpg01)
## [1] 0.1440678

Question 16: Using the Boston data set, fit classification models in order to predict whether a given census tract has a crime rate above or below the median. Explore logistic regression, LDA, naive Bayes, and KNN models using various subsets of the predictors. Describe your findings.

data("Boston")
attach(Boston)
crime1 = rep(0, length(crim))
crime1[crim>median(crim)] = 1
Boston = data.frame(Boston, crime1)
train = 1:(dim(Boston)[1]/2)
test = (dim(Boston)[1]/2+1):dim(Boston)[1]
Boston_train = Boston[train,]
Boston_test = Boston[test,]
crime1.test = crime1[test]
plot(Boston)

 

Logistic Regression

set.seed(1)
Boston.logit = glm(crime1~nox + tax + dis + medv + lstat, data = Boston, family = binomial)
Boston.probs = predict(Boston.logit, Boston_test, type ="response")
Boston.pred = rep(0, length(Boston.probs))
Boston.pred[Boston.probs > 0.5] = 1
table(Boston.pred, crime1.test)
##            crime1.test
## Boston.pred   0   1
##           0  75  15
##           1  15 148
mean(Boston.pred == crime1.test)
## [1] 0.8814229

 

LDA

Boston.lda = lda(crime1~nox+tax+dis+medv+lstat, data =  Boston_train)
Boston.pred.lda = predict(Boston.lda, Boston_test)
table(Boston.pred.lda$class, crime1.test)
##    crime1.test
##       0   1
##   0  80  16
##   1  10 147
mean(Boston.pred.lda$class == crime1.test)
## [1] 0.8972332

-89.7% was correctly predicted

 

K-Nearest Neighbor

train.B2= cbind(nox,tax,dis,lstat)[train,]
test.B2 = cbind(nox,tax,dis,lstat)[test,]
train.crime = crime1.test
set.seed(1)

Boston.pred.knn = knn(train.B2, test.B2, train.crime, k=10)
table(Boston.pred.knn, crime1.test)
##                crime1.test
## Boston.pred.knn   0   1
##               0  43  21
##               1  47 142
mean(Boston.pred.knn == crime1.test)
## [1] 0.7312253

 

Naive Bayes

Bostob.nb = naiveBayes(crime1~nox+tax+dis+lstat, data = Boston, subset = train)
Boston.pred.nb = predict(Bostob.nb, Boston_test)
table(Boston.pred.nb, crime1.test)
##               crime1.test
## Boston.pred.nb   0   1
##              0  75  18
##              1  15 145
mean(Boston.pred.nb == crime1.test)
## [1] 0.8695652