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

According to the plots above, where the columns and rows represent all 9 variables and the correlation between each variable, we can see that there are noticeable pattern between Volumn 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?
w1 = glm(Direction ~ Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data=Weekly,family=binomial)
summary(w1)
## 
## 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

According to the results above, Lag2 has p = 0.0296 < 0.05, indicating a significant relationship between Lag2 and Direction.

(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.
prod1 = predict.glm(w1, type = "response")
pred1 = ifelse(prod1 >= 0.5, "Up", "Down")
caret::confusionMatrix(as.factor(pred1), as.factor(Weekly$Direction), positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down  Up
##       Down   54  48
##       Up    430 557
##                                          
##                Accuracy : 0.5611         
##                  95% CI : (0.531, 0.5908)
##     No Information Rate : 0.5556         
##     P-Value [Acc > NIR] : 0.369          
##                                          
##                   Kappa : 0.035          
##                                          
##  Mcnemar's Test P-Value : <2e-16         
##                                          
##             Sensitivity : 0.9207         
##             Specificity : 0.1116         
##          Pos Pred Value : 0.5643         
##          Neg Pred Value : 0.5294         
##              Prevalence : 0.5556         
##          Detection Rate : 0.5115         
##    Detection Prevalence : 0.9063         
##       Balanced Accuracy : 0.5161         
##                                          
##        'Positive' Class : Up             
## 

Looking at the result above, I can see that the data set is highly unbalanced which led to a high Sensitivity score (true positive) and low Specificity score (true negative). The current model has the accuracy of 56.11%, with 92% of accurately predicting true positive and 11% of accurately predicting true negative.

(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).
wtrain = Weekly[Weekly$Year<2009,]
wtest = Weekly[Weekly$Year>2008,]
w2 = glm(Direction ~ Lag2, data=wtrain,family=binomial)
summary(w2)
## 
## Call:
## glm(formula = Direction ~ Lag2, family = binomial, data = wtrain)
## 
## 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
prod2 = predict.glm(w2, wtest, type = "response")
pred2 = ifelse(prod2 >= 0.5, "Up", "Down")
caret::confusionMatrix(as.factor(pred2), as.factor(wtest$Direction), positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    9  5
##       Up     34 56
##                                          
##                Accuracy : 0.625          
##                  95% CI : (0.5247, 0.718)
##     No Information Rate : 0.5865         
##     P-Value [Acc > NIR] : 0.2439         
##                                          
##                   Kappa : 0.1414         
##                                          
##  Mcnemar's Test P-Value : 7.34e-06       
##                                          
##             Sensitivity : 0.9180         
##             Specificity : 0.2093         
##          Pos Pred Value : 0.6222         
##          Neg Pred Value : 0.6429         
##              Prevalence : 0.5865         
##          Detection Rate : 0.5385         
##    Detection Prevalence : 0.8654         
##       Balanced Accuracy : 0.5637         
##                                          
##        'Positive' Class : Up             
## 

With only Lag2 as a predictor, we can see that the overall accuracy and Specificity accuracy improve slightly.

(e) Repeat (d) using LDA.
w3 = lda(Direction ~ Lag2, data=wtrain,family=binomial)
pred3 = predict(w3, wtest)
caret::confusionMatrix(as.factor(pred3$class), as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    9  5
##       Up     34 56
##                                          
##                Accuracy : 0.625          
##                  95% CI : (0.5247, 0.718)
##     No Information Rate : 0.5865         
##     P-Value [Acc > NIR] : 0.2439         
##                                          
##                   Kappa : 0.1414         
##                                          
##  Mcnemar's Test P-Value : 7.34e-06       
##                                          
##             Sensitivity : 0.20930        
##             Specificity : 0.91803        
##          Pos Pred Value : 0.64286        
##          Neg Pred Value : 0.62222        
##              Prevalence : 0.41346        
##          Detection Rate : 0.08654        
##    Detection Prevalence : 0.13462        
##       Balanced Accuracy : 0.56367        
##                                          
##        'Positive' Class : Down           
## 

The LDA model has an accuracy of 62.5%, with 20.9% sensitivity and 91.8% specificity. Showing decrease in predicting true positive compare to the previous two models.

(f) Repeat (d) using QDA.
w4 = qda(Direction ~ Lag2, data=wtrain,family=binomial)
pred4 = predict(w4, wtest)
caret::confusionMatrix(as.factor(pred4$class), as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    0  0
##       Up     43 61
##                                           
##                Accuracy : 0.5865          
##                  95% CI : (0.4858, 0.6823)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.5419          
##                                           
##                   Kappa : 0               
##                                           
##  Mcnemar's Test P-Value : 1.504e-10       
##                                           
##             Sensitivity : 0.0000          
##             Specificity : 1.0000          
##          Pos Pred Value :    NaN          
##          Neg Pred Value : 0.5865          
##              Prevalence : 0.4135          
##          Detection Rate : 0.0000          
##    Detection Prevalence : 0.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : Down            
## 

The QDA model gave us 58.6% overall accuracy but failed to predict any true positive and able to predict 100% of all true negative data.

(g) Repeat (d) using KNN with K = 1.
train1 = wtrain$Lag2[1:length(wtest$Lag2)]
test1=cbind(wtest$Lag2)
Dtrain = as.factor(wtrain$Direction[1:length(wtest$Lag2)])

w5 =knn(train1, test1, Dtrain, k=1)
caret::confusionMatrix(w5, as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   19 31
##       Up     24 30
##                                           
##                Accuracy : 0.4712          
##                  95% CI : (0.3725, 0.5715)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.9932          
##                                           
##                   Kappa : -0.0648         
##                                           
##  Mcnemar's Test P-Value : 0.4185          
##                                           
##             Sensitivity : 0.4419          
##             Specificity : 0.4918          
##          Pos Pred Value : 0.3800          
##          Neg Pred Value : 0.5556          
##              Prevalence : 0.4135          
##          Detection Rate : 0.1827          
##    Detection Prevalence : 0.4808          
##       Balanced Accuracy : 0.4668          
##                                           
##        'Positive' Class : Down            
## 

With this method, the accuracy is the lowest compared to the others with 47% but has a more balanced sensitivity and specificity scores.

(h) Repeat (d) using naive Bayes.
w6 = naiveBayes(Direction~Lag2,data=wtrain, family=binomial)
pred6 = predict(w6, wtest)
confusionMatrix(pred6, as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    0  0
##       Up     43 61
##                                           
##                Accuracy : 0.5865          
##                  95% CI : (0.4858, 0.6823)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.5419          
##                                           
##                   Kappa : 0               
##                                           
##  Mcnemar's Test P-Value : 1.504e-10       
##                                           
##             Sensitivity : 0.0000          
##             Specificity : 1.0000          
##          Pos Pred Value :    NaN          
##          Neg Pred Value : 0.5865          
##              Prevalence : 0.4135          
##          Detection Rate : 0.0000          
##    Detection Prevalence : 0.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : Down            
## 

Similiar to the QDA model, this model has 58.6% overall accuracy but failed to predict any true positive and able to predict 100% of all true negative data.

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

I believe the KNN method gave the best result, even though it has low accuracy but it has the most balanced accuracy score for predicting both true positive and true negative.

(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.
w7 =knn(train1, test1, Dtrain, k=50)
caret::confusionMatrix(w7, as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   10 13
##       Up     33 48
##                                         
##                Accuracy : 0.5577        
##                  95% CI : (0.457, 0.655)
##     No Information Rate : 0.5865        
##     P-Value [Acc > NIR] : 0.757916      
##                                         
##                   Kappa : 0.0209        
##                                         
##  Mcnemar's Test P-Value : 0.005088      
##                                         
##             Sensitivity : 0.23256       
##             Specificity : 0.78689       
##          Pos Pred Value : 0.43478       
##          Neg Pred Value : 0.59259       
##              Prevalence : 0.41346       
##          Detection Rate : 0.09615       
##    Detection Prevalence : 0.22115       
##       Balanced Accuracy : 0.50972       
##                                         
##        'Positive' Class : Down          
## 

I want to experiment the KNN method with increasing k to 50, and the result showed an increase of overall accuracy and specificity score with a decrease in sensitivity score.

## glm
w_GLM = glm(Direction ~ ., data=wtrain,family=binomial, control = list(maxit = 100), penalty = "L1")
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
prod8 = predict.glm(w_GLM, wtest, type = "response")
pred8 = ifelse(prod8 >= 0.5, "Up", "Down")

## nb
w_NB = naiveBayes(Direction~.,data=wtrain, family=binomial)
pred_NB = predict(w_NB, wtest)

## knn
trainknn = cbind(wtrain$year,  wtrain$Lag1, wtrain$Lag2, wtrain$Lag3, wtrain$Lag4, wtrain$Lag5, wtrain$Volume, wtrain$Today)
testknn = cbind(wtest$year,  wtest$Lag1, wtest$Lag2, wtest$Lag3, wtest$Lag4, wtest$Lag5, wtest$Volume, wtest$Today)
w_KNN =knn(trainknn, testknn, wtrain$Direction, k=20)

## QDA
w_QDA = qda(Direction ~ ., data=wtrain,family=binomial)
pred_QDA = predict(w_QDA, wtest)

## LDA

w_LDA = lda(Direction ~ ., data=wtrain,family=binomial)
pred_LDA = predict(w_LDA, wtest)

## result
confusionMatrix(as.factor(pred8), as.factor(wtest$Direction), positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   43  0
##       Up      0 61
##                                      
##                Accuracy : 1          
##                  95% CI : (0.9652, 1)
##     No Information Rate : 0.5865     
##     P-Value [Acc > NIR] : < 2.2e-16  
##                                      
##                   Kappa : 1          
##                                      
##  Mcnemar's Test P-Value : NA         
##                                      
##             Sensitivity : 1.0000     
##             Specificity : 1.0000     
##          Pos Pred Value : 1.0000     
##          Neg Pred Value : 1.0000     
##              Prevalence : 0.5865     
##          Detection Rate : 0.5865     
##    Detection Prevalence : 0.5865     
##       Balanced Accuracy : 1.0000     
##                                      
##        'Positive' Class : Up         
## 
confusionMatrix(pred_NB, as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   43 15
##       Up      0 46
##                                          
##                Accuracy : 0.8558         
##                  95% CI : (0.7733, 0.917)
##     No Information Rate : 0.5865         
##     P-Value [Acc > NIR] : 2.616e-09      
##                                          
##                   Kappa : 0.7172         
##                                          
##  Mcnemar's Test P-Value : 0.0003006      
##                                          
##             Sensitivity : 1.0000         
##             Specificity : 0.7541         
##          Pos Pred Value : 0.7414         
##          Neg Pred Value : 1.0000         
##              Prevalence : 0.4135         
##          Detection Rate : 0.4135         
##    Detection Prevalence : 0.5577         
##       Balanced Accuracy : 0.8770         
##                                          
##        'Positive' Class : Down           
## 
confusionMatrix(w_KNN, as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   38  4
##       Up      5 57
##                                           
##                Accuracy : 0.9135          
##                  95% CI : (0.8421, 0.9597)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 1.086e-13       
##                                           
##                   Kappa : 0.821           
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.8837          
##             Specificity : 0.9344          
##          Pos Pred Value : 0.9048          
##          Neg Pred Value : 0.9194          
##              Prevalence : 0.4135          
##          Detection Rate : 0.3654          
##    Detection Prevalence : 0.4038          
##       Balanced Accuracy : 0.9091          
##                                           
##        'Positive' Class : Down            
## 
confusionMatrix(as.factor(pred_QDA$class), as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   43 12
##       Up      0 49
##                                           
##                Accuracy : 0.8846          
##                  95% CI : (0.8071, 0.9389)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 2.536e-11       
##                                           
##                   Kappa : 0.7715          
##                                           
##  Mcnemar's Test P-Value : 0.001496        
##                                           
##             Sensitivity : 1.0000          
##             Specificity : 0.8033          
##          Pos Pred Value : 0.7818          
##          Neg Pred Value : 1.0000          
##              Prevalence : 0.4135          
##          Detection Rate : 0.4135          
##    Detection Prevalence : 0.5288          
##       Balanced Accuracy : 0.9016          
##                                           
##        'Positive' Class : Down            
## 
confusionMatrix(as.factor(pred_LDA$class), as.factor(wtest$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   36  0
##       Up      7 61
##                                           
##                Accuracy : 0.9327          
##                  95% CI : (0.8662, 0.9725)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 1.632e-15       
##                                           
##                   Kappa : 0.8578          
##                                           
##  Mcnemar's Test P-Value : 0.02334         
##                                           
##             Sensitivity : 0.8372          
##             Specificity : 1.0000          
##          Pos Pred Value : 1.0000          
##          Neg Pred Value : 0.8971          
##              Prevalence : 0.4135          
##          Detection Rate : 0.3462          
##    Detection Prevalence : 0.3462          
##       Balanced Accuracy : 0.9186          
##                                           
##        'Positive' Class : Down            
## 

Next I wanted to try all models with all variables as predictors. According to the result above, the best performing model is the logistic regression model, with 100% in all overall accuracy, specificity, and sensitivity.

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.
mpg_median <- median(Auto$mpg)
Auto$mpg01 <- ifelse(Auto$mpg > mpg_median, 1, 0)
str(Auto)
## 'data.frame':    392 obs. of  10 variables:
##  $ mpg         : num  18 15 18 16 17 15 14 14 14 15 ...
##  $ cylinders   : int  8 8 8 8 8 8 8 8 8 8 ...
##  $ displacement: num  307 350 318 304 302 429 454 440 455 390 ...
##  $ horsepower  : int  130 165 150 150 140 198 220 215 225 190 ...
##  $ weight      : int  3504 3693 3436 3433 3449 4341 4354 4312 4425 3850 ...
##  $ acceleration: num  12 11.5 11 12 10.5 10 9 8.5 10 8.5 ...
##  $ year        : int  70 70 70 70 70 70 70 70 70 70 ...
##  $ origin      : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ name        : Factor w/ 304 levels "amc ambassador brougham",..: 49 36 231 14 161 141 54 223 241 2 ...
##  $ mpg01       : num  0 0 0 0 0 0 0 0 0 0 ...
##  - attr(*, "na.action")= 'omit' Named int [1:5] 33 127 331 337 355
##   ..- attr(*, "names")= chr [1:5] "33" "127" "331" "337" ...
head(Auto)
##   mpg cylinders displacement horsepower weight acceleration year origin
## 1  18         8          307        130   3504         12.0   70      1
## 2  15         8          350        165   3693         11.5   70      1
## 3  18         8          318        150   3436         11.0   70      1
## 4  16         8          304        150   3433         12.0   70      1
## 5  17         8          302        140   3449         10.5   70      1
## 6  15         8          429        198   4341         10.0   70      1
##                        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
(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.
plot(Auto)

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

According to the plots and the correlation table above, ‘cylinder’, ‘displacement’, and ‘weight’ are mosy likely to be helpful in predicting mpg01.

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

tr_ind <- sample(nrow(Auto),0.8*nrow(Auto),replace = F)
Atrain <- Auto[tr_ind, ]
Atest <- Auto[-tr_ind, ]
(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?
auto_lda <- lda(mpg01 ~ cylinders + displacement + weight, data = Atrain)
auto_pred <- predict(auto_lda, Atest)
auto_pred_class <- factor(auto_pred$class)
Atest$mpg01 <- factor(Atest$mpg01)
levels(auto_pred_class) <- levels(Atest$mpg01)
caret::confusionMatrix(auto_pred_class, Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  4
##          1  7 33
##                                           
##                Accuracy : 0.8608          
##                  95% CI : (0.7645, 0.9284)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 5.745e-10       
##                                           
##                   Kappa : 0.7217          
##                                           
##  Mcnemar's Test P-Value : 0.5465          
##                                           
##             Sensitivity : 0.8333          
##             Specificity : 0.8919          
##          Pos Pred Value : 0.8974          
##          Neg Pred Value : 0.8250          
##              Prevalence : 0.5316          
##          Detection Rate : 0.4430          
##    Detection Prevalence : 0.4937          
##       Balanced Accuracy : 0.8626          
##                                           
##        'Positive' Class : 0               
## 

This model’s accuracy is 86%, therefore the test error is 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?
auto_qda = qda(mpg01 ~ cylinders + displacement + weight, data = Atrain)
auto_pred1 = predict(auto_qda, Atest)
caret::confusionMatrix(as.factor(auto_pred1$class), Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 37  4
##          1  5 33
##                                           
##                Accuracy : 0.8861          
##                  95% CI : (0.7947, 0.9466)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 1.615e-11       
##                                           
##                   Kappa : 0.7716          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.8810          
##             Specificity : 0.8919          
##          Pos Pred Value : 0.9024          
##          Neg Pred Value : 0.8684          
##              Prevalence : 0.5316          
##          Detection Rate : 0.4684          
##    Detection Prevalence : 0.5190          
##       Balanced Accuracy : 0.8864          
##                                           
##        'Positive' Class : 0               
## 

For the QDA model, it has an overall accuracy of 88.61%, meaning 11.39% of test error.

(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_glm = glm(mpg01 ~ cylinders + displacement + weight, data = Atrain)
auto_prod2 = predict.glm(auto_glm, Atest, type = "response")
auto_pred2 = ifelse(auto_prod2 >= 0.5, "1", "0")
caret::confusionMatrix(as.factor(auto_pred2), Atest$mpg01, positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  4
##          1  7 33
##                                           
##                Accuracy : 0.8608          
##                  95% CI : (0.7645, 0.9284)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 5.745e-10       
##                                           
##                   Kappa : 0.7217          
##                                           
##  Mcnemar's Test P-Value : 0.5465          
##                                           
##             Sensitivity : 0.8919          
##             Specificity : 0.8333          
##          Pos Pred Value : 0.8250          
##          Neg Pred Value : 0.8974          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4177          
##    Detection Prevalence : 0.5063          
##       Balanced Accuracy : 0.8626          
##                                           
##        'Positive' Class : 1               
## 

For the logistic regression model, the overall accuracy is 86%, therefore the test has 14% error.

(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_b <- naiveBayes(mpg01~ cylinders + displacement + weight, data=Atrain)
auto_pred3 <- predict(auto_b, Atest)
caret::confusionMatrix(as.factor(auto_pred3), Atest$mpg01, positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 36  4
##          1  6 33
##                                           
##                Accuracy : 0.8734          
##                  95% CI : (0.7795, 0.9376)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 1.017e-10       
##                                           
##                   Kappa : 0.7466          
##                                           
##  Mcnemar's Test P-Value : 0.7518          
##                                           
##             Sensitivity : 0.8919          
##             Specificity : 0.8571          
##          Pos Pred Value : 0.8462          
##          Neg Pred Value : 0.9000          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4177          
##    Detection Prevalence : 0.4937          
##       Balanced Accuracy : 0.8745          
##                                           
##        'Positive' Class : 1               
## 

The naive Bayes model has overall 87.3% accuracy, therefore there’s 12.7% of test error.

(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?
set.seed(123)

train2 = cbind(Atrain$cylinders, Atrain$displacement, Atrain$weight)
test2=cbind(Atest$cylinders, Atest$displacement, Atest$weight)
Mtrain = Atrain$mpg01
auto_knn1 =knn(train2, test2, Mtrain, k=1)
caret::confusionMatrix(auto_knn1, Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 36  9
##          1  6 28
##                                           
##                Accuracy : 0.8101          
##                  95% CI : (0.7062, 0.8897)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 2.28e-07        
##                                           
##                   Kappa : 0.6169          
##                                           
##  Mcnemar's Test P-Value : 0.6056          
##                                           
##             Sensitivity : 0.8571          
##             Specificity : 0.7568          
##          Pos Pred Value : 0.8000          
##          Neg Pred Value : 0.8235          
##              Prevalence : 0.5316          
##          Detection Rate : 0.4557          
##    Detection Prevalence : 0.5696          
##       Balanced Accuracy : 0.8069          
##                                           
##        'Positive' Class : 0               
## 
auto_knn2 =knn(train2, test2, Mtrain, k=5)
caret::confusionMatrix(auto_knn2, Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  5
##          1  7 32
##                                          
##                Accuracy : 0.8481         
##                  95% CI : (0.7497, 0.919)
##     No Information Rate : 0.5316         
##     P-Value [Acc > NIR] : 2.935e-09      
##                                          
##                   Kappa : 0.696          
##                                          
##  Mcnemar's Test P-Value : 0.7728         
##                                          
##             Sensitivity : 0.8333         
##             Specificity : 0.8649         
##          Pos Pred Value : 0.8750         
##          Neg Pred Value : 0.8205         
##              Prevalence : 0.5316         
##          Detection Rate : 0.4430         
##    Detection Prevalence : 0.5063         
##       Balanced Accuracy : 0.8491         
##                                          
##        'Positive' Class : 0              
## 
auto_knn3 =knn(train2, test2, Mtrain, k=10)
caret::confusionMatrix(auto_knn3, Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  4
##          1  7 33
##                                           
##                Accuracy : 0.8608          
##                  95% CI : (0.7645, 0.9284)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 5.745e-10       
##                                           
##                   Kappa : 0.7217          
##                                           
##  Mcnemar's Test P-Value : 0.5465          
##                                           
##             Sensitivity : 0.8333          
##             Specificity : 0.8919          
##          Pos Pred Value : 0.8974          
##          Neg Pred Value : 0.8250          
##              Prevalence : 0.5316          
##          Detection Rate : 0.4430          
##    Detection Prevalence : 0.4937          
##       Balanced Accuracy : 0.8626          
##                                           
##        'Positive' Class : 0               
## 
auto_knn4 =knn(train2, test2, Mtrain, k=20)
caret::confusionMatrix(auto_knn4, Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  3
##          1  7 34
##                                           
##                Accuracy : 0.8734          
##                  95% CI : (0.7795, 0.9376)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 1.017e-10       
##                                           
##                   Kappa : 0.7474          
##                                           
##  Mcnemar's Test P-Value : 0.3428          
##                                           
##             Sensitivity : 0.8333          
##             Specificity : 0.9189          
##          Pos Pred Value : 0.9211          
##          Neg Pred Value : 0.8293          
##              Prevalence : 0.5316          
##          Detection Rate : 0.4430          
##    Detection Prevalence : 0.4810          
##       Balanced Accuracy : 0.8761          
##                                           
##        'Positive' Class : 0               
## 
auto_knn5 =knn(train2, test2, Mtrain, k=25)
caret::confusionMatrix(auto_knn5, Atest$mpg01)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  4
##          1  7 33
##                                           
##                Accuracy : 0.8608          
##                  95% CI : (0.7645, 0.9284)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 5.745e-10       
##                                           
##                   Kappa : 0.7217          
##                                           
##  Mcnemar's Test P-Value : 0.5465          
##                                           
##             Sensitivity : 0.8333          
##             Specificity : 0.8919          
##          Pos Pred Value : 0.8974          
##          Neg Pred Value : 0.8250          
##              Prevalence : 0.5316          
##          Detection Rate : 0.4430          
##    Detection Prevalence : 0.4937          
##       Balanced Accuracy : 0.8626          
##                                           
##        'Positive' Class : 0               
## 

I tested the KNN method with k = 1, 5, 10, 20, 25. The test error decreses as k number increases, and the best performing model has k=20 with overall accuracy of 87.34%, therefore a test error of 12.66%.

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.
Boston$crim1 <- ifelse(Boston$crim > median(Boston$crim), 1, 0)
set.seed(123)
boston_ind <- sample(1:nrow(Boston), 0.8 * nrow(Boston))
btrain <- Boston[boston_ind, ]
btest <- Boston[-boston_ind, ]
# Fit glm model
b1 = glm(crim1 ~ . - crim, data = btrain, family = binomial)
bprod1 = predict.glm(b1, btest, type = "response")
bpred1 = ifelse(bprod1 >= 0.5, "1", "0")

# Fit LDA model
b2 <- lda(crim1 ~ .  - crim, data = btrain)
bpred2 = predict(b2, btest, type = "response")

# Fit naive Bayes model
b3 <- naiveBayes(crim1 ~ .  - crim, data = btrain)
bpred3 = predict(b3, btest)

# Fit KNN model
b4 <- knn(btrain[, -which(names(btrain) %in% c("crim", "crim1"))], 
           btest[, -which(names(btest) %in% c("crim", "crim1"))], 
           btrain$crim1, k = 20)

caret::confusionMatrix(as.factor(bpred1), as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 40  7
##          1  9 46
##                                           
##                Accuracy : 0.8431          
##                  95% CI : (0.7578, 0.9076)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 6.701e-12       
##                                           
##                   Kappa : 0.6853          
##                                           
##  Mcnemar's Test P-Value : 0.8026          
##                                           
##             Sensitivity : 0.8679          
##             Specificity : 0.8163          
##          Pos Pred Value : 0.8364          
##          Neg Pred Value : 0.8511          
##              Prevalence : 0.5196          
##          Detection Rate : 0.4510          
##    Detection Prevalence : 0.5392          
##       Balanced Accuracy : 0.8421          
##                                           
##        'Positive' Class : 1               
## 
caret::confusionMatrix(as.factor(bpred2$class), as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 41 12
##          1  8 41
##                                           
##                Accuracy : 0.8039          
##                  95% CI : (0.7135, 0.8759)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 2.318e-09       
##                                           
##                   Kappa : 0.6084          
##                                           
##  Mcnemar's Test P-Value : 0.5023          
##                                           
##             Sensitivity : 0.7736          
##             Specificity : 0.8367          
##          Pos Pred Value : 0.8367          
##          Neg Pred Value : 0.7736          
##              Prevalence : 0.5196          
##          Detection Rate : 0.4020          
##    Detection Prevalence : 0.4804          
##       Balanced Accuracy : 0.8052          
##                                           
##        'Positive' Class : 1               
## 
caret::confusionMatrix(bpred3, as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 41 14
##          1  8 39
##                                           
##                Accuracy : 0.7843          
##                  95% CI : (0.6919, 0.8596)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 2.976e-08       
##                                           
##                   Kappa : 0.57            
##                                           
##  Mcnemar's Test P-Value : 0.2864          
##                                           
##             Sensitivity : 0.7358          
##             Specificity : 0.8367          
##          Pos Pred Value : 0.8298          
##          Neg Pred Value : 0.7455          
##              Prevalence : 0.5196          
##          Detection Rate : 0.3824          
##    Detection Prevalence : 0.4608          
##       Balanced Accuracy : 0.7863          
##                                           
##        'Positive' Class : 1               
## 
caret::confusionMatrix(b4, as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 45  9
##          1  4 44
##                                           
##                Accuracy : 0.8725          
##                  95% CI : (0.7919, 0.9304)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 3.975e-14       
##                                           
##                   Kappa : 0.7457          
##                                           
##  Mcnemar's Test P-Value : 0.2673          
##                                           
##             Sensitivity : 0.8302          
##             Specificity : 0.9184          
##          Pos Pred Value : 0.9167          
##          Neg Pred Value : 0.8333          
##              Prevalence : 0.5196          
##          Detection Rate : 0.4314          
##    Detection Prevalence : 0.4706          
##       Balanced Accuracy : 0.8743          
##                                           
##        'Positive' Class : 1               
## 

I started the model with all the variables as predictors and explored logistic regression, LDA, naive Bayes, and KNN models. The best performing model out of all is the knn model (k=20) with the highest overall (87%), sensitivity (83%), and specificity score (92%).

summary(b1)
## 
## Call:
## glm(formula = crim1 ~ . - crim, family = binomial, data = btrain)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -43.940569   7.699601  -5.707 1.15e-08 ***
## zn           -0.108695   0.043931  -2.474 0.013353 *  
## indus        -0.007583   0.054961  -0.138 0.890263    
## chas          0.192795   0.779468   0.247 0.804644    
## nox          45.609507   8.736925   5.220 1.79e-07 ***
## rm            0.499219   0.794694   0.628 0.529879    
## age           0.021687   0.013745   1.578 0.114617    
## dis           0.612345   0.238999   2.562 0.010403 *  
## rad           0.632731   0.181996   3.477 0.000508 ***
## tax          -0.008401   0.003118  -2.694 0.007058 ** 
## ptratio       0.387566   0.138564   2.797 0.005158 ** 
## lstat         0.115663   0.055658   2.078 0.037701 *  
## medv          0.165532   0.077288   2.142 0.032214 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 560.02  on 403  degrees of freedom
## Residual deviance: 169.24  on 391  degrees of freedom
## AIC: 195.24
## 
## Number of Fisher Scoring iterations: 9

Next, I only want to look at the most significant varibles and use them as predictors.

# Fit glm model
b5 = glm(crim1 ~ zn + nox + dis + rad + tax + ptratio + medv, data = btrain, family = binomial)
bprod5 = predict.glm(b5, btest, type = "response")
bpred5 = ifelse(bprod1 >= 0.5, "1", "0")

# Fit LDA model
b6 <- lda(crim1 ~ zn + nox + dis + rad + tax + ptratio + medv, data = btrain)
bpred6 = predict(b6, btest, type = "response")

# Fit naive Bayes model
b7 <- naiveBayes(crim1 ~ zn + nox + dis + rad + tax + ptratio + medv, data = btrain)
bpred7 = predict(b7, btest)

# Fit KNN model
train5 = cbind(btrain$zn,  btrain$nox, btrain$dis, btrain$rad, btrain$tax, btrain$ptratio, btrain$medv)
test5=cbind(btest$zn,  btest$nox, btest$dis, btest$rad, btest$tax, btest$ptratio, btest$medv)
b8 <- knn(train5, test5, btrain$crim1, k = 20)

caret::confusionMatrix(as.factor(bpred5), as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 40  7
##          1  9 46
##                                           
##                Accuracy : 0.8431          
##                  95% CI : (0.7578, 0.9076)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 6.701e-12       
##                                           
##                   Kappa : 0.6853          
##                                           
##  Mcnemar's Test P-Value : 0.8026          
##                                           
##             Sensitivity : 0.8679          
##             Specificity : 0.8163          
##          Pos Pred Value : 0.8364          
##          Neg Pred Value : 0.8511          
##              Prevalence : 0.5196          
##          Detection Rate : 0.4510          
##    Detection Prevalence : 0.5392          
##       Balanced Accuracy : 0.8421          
##                                           
##        'Positive' Class : 1               
## 
caret::confusionMatrix(as.factor(bpred6$class), as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 42 11
##          1  7 42
##                                           
##                Accuracy : 0.8235          
##                  95% CI : (0.7355, 0.8919)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 1.42e-10        
##                                           
##                   Kappa : 0.6476          
##                                           
##  Mcnemar's Test P-Value : 0.4795          
##                                           
##             Sensitivity : 0.7925          
##             Specificity : 0.8571          
##          Pos Pred Value : 0.8571          
##          Neg Pred Value : 0.7925          
##              Prevalence : 0.5196          
##          Detection Rate : 0.4118          
##    Detection Prevalence : 0.4804          
##       Balanced Accuracy : 0.8248          
##                                           
##        'Positive' Class : 1               
## 
caret::confusionMatrix(bpred7, as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 40 13
##          1  9 40
##                                           
##                Accuracy : 0.7843          
##                  95% CI : (0.6919, 0.8596)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : 2.976e-08       
##                                           
##                   Kappa : 0.5693          
##                                           
##  Mcnemar's Test P-Value : 0.5224          
##                                           
##             Sensitivity : 0.7547          
##             Specificity : 0.8163          
##          Pos Pred Value : 0.8163          
##          Neg Pred Value : 0.7547          
##              Prevalence : 0.5196          
##          Detection Rate : 0.3922          
##    Detection Prevalence : 0.4804          
##       Balanced Accuracy : 0.7855          
##                                           
##        'Positive' Class : 1               
## 
caret::confusionMatrix(b8, as.factor(btest$crim1), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 46  6
##          1  3 47
##                                           
##                Accuracy : 0.9118          
##                  95% CI : (0.8391, 0.9589)
##     No Information Rate : 0.5196          
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.8237          
##                                           
##  Mcnemar's Test P-Value : 0.505           
##                                           
##             Sensitivity : 0.8868          
##             Specificity : 0.9388          
##          Pos Pred Value : 0.9400          
##          Neg Pred Value : 0.8846          
##              Prevalence : 0.5196          
##          Detection Rate : 0.4608          
##    Detection Prevalence : 0.4902          
##       Balanced Accuracy : 0.9128          
##                                           
##        'Positive' Class : 1               
## 

After using all the statistically significant predictors for all the models, the best model is still the KNN model with k = 20. This second KNN model has an overall accuracy of 92%, sensitivity of 89%, specificity of 94%. Comparing both KNN models, I find the second one has the highest performance score, therefore, it is best to use a model with statistically significant predictors.