Chapter 4 Homework

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("e1071")
library("MASS")
library("class")
library("ISLR2")

data(Auto)
data(Boston)

(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
pairs(Weekly)

From the ‘Weekly’ data set, Year and Volume appear to have a correlation.

This is also shown in the the scatterplots formed from the pairs function.

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

summary(glm.fit)
## 
## 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

Yes, the Lag 2 predictor appears to be statistically significant based on it having a low p-value.

(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.fit, type='response')

glm.pred=rep("Down",1089)
glm.pred[glm.probs>0.5]="Up"

table(glm.pred,Weekly$Direction)
##         
## glm.pred Down  Up
##     Down   54  48
##     Up    430 557
mean(glm.pred==Weekly$Direction)
## [1] 0.5610652

The overall fraction of correct predictions is 56%. There were 430 times where the prediction that the market would be “up”, but it was actually “down”. There were also 48 instances where the market was predicted to be “down”, but it was actually “up”.

(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<=2008)

#dim(train) Dimension of train

Weekly.above2008=Weekly[!train,] # Create an object that contains all values from 
#the data set that are above 2008

#dim(Weekly) # Dimension of data set
#dim(Weekly.above2008) # Dimensions of aggregated data set

Direction.above2008=Weekly$Direction[!train] # Create an object that contains all 
#the Direction values from the data set that are less then 2008

glm.fits=glm(Direction~Lag2,data = Weekly, subset=train, family = binomial)
# Add subset to eliminate the values greater then 2008

glm.probs2 = predict(glm.fits, Weekly.above2008, type ='response')
#Added subset to testing data to get prediction for values greater then 2008 

glm.pred2=rep('Down',104)
glm.pred2[glm.probs2>0.5]="Up"

table(glm.pred2,Direction.above2008) # Confusion matrix
##          Direction.above2008
## glm.pred2 Down Up
##      Down    9  5
##      Up     34 56
mean(glm.pred2==Direction.above2008) #Correct Classification Rate
## [1] 0.625
#mean(glm.pred2!=Direction.above2008) Error Rate

(e) Repeat (d) using LDA.

lda.fit=lda(Direction~Lag2,data = Weekly, subset=train)

lda.pred=predict(lda.fit,Weekly.above2008)
# names(lda.pred) Prints names for LDA

# Class Get the LDA statements
# Posterior will be matrix (Probability)
# X contains the linear discriminate

lda.class=lda.pred$class
table(lda.class, Direction.above2008)
##          Direction.above2008
## lda.class Down Up
##      Down    9  5
##      Up     34 56
mean(lda.class==Direction.above2008)
## [1] 0.625
lda.class=lda.pred$class 

(f) Repeat (d) using QDA.

qda.fit=qda(Direction~Lag2,data = Weekly, subset=train)
#qda.fit

qda.class=predict(qda.fit,Weekly.above2008)$class

table(qda.class, Direction.above2008)
##          Direction.above2008
## qda.class Down Up
##      Down    0  0
##      Up     43 61
mean(qda.class==Direction.above2008)
## [1] 0.5865385

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

train.x = Weekly[train,"Lag2",drop=FALSE]
#dim(test.x) Checks dimensions of train.x
test.x = Weekly[!train,"Lag2",drop=FALSE]
#dim(test.x) Checks dimensions of test.x
train.Direction=Weekly$Direction[train]

#length(train.Direction) Checks length of train direction

set.seed(1)

knn.pred=knn(train.x,test.x,train.Direction,k=1)

table(knn.pred, Direction.above2008)
##         Direction.above2008
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred==Direction.above2008)
## [1] 0.5

(h) Repeat (d) using naive Bayes.

nb.fit = naiveBayes(Direction ~ Lag2, data = Weekly, subset = train)
nb.fit
## 
## 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
nb.pred=predict(nb.fit,Weekly.above2008)

table(nb.pred, Direction.above2008)
##        Direction.above2008
## nb.pred Down Up
##    Down    0  0
##    Up     43 61
mean(nb.pred==Direction.above2008)
## [1] 0.5865385

(i) Which of these methods appears to provide the best results on this data? Both the Logistic Regression model and the LDA model provide the same percentage of correct preditions of 62.5%.

(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.x = Weekly[train,c("Lag1","Lag2","Lag3","Lag4","Lag5","Volume")]
#dim(test.x) Checks dimensions of train.x
test.x = Weekly[!train, c("Lag1","Lag2","Lag3","Lag4","Lag5","Volume")]
#dim(test.x) Checks dimensions of test.x
train.Direction=Weekly$Direction[train]

#length(train.Direction) Checks length of train direction

set.seed(1)

#for(k in 1:20){
  #knn.pred = knn(train.x, test.x, train.Direction, k=k)
  #print(c(K=k, Accuracy=mean(knn.pred==Direction.above2008)))
#}
knn.pred=knn(train.x,test.x,train.Direction,k=11)

table(knn.pred, Direction.above2008)
##         Direction.above2008
## knn.pred Down Up
##     Down   21 19
##     Up     22 42
mean(knn.pred==Direction.above2008)
## [1] 0.6057692

The results for making modifications to the KNN model using all predictors did have a significant impact because using K=11 increased the amount of correct predictions to 60%.

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.

(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 = na.omit(Auto) #Loaded in Auto data

mpg01 = ifelse(Auto$mpg > median(Auto$mpg), 1, 0) 
#Created new variable that classifies the median
#values

ModifiedAuto = data.frame(mpg01, Auto)
#Created a new data frame with both variables

(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(ModifiedAuto[, c("mpg01", "cylinders", "displacement",
               "horsepower", "weight", "acceleration",
               "year", "origin")])

cor(ModifiedAuto[, c("mpg01", "cylinders", "displacement",
             "horsepower", "weight", "acceleration",
             "year", "origin")])
##                   mpg01  cylinders displacement horsepower     weight
## mpg01         1.0000000 -0.7591939   -0.7534766 -0.6670526 -0.7577566
## cylinders    -0.7591939  1.0000000    0.9508233  0.8429834  0.8975273
## displacement -0.7534766  0.9508233    1.0000000  0.8972570  0.9329944
## horsepower   -0.6670526  0.8429834    0.8972570  1.0000000  0.8645377
## weight       -0.7577566  0.8975273    0.9329944  0.8645377  1.0000000
## acceleration  0.3468215 -0.5046834   -0.5438005 -0.6891955 -0.4168392
## year          0.4299042 -0.3456474   -0.3698552 -0.4163615 -0.3091199
## origin        0.5136984 -0.5689316   -0.6145351 -0.4551715 -0.5850054
##              acceleration       year     origin
## mpg01           0.3468215  0.4299042  0.5136984
## cylinders      -0.5046834 -0.3456474 -0.5689316
## displacement   -0.5438005 -0.3698552 -0.6145351
## horsepower     -0.6891955 -0.4163615 -0.4551715
## weight         -0.4168392 -0.3091199 -0.5850054
## acceleration    1.0000000  0.2903161  0.2127458
## year            0.2903161  1.0000000  0.1815277
## origin          0.2127458  0.1815277  1.0000000

Using the calculated coefficients, the predictors that appear to be useful in predicting mpg01 are ‘Displacement’, ‘Weight’, and ‘cylinders’.

They all appear to have a correlation to the ‘mpg01’ with values over 0.75.

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

set.seed(100)

train_Auto<- sample(1:nrow(ModifiedAuto),
                      size = 0.8 * nrow(ModifiedAuto))

train_data14 <- ModifiedAuto[train_Auto, ]
test_data14  <- ModifiedAuto[-train_Auto, ]

(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.fit14=lda(mpg01~displacement+weight+cylinders,data = train_data14)

lda.pred14=predict(lda.fit14,test_data14)

lda.class14=lda.pred14$class

table(Predicted = lda.class14, 
      Actual = test_data14$mpg01)
##          Actual
## Predicted  0  1
##         0 44  3
##         1  2 30
mean(lda.class14!=test_data14$mpg01)
## [1] 0.06329114

The LDA test error is 6.3%.

(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.fit14=qda(mpg01~displacement+weight+cylinders,data = train_data14)

qda.pred14=predict(qda.fit14,test_data14)

qda.class14=qda.pred14$class

table(Predicted = qda.class14, 
      Actual = test_data14$mpg01)
##          Actual
## Predicted  0  1
##         0 44  3
##         1  2 30
mean(qda.class14!=test_data14$mpg01)
## [1] 0.06329114

The QDA test error is 6.3%.

(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.fits14=glm(mpg01~displacement+weight+cylinders,data = train_data14, 
               family = binomial)

glm.probs14 = predict(glm.fits14, test_data14, type ='response')

glm.pred14 <- ifelse(glm.probs14 > 0.5, 1, 0)

table(Predicted = glm.pred14,
      Actual = test_data14$mpg01)
##          Actual
## Predicted  0  1
##         0 44  3
##         1  2 30
mean(glm.pred14!=test_data14$mpg01)
## [1] 0.06329114

The Logistic Regression test error is 6.3%.

(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.fit14 = naiveBayes(mpg01~displacement+weight+cylinders,data = train_data14)

nb.pred14=predict(nb.fit14,test_data14)

table(nb.pred14, test_data14$mpg01)
##          
## nb.pred14  0  1
##         0 44  3
##         1  2 30
mean(nb.pred14!=test_data14$mpg01)
## [1] 0.06329114

The naive Bayes test error is 6.3%.

(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.x14 = train_data14[, c("displacement", "weight", "cylinders")]
test.x14 = test_data14[, c("displacement", "weight", "cylinders")]

train14 = train_data14$mpg01
test14 = test_data14$mpg01

set.seed(1)

#for(k in 1:20){
#knn.pred14 = knn(train.x14,
                    #test.x14,
                    #train14,
                    #k = k)
  
  #print(c(K = k,
          #Accuracy = mean(knn.pred14 == test14)))
#}

# Example final model
knn.pred14A = knn(train.x14,
                  test.x14,
                  train14,
                  k = 3)

knn.pred14B = knn(train.x14,
                  test.x14,
                  train14,
                  k = 4)

knn.pred14C = knn(train.x14,
                  test.x14,
                  train14,
                  k = 7)

knn.pred14D = knn(train.x14,
                  test.x14,
                  train14,
                  k = 11)

table(Predicted = knn.pred14A,
      Actual = test14)
##          Actual
## Predicted  0  1
##         0 44  1
##         1  2 32
# Test error
mean(knn.pred14A != test14)
## [1] 0.03797468
mean(knn.pred14B != test14)
## [1] 0.07594937
mean(knn.pred14C != test14)
## [1] 0.08860759
mean(knn.pred14D != test14)
## [1] 0.08860759

The best KNN with K as 3 yielded a test error of 3.8%.

KNN with K as 4 yielded a test error of 7.6%. KNN with K as 7 yielded a test error of 8.9%. KNN with K as 11 yielded a test error of 8.9%.

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.

Boston = na.omit(Boston) #Loaded in Boston data

crimAboveMed = ifelse(Boston$crim > median(Boston$crim), 1, 0) 
#Created new variable that classifies the median
#values

ModifiedBoston = data.frame(crimAboveMed, Boston)

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

set.seed(100)

train_Boston16<- sample(1:nrow(ModifiedBoston),
                      size = 0.8 * nrow(ModifiedBoston))

train_data16 <- ModifiedBoston[train_Boston16, ]
test_data16  <- ModifiedBoston[-train_Boston16, ]

I chose to split my data for Boston into 2 for training (80%) and test (20%).

I also chose to use lower status of population, age of units, and the weighted mean of distances to five Boston employment centers as my 3 predictors to determine if the crime per capita rate is above the median value.

glm.fits16=glm(crimAboveMed~age+dis+lstat,data = train_data16, 
               family = binomial)

glm.probs16 = predict(glm.fits16, test_data16, type ='response')

glm.pred16 <- ifelse(glm.probs16 > 0.5, 1, 0)

table(Predicted = glm.pred16,
      Actual = test_data16$crimAboveMed)
##          Actual
## Predicted  0  1
##         0 42 10
##         1  8 42
mean(glm.pred16==test_data16$crimAboveMed)
## [1] 0.8235294
mean(glm.pred16!=test_data16$crimAboveMed)
## [1] 0.1764706

The test error rate log regression is 17.6%

lda.fit16=lda(crimAboveMed~age+dis+lstat,data = train_data16)

lda.pred16=predict(lda.fit16,test_data16)

lda.class16=lda.pred16$class

table(Predicted = lda.class16, 
      Actual = test_data16$crimAboveMed)
##          Actual
## Predicted  0  1
##         0 39  6
##         1 11 46
mean(lda.class16==test_data16$crimAboveMed)
## [1] 0.8333333
mean(lda.class16!=test_data16$crimAboveMed)
## [1] 0.1666667

The test error rate for LDA is 16.7%

nb.fit16 = naiveBayes(crimAboveMed~age+dis+lstat,data = train_data16)

nb.pred16=predict(nb.fit16,test_data16)

table(nb.pred16, test_data16$crimAboveMed)
##          
## nb.pred16  0  1
##         0 41  5
##         1  9 47
mean(nb.pred16==test_data16$crimAboveMed)
## [1] 0.8627451
mean(nb.pred16!=test_data16$crimAboveMed)
## [1] 0.1372549

The test error rate for naive Bayes is 13.7%

train.x16 = train_data16[, c("age", "dis", "lstat")]
test.x16 = test_data16[, c("age", "dis", "lstat")]

train16 = train_data16$crimAboveMed
test16 = test_data16$crimAboveMed

set.seed(1)

#for(k in 1:20){
#knn.pred16 = knn(train.x16,
                    #test.x16,
                    #train16,
                    #k = k)
  
  #print(c(K = k,
          #Accuracy = mean(knn.pred16 == test16)))
#}

# Example final model
knn.pred16A = knn(train.x16,
                  test.x16,
                  train16,
                  k = 4)

knn.pred16B = knn(train.x16,
                  test.x16,
                  train16,
                  k = 6)

knn.pred16C = knn(train.x16,
                  test.x16,
                  train16,
                  k = 13)

knn.pred16D = knn(train.x16,
                  test.x16,
                  train16,
                  k = 17)

table(Predicted = knn.pred16D,
      Actual = test16)
##          Actual
## Predicted  0  1
##         0 39  7
##         1 11 45
# Test error
mean(knn.pred16A != test16)
## [1] 0.2156863
mean(knn.pred16B != test16)
## [1] 0.2352941
mean(knn.pred16C != test16)
## [1] 0.1862745
mean(knn.pred16D != test16)
## [1] 0.1764706

The best KNN with K as 17 yielded a test error of 17.6%.

KNN with K as 13 yielded a test error of 18.6%. KNN with K as 6 yielded a test error of 23.5%. KNN with K as 4 yielded a test error of 21.5%.

Out of the 4 models fitted, the naive Bayes model fitted the best.

The logistical regression model yielded the highest amount of false positives when crime per capita was above the median value.

Both the KNN and LDA models yielded the highest amount of false negatives when crime per capita was determined to be lower then expected.