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.

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

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

Off the bat, we don’t notice any distinct patterns. However there does seem to be an exponential relationship between volume and years. We can see that as time does on, the volume only increases at an exponential rate. This can be further exemplified by taking a look at the correlation between these two variables(0.84194162).

13.(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.direct = glm(Direction ~ . - Year - Today, data = Weekly, family = "binomial")
summary(glm.direct)
## 
## Call:
## glm(formula = Direction ~ . - Year - Today, 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

Lag2 seems to be the only statistically significant predictor to the response variable Direction. Lag2 is the only predictor with a P-Value less than 0.05 (0.0296). Because of its significance, it might be advised to take a closer look at a models with just Lag2 as the predictor.

13.(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.direct.probs = predict(glm.direct, type = "response")
glm.direct.pred = rep("Down", 1089)
glm.direct.pred[glm.direct.probs > 0.5] = "Up"
table(glm.direct.pred, Weekly$Direction)
##                
## glm.direct.pred Down  Up
##            Down   54  48
##            Up    430 557

From the confusion matrix we can see that the model correctly predicted the direction for 611 weeks (54 + 557) out of the 1089, giving us an accuracy of 0.561065. Lets take a closer look at the confusion matrix:

- True Positive: 557/605 = 0.92

- False Positive: 430/484 = 0.89

While our true positive value (i.e. recall) is fairly high, the number of false positives is also high. This may not be a good model depending on how much loss could occur when incorrectly predicting a down week.

13.(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)
glm.fit = glm(Direction ~ Lag2, data = Weekly, subset = train, family = "binomial")
summary(glm.fit)
## 
## Call:
## glm(formula = Direction ~ Lag2, family = "binomial", data = Weekly, 
##     subset = train)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.20326    0.06428   3.162  0.00157 **
## Lag2         0.05810    0.02870   2.024  0.04298 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1354.7  on 984  degrees of freedom
## Residual deviance: 1350.5  on 983  degrees of freedom
## AIC: 1354.5
## 
## Number of Fisher Scoring iterations: 4
glm.probs = predict(glm.fit, Weekly[!train, ], type = "response")
glm.pred = rep("Down", dim(Weekly[!train, ])[1])
glm.pred[glm.probs > 0.5] = "Up"
table(glm.pred, Weekly[!train, ]$Direction)
##         
## glm.pred Down Up
##     Down    9  5
##     Up     34 56

- Accuracy: 65/104 = 0.625

- True Positive: 56/61 = 0.91

- False Positive: 34/43 = 0.79

13.(e) Repeat (d) using LDA.

lda.fit = lda(Direction ~ Lag2, data = Weekly, subset = train)
lda.fit
## 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(lda.fit, 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

- Accuracy: 65/104 = 0.625

- True Positive: 56/61 = 0.91

- False Positive: 34/43 = 0.79

13.(f) Repeat (d) using QDA.

qda.fit = qda(Direction ~ Lag2, data = Weekly, subset = train)
qda.fit
## 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(qda.fit, 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
  • Accuracy: 65/104 = 0.625
  • True Positive: 61/61 = 1
  • False Positive: 43/43 = 1

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

train.X = data.frame(Weekly[train, ]$Lag2)
test.X = data.frame(Weekly[!train, ]$Lag2)
train.Direction = Weekly[train, ]$Direction
set.seed(1)
knn.pred = knn(train.X, test.X, train.Direction, 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

- True Positive: 31/61 = 0.508

- False Positive: 22/43 = 0.512

13.(h) Repeat (d) using naive Bayes.

train.X <- data.frame(Weekly[train, ]$Lag2)
test.X <- data.frame(Weekly[!train, ]$Lag2)
train.Direction <- Weekly[train, ]$Direction
naive_model <- naiveBayes(train.X, train.Direction)
naive_pred <- predict(naive_model, test.X)
## Warning in predict.naiveBayes(naive_model, test.X): Type mismatch between
## training and new data for variable 'Weekly.train....Lag2'. Did you use factors
## with numeric labels for training, and numeric values for new data?
table(naive_pred, Weekly[!train, ]$Direction)
##           
## naive_pred Down Up
##       Down    0  0
##       Up     43 61
accuracy <- mean(naive_pred == Weekly[!train, ]$Direction)
  • Accuracy: 65/104 = 0.625
  • True Positive: 61/61 = 1
  • False Positive: 43/43 = 1

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

It seems as if Logistic regression and LDA are the best models to use on this data. Both these models performed equally well when trained and tested on the data

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

weighted.lag.avg = 0.4*Weekly$Lag1 + 0.35*Weekly$Lag2 + 0.15*Weekly$Lag3 + 0.05*Weekly$Lag4 + 0.05*Weekly$Lag5
Weekly = data.frame(Weekly, weighted.lag.avg)
head(Weekly)
##   Year   Lag1   Lag2   Lag3   Lag4   Lag5    Volume  Today Direction
## 1 1990  0.816  1.572 -3.936 -0.229 -3.484 0.1549760 -0.270      Down
## 2 1990 -0.270  0.816  1.572 -3.936 -0.229 0.1485740 -2.576      Down
## 3 1990 -2.576 -0.270  0.816  1.572 -3.936 0.1598375  3.514        Up
## 4 1990  3.514 -2.576 -0.270  0.816  1.572 0.1616300  0.712        Up
## 5 1990  0.712  3.514 -2.576 -0.270  0.816 0.1537280  1.178        Up
## 6 1990  1.178  0.712  3.514 -2.576 -0.270 0.1544440 -1.372      Down
##   weighted.lag.avg
## 1          0.10055
## 2          0.20515
## 3         -1.12070
## 4          0.58290
## 5          1.15560
## 6          1.10520
cor(Weekly$Today, Weekly$weighted.lag.avg)
## [1] -0.03724141
glm.fit = glm(Direction ~ weighted.lag.avg, data = Weekly, subset = train, family = "binomial")
summary(glm.fit)
## 
## Call:
## glm(formula = Direction ~ weighted.lag.avg, family = "binomial", 
##     data = Weekly, subset = train)
## 
## Coefficients:
##                  Estimate Std. Error z value Pr(>|z|)    
## (Intercept)       0.21349    0.06446   3.312 0.000926 ***
## weighted.lag.avg -0.02816    0.05347  -0.527 0.598508    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1354.7  on 984  degrees of freedom
## Residual deviance: 1354.4  on 983  degrees of freedom
## AIC: 1358.4
## 
## Number of Fisher Scoring iterations: 3
glm.probs = predict(glm.fit, Weekly[!train, ], type = "response")
glm.pred = rep("Down", dim(Weekly[!train, ])[1])
glm.pred[glm.probs > 0.5] = "Up"
table(glm.pred, Weekly[!train, ]$Direction)
##         
## glm.pred Down Up
##       Up   43 61
mean(glm.pred == Weekly[!train, ]$Direction)
## [1] 0.5865385
lda.fit = lda(Direction ~ weighted.lag.avg, data = Weekly, subset = train)
lda.pred = predict(lda.fit, Weekly[!train, ])
table(lda.pred$class, Weekly[!train, ]$Direction)
##       
##        Down Up
##   Down    0  0
##   Up     43 61
mean(lda.pred$class == Weekly[!train, ]$Direction)
## [1] 0.5865385
qda.fit = qda(Direction ~ weighted.lag.avg, data = Weekly, subset = train)
qda.pred = predict(qda.fit, 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
train.X = data.frame(Weekly[train, "weighted.lag.avg"])
test.X = data.frame(Weekly[!train, "weighted.lag.avg"])
train.Direction = Weekly[train, "Direction"]
set.seed(1)
knn.pred = knn(train.X, test.X, train.Direction, k = 1)
table(knn.pred, Weekly[!train, ]$Direction)
##         
## knn.pred Down Up
##     Down   14 28
##     Up     29 33
mean(knn.pred == Weekly[!train, ]$Direction)
## [1] 0.4519231

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.

14.(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)
# Creating factors of the origin variable
Auto$origin[Auto$origin == 1] = "American"
Auto$origin[Auto$origin == 2] = "European"
Auto$origin[Auto$origin == 3] = "Japanese"
Auto$origin = as.factor(Auto$origin)

# Creating binary variable
mpg01 = rep(0, dim(Auto)[1])
# If mpg is greater than median value, update value to 1
mpg01[Auto$mpg > median(Auto$mpg)] = 1
# Create new data frame with binary variable
Auto = data.frame(Auto, mpg01)
head(Auto)
##   mpg cylinders displacement horsepower weight acceleration year   origin
## 1  18         8          307        130   3504         12.0   70 American
## 2  15         8          350        165   3693         11.5   70 American
## 3  18         8          318        150   3436         11.0   70 American
## 4  16         8          304        150   3433         12.0   70 American
## 5  17         8          302        140   3449         10.5   70 American
## 6  15         8          429        198   4341         10.0   70 American
##                        name mpg01
## 1 chevrolet chevelle malibu     0
## 2         buick skylark 320     0
## 3        plymouth satellite     0
## 4             amc rebel sst     0
## 5               ford torino     0
## 6          ford galaxie 500     0

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

par(mfrow = c(2, 3))
plot(factor(Auto$mpg01), Auto$cylinders, ylab = "cylinders")
plot(factor(Auto$mpg01), Auto$displacement, ylab = "displacement")
plot(factor(Auto$mpg01), Auto$horsepower, ylab = "horsepower")
plot(factor(Auto$mpg01), Auto$weight, ylab = "weight")
plot(factor(Auto$mpg01), Auto$acceleration, ylab = "acceleration")
plot(factor(Auto$mpg01), Auto$year, ylab = "year")

pairs(Auto)

Based on the box plots and scatter plots, horsepower, weight, displacement, and origin might be the best predictors to include in the model. All of these predictors appear to have clear clustering when compared against the response variable, mpg01.

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

set.seed(47)
train = sample(dim(Auto)[1], size = 0.70*dim(Auto)[1])

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

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

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

# Train logistic regression model
log.model <- glm(mpg01 ~ cylinders + displacement + horsepower + weight + year, subset = train, data = Auto, family = binomial)

summary(log.model)
## 
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower + 
##     weight + year, family = binomial, data = Auto, subset = train)
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  -13.864345   5.791219  -2.394   0.0167 *  
## cylinders     -0.203355   0.473310  -0.430   0.6675    
## displacement   0.002807   0.011737   0.239   0.8110    
## horsepower    -0.038139   0.019361  -1.970   0.0489 *  
## weight        -0.004603   0.001171  -3.932 8.41e-05 ***
## year           0.408016   0.091124   4.478 7.55e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 378.38  on 273  degrees of freedom
## Residual deviance: 106.36  on 268  degrees of freedom
## AIC: 118.36
## 
## Number of Fisher Scoring iterations: 8

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

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

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.