Problem 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.

library(ISLR2)
attach(Weekly)

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

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

The only variables that appear to have any relation are Volume and Year.

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

glm.fits<-glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data=Weekly,family=binomial)
summary(glm.fits)
## 
## 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

The only variable that appears to be statistically significant is Lag2.

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

glm.probs<-predict(glm.fits, type="response")
glm.pred<-rep("Down",1089)
glm.pred[glm.probs > 0.5] = "Up"
table(glm.pred, Direction)
##         Direction
## glm.pred Down  Up
##     Down   54  48
##     Up    430 557

\(\frac{54+557}{54+48+430+557}=0.5611\) shows that 56.11% of the time the Direction was correctly predicted.
\(\frac{557}{48+557}=0.9207\) means Ups were correctly predicted 92.07% of the time.
\(\frac{54}{54+430}=0.1116\) means Downs were only correctly predicted 11.16% of the time.

(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<-(Year<2009)
Weekly.910 <-Weekly[!train,]
Direction.910<-Direction[!train]
glm.fits<-glm(Direction~Lag2, data=Weekly, family=binomial, subset=train)
glm.probs<-predict(glm.fits, Weekly.910, type="response")
glm.pred<-rep("Down", length(glm.probs))
glm.pred[glm.probs > 0.5] = "Up"
table(glm.pred, Direction.910)
##         Direction.910
## glm.pred Down Up
##     Down    9  5
##     Up     34 56
mean(glm.pred == Direction.910)
## [1] 0.625

By making a training subset with Lag2 as the predictor, we correctly predicted the Direction 62.5% of the time. \(\frac{56}{5+56}=0.9180\) means Ups were correctly predicted 91.8% of the time.
\(\frac{9}{9+34}=0.2093\) means Downs were only correctly predicted 20.93% of the time. This is an improvement from the previous model.

(e) Repeat (d) using LDA.

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
lda.fits<-lda(Direction~Lag2, data=Weekly, family=binomial, subset=train)
lda.pred<-predict(lda.fits, Weekly.910)
table(lda.pred$class, Direction.910)
##       Direction.910
##        Down Up
##   Down    9  5
##   Up     34 56
mean(lda.pred$class==Direction.910)
## [1] 0.625

The LDA produces similar results to the logistic model in (d).

(f) Repeat (d) using QDA.

qda.fits<-qda(Direction~Lag2, data=Weekly, subset=train)
qda.pred<-predict(qda.fits, Weekly.910)$class
table(qda.pred, Direction.910)
##         Direction.910
## qda.pred Down Up
##     Down    0  0
##     Up     43 61
mean(qda.pred==Direction.910)
## [1] 0.5865385

The QDA predicted everything as an Up, which has worse overall results than the previous models.

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

library(class)
train.X<-as.matrix(Lag2[train])
test.X<-as.matrix(Lag2[!train])
train.Direction<-Direction[train]
set.seed(1)
knn.pred<-knn(train.X, test.X, train.Direction, k=1)
table(knn.pred, Direction.910)
##         Direction.910
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred == Direction.910)
## [1] 0.5

The KNN model appears to be entirely random, with a 50% success rate.

(h) Repeat (d) using naive Bayes.

library(e1071)
nb.fits<-naiveBayes(Direction~Lag2, data=Weekly, subset=train)
nb.pred<-predict(nb.fits, Weekly.910)
table(nb.pred, Direction.910)
##        Direction.910
## nb.pred Down Up
##    Down    0  0
##    Up     43 61
mean(nb.pred == Direction.910)
## [1] 0.5865385

Naive Bayes also predicts everything as Up.

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

The logistic regression and the LDA appears to have the best results on the 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.

glm.fits<-glm(Direction~Lag2+Lag4, data=Weekly, family=binomial, subset=train)
glm.probs<-predict(glm.fits, Weekly.910, type="response")
glm.pred<-rep("Down", length(glm.probs))
glm.pred[glm.probs > 0.5] = "Up"
table(glm.pred, Direction.910)
##         Direction.910
## glm.pred Down Up
##     Down    8  4
##     Up     35 57
mean(glm.pred == Direction.910)
## [1] 0.625
lda.fits<-lda(Direction~Lag2+Lag3+Lag4, data=Weekly, family=binomial, subset=train)
lda.pred<-predict(lda.fits, Weekly.910)
table(lda.pred$class, Direction.910)
##       Direction.910
##        Down Up
##   Down    8  5
##   Up     35 56
mean(lda.pred$class==Direction.910)
## [1] 0.6153846
qda.fits<-qda(Direction~Lag2+Lag5, data=Weekly, subset=train)
qda.pred<-predict(qda.fits, Weekly.910)$class
table(qda.pred, Direction.910)
##         Direction.910
## qda.pred Down Up
##     Down    3 11
##     Up     40 50
mean(qda.pred==Direction.910)
## [1] 0.5096154
knn.pred<-knn(train.X, test.X, train.Direction, k=3)
table(knn.pred, Direction.910)
##         Direction.910
## knn.pred Down Up
##     Down   16 19
##     Up     27 42
mean(knn.pred == Direction.910)
## [1] 0.5576923
nb.fits<-naiveBayes(Direction~Lag1+Lag2, data=Weekly, subset=train)
nb.pred<-predict(nb.fits, Weekly.910)
table(nb.pred, Direction.910)
##        Direction.910
## nb.pred Down Up
##    Down    3  8
##    Up     40 53
mean(nb.pred == Direction.910)
## [1] 0.5384615
detach(Weekly)

Despite trying many different transformations using multiple predictors, nothing was able to surpass the original logistic regression and LDA that used just Lag2.

Problem 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.

attach(Auto)

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

mpg01<-rep(0, length(mpg))
mpg01[mpg > median(mpg)]<-1
Auto01<-data.frame(Auto, mpg01)
rm(mpg01)

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

pairs(Auto01[,1:10])

Displacement, horsepower, and weight appear to correlate with mpg01.

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

detach(Auto)
attach(Auto01)
train<-(year%%2==0)
train.X<-Auto01[train,]
test.X<-Auto01[-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?

lda.fits<-lda(mpg01~displacement+horsepower+weight, data=train.X)
lda.pred<-predict(lda.fits, test.X)
table(lda.pred$class, test.X$mpg01)
##    
##       0   1
##   0 160  11
##   1  35 185
mean(lda.pred$class != test.X$mpg01)
## [1] 0.1176471

The LDA has a test error rate of 11.76%.

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

qda.fits<-qda(mpg01~displacement+horsepower+weight, data=train.X)
qda.pred<-predict(qda.fits, test.X)
table(qda.pred$class, test.X$mpg01)
##    
##       0   1
##   0 170  17
##   1  25 179
mean(qda.pred$class != test.X$mpg01)
## [1] 0.1074169

The QDA has a test error rate of 10.74%.

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

glm.fits<-glm(mpg01~displacement+horsepower+weight, data=train.X, family=binomial)
glm.probs<-predict(glm.fits, test.X, type="response")
glm.pred<-rep(0, length(glm.probs))
glm.pred[glm.probs > 0.5] = 1
table(glm.pred, test.X$mpg01)
##         
## glm.pred   0   1
##        0 172  16
##        1  23 180
mean(glm.pred != test.X$mpg01)
## [1] 0.09974425

The logistic regression has a test error rate of 9.97%.

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

nb.fits<-naiveBayes(mpg01~displacement+horsepower+weight, data=train.X)
nb.pred<-predict(nb.fits, test.X)
table(nb.pred, test.X$mpg01)
##        
## nb.pred   0   1
##       0 169  14
##       1  26 182
mean(nb.pred != test.X$mpg01)
## [1] 0.1023018

The Naive Bayes has a test error rate of 10.23%.

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

train.K<-cbind(displacement, horsepower, weight)[train,]
test.K<-cbind(displacement, horsepower, weight)[-train,]
knn.pred<-knn(train.K,test.K,train.X$mpg01,k=1)
mean(knn.pred != test.X$mpg01)
## [1] 0.07161125
knn.pred<-knn(train.K,test.K,train.X$mpg01,k=3)
mean(knn.pred != test.X$mpg01)
## [1] 0.0971867
knn.pred<-knn(train.K,test.K,train.X$mpg01,k=10)
mean(knn.pred != test.X$mpg01)
## [1] 0.1202046
detach(Auto01)

k=1 appears to be the best value of K on this data set, with a 7.16% test error rate.

Problem 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.
Hint: You will have to create the response variable yourself, using the variables that are contained in the Boston data set.

attach(Boston)
crim01<-rep(0, length(crim))
crim01[crim > median(crim)]<-1
Boston01<-data.frame(Boston, crim01)
rm(crim01)
detach(Boston)
attach(Boston01)

train<-1:(dim(Boston01)[1]/2)
test<-(dim(Boston01)[1]/2 + 1):dim(Boston01)[1]
train.Boston = Boston01[train,]
test.Boston = Boston01[test,]
test.crim = crim01[test]

glm.fits<-glm(crim01~indus+nox+age+dis+rad+tax, data=train.Boston, family=binomial)
glm.probs = predict(glm.fits, test.Boston, type = "response")
glm.pred = rep(0, length(glm.probs))
glm.pred[glm.probs > 0.5] = 1
table(glm.pred, test.crim)
##         test.crim
## glm.pred   0   1
##        0  75   8
##        1  15 155
mean(glm.pred != test.crim)
## [1] 0.09090909
lda.fits<-lda(crim01~indus+nox+age+dis+rad+tax, data=train.Boston)
lda.pred<-predict(lda.fits, test.Boston)
table(lda.pred$class, test.Boston$crim01)
##    
##       0   1
##   0  81  18
##   1   9 145
mean(lda.pred$class != test.Boston$crim01)
## [1] 0.1067194
nb.fits<-naiveBayes(crim01~indus+nox+age+dis+rad+tax, data=train.Boston)
nb.pred<-predict(nb.fits, test.Boston)
table(nb.pred, test.Boston$crim01)
##        
## nb.pred   0   1
##       0  77  13
##       1  13 150
mean(nb.pred != test.Boston$crim01)
## [1] 0.1027668
set.seed(1)
train.K<-cbind(indus, nox, age, dis, rad, tax)[train,]
test.K<-cbind(indus, nox, age, dis, rad, tax)[-train,]
knn.pred<-knn(train.K,test.K,train.Boston$crim01,k=1)
table(knn.pred, test.Boston$crim01)
##         
## knn.pred   0   1
##        0  82 151
##        1   8  12
mean(knn.pred != test.Boston$crim01)
## [1] 0.6284585
knn.pred<-knn(train.K,test.K,train.Boston$crim01,k=5)
table(knn.pred, test.Boston$crim01)
##         
## knn.pred   0   1
##        0  80  22
##        1  10 141
mean(knn.pred != test.Boston$crim01)
## [1] 0.1264822
knn.pred<-knn(train.K,test.K,train.Boston$crim01,k=10)
table(knn.pred, test.Boston$crim01)
##         
## knn.pred   0   1
##        0  83  23
##        1   7 140
mean(knn.pred != test.Boston$crim01)
## [1] 0.1185771
knn.pred<-knn(train.K,test.K,train.Boston$crim01,k=15)
table(knn.pred, test.Boston$crim01)
##         
## knn.pred   0   1
##        0  83  23
##        1   7 140
mean(knn.pred != test.Boston$crim01)
## [1] 0.1185771
knn.pred<-knn(train.K,test.K,train.Boston$crim01,k=20)
table(knn.pred, test.Boston$crim01)
##         
## knn.pred   0   1
##        0  83  23
##        1   7 140
mean(knn.pred != test.Boston$crim01)
## [1] 0.1185771

The generalized logistic model is the best performing of the models in this scenario, with a 9.09% test error rate. Other models tested were mostly just over 10%, though the k=1 KNN model had a massive 62.85% error rate. The indus, nox, age, dis, rad, and tax variables were all predictors of whether crime rates were above or below the median.