10

This question should be answered using the Weekly data set, which is part of the ISLR 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.

10-A)

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

Let’s do a summary first.

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

Looks like Direction is up more often than down, 605 to 484.

A gander at pair plots for the data might show us some relations:

pairs(Weekly)

It looks like there may be a relation between Year and Volume so let us examine correlations next.

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

There does appear to be a correlation between Volume and Year, with a value of ~0.842. As with the plot, this table does not indicate any other correlations.

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

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

AIC of the model is 1500. Only Lag2 is statistically significant, with a p-value of approximately 0.03. This assumes we’ve got a selection threshold of 0.05.

10-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.model, type = 'response')
glm.preds<-rep('Down', 1089)
glm.preds[glm.probs > 0.5] = 'Up'
table(glm.preds, Direction)
##          Direction
## glm.preds Down  Up
##      Down   54  48
##      Up    430 557
#And here's Caret's Confusion Matrix
caret::confusionMatrix(as.factor(glm.preds), 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             
## 

Accuracy of the model is 56.11%. The model is good with it’s Sensitivity at 92.1%, predicting the market was up when it was really up. The model misses most cases when the market goes down, achieving only 11.2% specificity. For a good model, ideally we would like both sensitivity and specificity to be high. As it is, we might have similar luck training a pigeon to peck at the “Up” vote…maybe even make more of a profit if we give the bird a name, a Youtube account and social media presence.

10-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.train<-Weekly[train, ]
Weekly.test<-Weekly[!train, ]

glm.model10D<-glm(Direction~Lag2, data=Weekly.train, family=binomial)
glm.model10D.probs<-predict(glm.model10D, Weekly.test, type = 'response')
glm.10D.preds<- rep('Down', length(glm.model10D.probs))
glm.10D.preds[glm.model10D.probs>0.5]='Up'

caret::confusionMatrix(as.factor(glm.10D.preds), Weekly.test$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             
## 

Our confusion matrix indicates a model accuracy of 62.5% overall fraction of correct predictions. Our sensitivity and specificity are still out of alignment at 91.8% and 20.9%, respectively.

10-E)

Repeat (d) using LDA.

library(MASS)
lda.fit<- lda(Direction~ Lag2, data = Weekly.train)
lda.preds<- predict(lda.fit, Weekly.test)
lda.class<- lda.preds$class

caret::confusionMatrix(lda.class, Weekly.test$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             
## 

The overall predictive accuracy of the LDA model is still 62.5%. Sensitivity and specificity have not changed.

10-F)

Repeat (d) using QDA.

QDA.fit<- qda(Direction~Lag2, data=Weekly.train)
QDA.preds<- predict(QDA.fit, Weekly.test)
QDA.class<-QDA.preds$class

caret::confusionMatrix(QDA.class, Weekly.test$Direction, positive = 'Up')
## 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 : 1.0000          
##             Specificity : 0.0000          
##          Pos Pred Value : 0.5865          
##          Neg Pred Value :    NaN          
##              Prevalence : 0.5865          
##          Detection Rate : 0.5865          
##    Detection Prevalence : 1.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : Up              
## 

Overall predictive model accuracy for QDA has dropped to 58.7%, and the model is predicting only “Up” direction. Might as well use the Homer Simpson solution of having a “thirsty bird” positioned at the side of the keyboard to tap the “Up” button.

10-G)

Repeat (d) using KNN with K = 1.

library(class)
train.X <- cbind(Weekly.train$Lag2)
test.X <- cbind(Weekly.test$Lag2)
train.Direction <- Weekly.train$Direction

set.seed(1)

knn.pred<- knn(train.X, test.X, train.Direction, k = 1)
caret::confusionMatrix(knn.pred, Weekly.test$Direction, positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   21 30
##       Up     22 31
##                                           
##                Accuracy : 0.5             
##                  95% CI : (0.4003, 0.5997)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.9700          
##                                           
##                   Kappa : -0.0033         
##                                           
##  Mcnemar's Test P-Value : 0.3317          
##                                           
##             Sensitivity : 0.5082          
##             Specificity : 0.4884          
##          Pos Pred Value : 0.5849          
##          Neg Pred Value : 0.4118          
##              Prevalence : 0.5865          
##          Detection Rate : 0.2981          
##    Detection Prevalence : 0.5096          
##       Balanced Accuracy : 0.4983          
##                                           
##        'Positive' Class : Up              
## 

Overall predictive accuracy of KNN that’s super overfitting is 0.5. Sensitivity and specificity are better evenly matched this time, though.

10-H)

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

LDA and simple logistic regression have the highest accuracy.

10-I)

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.

First I’ll muck about with different predictors on logistic regression. Lag1 had the second most significant p-value, next to Lag2.

glm.model10I<-glm(Direction~Lag2 + Lag1, data=Weekly.train, family=binomial)
glm.model10I.probs<-predict(glm.model10I, Weekly.test, type = 'response')
glm.10I.preds<- rep('Down', length(glm.model10I.probs))
glm.10I.preds[glm.model10I.probs>0.5]='Up'

caret::confusionMatrix(as.factor(glm.10I.preds), Weekly.test$Direction, positive = 'Up')
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    7  8
##       Up     36 53
##                                           
##                Accuracy : 0.5769          
##                  95% CI : (0.4761, 0.6732)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.6193          
##                                           
##                   Kappa : 0.035           
##                                           
##  Mcnemar's Test P-Value : 4.693e-05       
##                                           
##             Sensitivity : 0.8689          
##             Specificity : 0.1628          
##          Pos Pred Value : 0.5955          
##          Neg Pred Value : 0.4667          
##              Prevalence : 0.5865          
##          Detection Rate : 0.5096          
##    Detection Prevalence : 0.8558          
##       Balanced Accuracy : 0.5158          
##                                           
##        'Positive' Class : Up              
## 

Combination of Lag2 and Lag1 results in lower overall accuracy.

Linear Discriminant Analysis for Lag2, Lag1 interaction.

lda.fit.10I<- lda(Direction ~ Lag2:Lag1, data = Weekly.train)
lda.preds.10I<- predict(lda.fit.10I, Weekly.test)
lda.class.10I<- lda.preds.10I$class

caret::confusionMatrix(lda.class.10I, Weekly.test$Direction, positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    0  1
##       Up     43 60
##                                           
##                Accuracy : 0.5769          
##                  95% CI : (0.4761, 0.6732)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.6193          
##                                           
##                   Kappa : -0.0192         
##                                           
##  Mcnemar's Test P-Value : 6.37e-10        
##                                           
##             Sensitivity : 0.9836          
##             Specificity : 0.0000          
##          Pos Pred Value : 0.5825          
##          Neg Pred Value : 0.0000          
##              Prevalence : 0.5865          
##          Detection Rate : 0.5769          
##    Detection Prevalence : 0.9904          
##       Balanced Accuracy : 0.4918          
##                                           
##        'Positive' Class : Up              
## 

Preditive accuacy is not as good as before, and specificity is horrible.

Doing QDA combination of Lag2 and Lag1

QDA.fit.10I<- qda(Direction~Lag2 + Lag1, data=Weekly.train)
QDA.preds.10I<- predict(QDA.fit.10I, Weekly.test)
QDA.class.10I<-QDA.preds.10I$class

caret::confusionMatrix(QDA.class.10I, Weekly.test$Direction, positive = 'Up')
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    7 10
##       Up     36 51
##                                         
##                Accuracy : 0.5577        
##                  95% CI : (0.457, 0.655)
##     No Information Rate : 0.5865        
##     P-Value [Acc > NIR] : 0.7579156     
##                                         
##                   Kappa : -0.0013       
##                                         
##  Mcnemar's Test P-Value : 0.0002278     
##                                         
##             Sensitivity : 0.8361        
##             Specificity : 0.1628        
##          Pos Pred Value : 0.5862        
##          Neg Pred Value : 0.4118        
##              Prevalence : 0.5865        
##          Detection Rate : 0.4904        
##    Detection Prevalence : 0.8365        
##       Balanced Accuracy : 0.4994        
##                                         
##        'Positive' Class : Up            
## 

Again, still lower than original model.

Now trying different values of K for KNN.

#KNN with K = 4
knn.pred.10I<- knn(train.X, test.X, train.Direction, k = 4)
caret::confusionMatrix(knn.pred.10I, Weekly.test$Direction, positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   16 20
##       Up     27 41
##                                           
##                Accuracy : 0.5481          
##                  95% CI : (0.4474, 0.6459)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.8152          
##                                           
##                   Kappa : 0.0453          
##                                           
##  Mcnemar's Test P-Value : 0.3815          
##                                           
##             Sensitivity : 0.6721          
##             Specificity : 0.3721          
##          Pos Pred Value : 0.6029          
##          Neg Pred Value : 0.4444          
##              Prevalence : 0.5865          
##          Detection Rate : 0.3942          
##    Detection Prevalence : 0.6538          
##       Balanced Accuracy : 0.5221          
##                                           
##        'Positive' Class : Up              
## 
#KNN with K = 40
knn.pred.10I<- knn(train.X, test.X, train.Direction, k = 40)
caret::confusionMatrix(knn.pred.10I, Weekly.test$Direction, positive = "Up")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   21 23
##       Up     22 38
##                                           
##                Accuracy : 0.5673          
##                  95% CI : (0.4665, 0.6641)
##     No Information Rate : 0.5865          
##     P-Value [Acc > NIR] : 0.6921          
##                                           
##                   Kappa : 0.1109          
##                                           
##  Mcnemar's Test P-Value : 1.0000          
##                                           
##             Sensitivity : 0.6230          
##             Specificity : 0.4884          
##          Pos Pred Value : 0.6333          
##          Neg Pred Value : 0.4773          
##              Prevalence : 0.5865          
##          Detection Rate : 0.3654          
##    Detection Prevalence : 0.5769          
##       Balanced Accuracy : 0.5557          
##                                           
##        'Positive' Class : Up              
## 

Looks like the original logistic regression and LDA, targeting only the statistically significant variable, have the highest overall predictive model accuracy.

11

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.

11-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.data<-Auto

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

11-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(Auto.data[ ,-9])

Looks like there’s positive relations between displacement and horsepower, horsepower and weight, displacement and weight. Weaker relations, all negative, between mpg and displacement, mpg and horsepower, mpg and weight, horsepower and acceleration, displacement and acceleration. But because mpg01 is binary, we really can’t get much that tells us about that particular variable.

cor(Auto.data[ ,-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

Correlation table shows negative relations between mpg and: cylinders, displacement, horsepower, weight.

11-C)

Split the data into a training set and a test set.

# Let's do an 80/20 train/test split
set.seed(1)
index <- sample(1:nrow(Auto.data), 0.8*nrow(Auto.data))
Auto.train<-Auto.data[index, ]
Auto.test<-Auto.data[-index, ]

11-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.mpg01.fit <- lda(mpg01 ~ cylinders + displacement + weight + horsepower, data=Auto.train)
lda.mpg01.preds <- predict(lda.mpg01.fit, Auto.test)
lda.mpg01.class <- lda.mpg01.preds$class

caret::confusionMatrix(lda.mpg01.class, as.factor(Auto.test$mpg01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  0
##          1  7 37
##                                           
##                Accuracy : 0.9114          
##                  95% CI : (0.8259, 0.9636)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 2.819e-13       
##                                           
##                   Kappa : 0.8241          
##                                           
##  Mcnemar's Test P-Value : 0.02334         
##                                           
##             Sensitivity : 1.0000          
##             Specificity : 0.8333          
##          Pos Pred Value : 0.8409          
##          Neg Pred Value : 1.0000          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4684          
##    Detection Prevalence : 0.5570          
##       Balanced Accuracy : 0.9167          
##                                           
##        'Positive' Class : 1               
## 
#or just use mean(lda.mpg01.class != Auto.test$mpg01)

Overall prediction accuracy rate is 91.14%. The error rate is (1 - 0.9114) 8.86%.

11-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.mpg01.fit <- qda(mpg01 ~ cylinders + displacement + weight + horsepower, data=Auto.train)
QDA.mpg01.preds <- predict(QDA.mpg01.fit, Auto.test)
QDA.mpg01.class <- QDA.mpg01.preds$class

caret::confusionMatrix(QDA.mpg01.class, as.factor(Auto.test$mpg01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 37  2
##          1  5 35
##                                           
##                Accuracy : 0.9114          
##                  95% CI : (0.8259, 0.9636)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 2.819e-13       
##                                           
##                   Kappa : 0.8229          
##                                           
##  Mcnemar's Test P-Value : 0.4497          
##                                           
##             Sensitivity : 0.9459          
##             Specificity : 0.8810          
##          Pos Pred Value : 0.8750          
##          Neg Pred Value : 0.9487          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4430          
##    Detection Prevalence : 0.5063          
##       Balanced Accuracy : 0.9134          
##                                           
##        'Positive' Class : 1               
## 

Overall accuracy is identical to previous model. Error rate is (1 - 0.9114) 8.86% again.

11-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.mpg01.fit <- glm(mpg01 ~ cylinders + displacement + weight + horsepower, data=Auto.train, family = binomial)
glm.mpg01.probs <- predict(glm.mpg01.fit, Auto.test, type = "response")
glm.mpg01.preds <- rep(0, length(glm.mpg01.probs))
glm.mpg01.preds[glm.mpg01.probs>0.5]=1

caret::confusionMatrix(as.factor(glm.mpg01.preds), as.factor(Auto.test$mpg01), positive="1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 38  1
##          1  4 36
##                                           
##                Accuracy : 0.9367          
##                  95% CI : (0.8584, 0.9791)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 2.725e-15       
##                                           
##                   Kappa : 0.8735          
##                                           
##  Mcnemar's Test P-Value : 0.3711          
##                                           
##             Sensitivity : 0.9730          
##             Specificity : 0.9048          
##          Pos Pred Value : 0.9000          
##          Neg Pred Value : 0.9744          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4557          
##    Detection Prevalence : 0.5063          
##       Balanced Accuracy : 0.9389          
##                                           
##        'Positive' Class : 1               
## 

Error rate of the GLM is (1 - 0.9367) 6.33%

11-G)

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.Auto.X <- cbind(Auto.train$cylinders, Auto.train$displacement, Auto.train$weight, Auto.train$horsepower)
test.Auto.X <- cbind(Auto.test$cylinders, Auto.test$displacement, Auto.test$weight, Auto.test$horsepower)
train.mpg01 <- Auto.train$mpg01

set.seed(1)

#K=5

knn.mpg01.pred <- knn(train.Auto.X, test.Auto.X, train.mpg01, k=5)

caret::confusionMatrix(knn.mpg01.pred, as.factor(Auto.test$mpg01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 38  4
##          1  4 33
##                                           
##                Accuracy : 0.8987          
##                  95% CI : (0.8102, 0.9553)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 2.278e-12       
##                                           
##                   Kappa : 0.7967          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.8919          
##             Specificity : 0.9048          
##          Pos Pred Value : 0.8919          
##          Neg Pred Value : 0.9048          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4177          
##    Detection Prevalence : 0.4684          
##       Balanced Accuracy : 0.8983          
##                                           
##        'Positive' Class : 1               
## 

The test error associated with k=5 is 1-0.8987 = 10.13%.

#K=10
set.seed(1)
knn.mpg01.pred <- knn(train.Auto.X, test.Auto.X, train.mpg01, k=10)

caret::confusionMatrix(knn.mpg01.pred, as.factor(Auto.test$mpg01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 35  2
##          1  7 35
##                                           
##                Accuracy : 0.8861          
##                  95% CI : (0.7947, 0.9466)
##     No Information Rate : 0.5316          
##     P-Value [Acc > NIR] : 1.615e-11       
##                                           
##                   Kappa : 0.7731          
##                                           
##  Mcnemar's Test P-Value : 0.1824          
##                                           
##             Sensitivity : 0.9459          
##             Specificity : 0.8333          
##          Pos Pred Value : 0.8333          
##          Neg Pred Value : 0.9459          
##              Prevalence : 0.4684          
##          Detection Rate : 0.4430          
##    Detection Prevalence : 0.5316          
##       Balanced Accuracy : 0.8896          
##                                           
##        'Positive' Class : 1               
## 

The test error associated with k=10 is 1-0.8861 = 11.39%

#K=75
set.seed(1)
knn.mpg01.pred <- knn(train.Auto.X, test.Auto.X, train.mpg01, k=75)

caret::confusionMatrix(knn.mpg01.pred, as.factor(Auto.test$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               
## 

With k=75, the test error rate is 1-0.8608 = 13.92%. In this case, the k=5 model seems to perform the best, with 5 nearest neighbors.

13

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

First I will create the binary crime statistic.

Boston.data<-Boston

#Create a binary crime (crim01) to represent above/below as 1/0 median value of "crim".

crim01 <- rep(0, length(Boston.data$crim))
crim01[Boston.data$crim > median(Boston.data$crim)] = 1
Boston.data<-data.frame(Boston.data, crim01)

Now it is time to create a train/test split. I shall use an 80/20 split.

set.seed(1)
index13 <- sample(1:nrow(Boston.data), 0.8*nrow(Boston.data))
Boston.train <- Boston.data[index13, ]
Boston.test <- Boston.data[-index13, ]

Let’s play with logistic regression, and use crim01 related to all other variables except for the original crim.

glm.crim01.fit <- glm(crim01 ~ . - crim, Boston.train, family = binomial)
summary(glm.crim01.fit)
## 
## Call:
## glm(formula = crim01 ~ . - crim, family = binomial, data = Boston.train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0320  -0.1436  -0.0001   0.0016   3.6189  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -42.886750   7.627711  -5.622 1.88e-08 ***
## zn           -0.106512   0.042954  -2.480 0.013149 *  
## indus        -0.064955   0.051562  -1.260 0.207759    
## chas          0.473349   0.786069   0.602 0.547059    
## nox          56.659757   9.246096   6.128 8.90e-10 ***
## rm           -0.116177   0.846737  -0.137 0.890868    
## age           0.021587   0.013568   1.591 0.111610    
## dis           1.068641   0.278562   3.836 0.000125 ***
## rad           0.696528   0.175753   3.963 7.40e-05 ***
## tax          -0.007585   0.003075  -2.466 0.013646 *  
## ptratio       0.362327   0.148310   2.443 0.014564 *  
## black        -0.010208   0.005643  -1.809 0.070462 .  
## lstat         0.078033   0.055794   1.399 0.161939    
## medv          0.165209   0.080364   2.056 0.039806 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 560.06  on 403  degrees of freedom
## Residual deviance: 159.83  on 390  degrees of freedom
## AIC: 187.83
## 
## Number of Fisher Scoring iterations: 9

Variables zn, nox, dis, rad, tax, ptratio and medv are statistically significant. Let’s continue and push with the full model.

glm.crim01.probs <- predict(glm.crim01.fit, Boston.test, type = 'response')
glm.crim01.preds <- rep(0, length(glm.crim01.probs))
glm.crim01.preds[glm.crim01.probs > 0.5] = 1

caret::confusionMatrix(as.factor(glm.crim01.preds), as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 43  5
##          1  8 46
##                                           
##                Accuracy : 0.8725          
##                  95% CI : (0.7919, 0.9304)
##     No Information Rate : 0.5             
##     P-Value [Acc > NIR] : 2.151e-15       
##                                           
##                   Kappa : 0.7451          
##                                           
##  Mcnemar's Test P-Value : 0.5791          
##                                           
##             Sensitivity : 0.9020          
##             Specificity : 0.8431          
##          Pos Pred Value : 0.8519          
##          Neg Pred Value : 0.8958          
##              Prevalence : 0.5000          
##          Detection Rate : 0.4510          
##    Detection Prevalence : 0.5294          
##       Balanced Accuracy : 0.8725          
##                                           
##        'Positive' Class : 1               
## 

The logistic regression full model has an overall accuracy of 87.25%. Its sensitivity is 90.2% and its specificity is 84.31%. Sensitivity is known as “Recall” and is the ratio of the model predicting “1” when the reference was “1”. Specificity is the ratio of the model predicting “0” when the reality is “0”.

Let’s see what happens if we strip away the variables that are not statistically significant from the full model! Normally you’d use something like stepwise model selection, but here I’m just going to do a quick hack-and-slash.

glm.crim01.fit2 <- glm(crim01 ~ . - crim - indus - chas - rm - age - black - lstat, Boston.train, family = binomial)

glm.crim01.probs2 <- predict(glm.crim01.fit2, Boston.test, type = 'response')
glm.crim01.preds2 <- rep(0, length(glm.crim01.probs2))
glm.crim01.preds2[glm.crim01.probs2 > 0.5] = 1

caret::confusionMatrix(as.factor(glm.crim01.preds2), as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 44  6
##          1  7 45
##                                           
##                Accuracy : 0.8725          
##                  95% CI : (0.7919, 0.9304)
##     No Information Rate : 0.5             
##     P-Value [Acc > NIR] : 2.151e-15       
##                                           
##                   Kappa : 0.7451          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.8824          
##             Specificity : 0.8627          
##          Pos Pred Value : 0.8654          
##          Neg Pred Value : 0.8800          
##              Prevalence : 0.5000          
##          Detection Rate : 0.4412          
##    Detection Prevalence : 0.5098          
##       Balanced Accuracy : 0.8725          
##                                           
##        'Positive' Class : 1               
## 

Having stripped away the variables that were not statistically significant, we find that the overall model accuracy is 87.25%. It hasn’t changed from the full model. However the values for sensitivity and specificity have, at 88.24% and 86.27% respectively.

We now examine linear discriminant analysis (LDA) on the same data.

lda.crim01.fit <- lda(crim01 ~ . - crim, Boston.train)
lda.crim01.preds <- predict(lda.crim01.fit, Boston.test)
lda.crim01.class <- lda.crim01.preds$class

caret::confusionMatrix(lda.crim01.class, as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 50 13
##          1  1 38
##                                           
##                Accuracy : 0.8627          
##                  95% CI : (0.7804, 0.9229)
##     No Information Rate : 0.5             
##     P-Value [Acc > NIR] : 1.388e-14       
##                                           
##                   Kappa : 0.7255          
##                                           
##  Mcnemar's Test P-Value : 0.003283        
##                                           
##             Sensitivity : 0.7451          
##             Specificity : 0.9804          
##          Pos Pred Value : 0.9744          
##          Neg Pred Value : 0.7937          
##              Prevalence : 0.5000          
##          Detection Rate : 0.3725          
##    Detection Prevalence : 0.3824          
##       Balanced Accuracy : 0.8627          
##                                           
##        'Positive' Class : 1               
## 

The overall accuracy of this model is 86.27%. It’s got a 74.51% ratio for accurately predicting “1” from the reference “1” condition (sensitivity), and a 98.04% ratio for accurately predicting “0” from the reference “0” condition (specificity).

Let’s see what happens when we run the trimmed model (where I yanked the variables that were not statistically significant).

lda.crim01.fit2 <- lda(crim01 ~ . - crim - indus - chas - rm - age - black - lstat, Boston.train)
lda.crim01.preds2 <- predict(lda.crim01.fit2, Boston.test)
lda.crim01.class2 <- lda.crim01.preds2$class

caret::confusionMatrix(lda.crim01.class2, as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 50 14
##          1  1 37
##                                           
##                Accuracy : 0.8529          
##                  95% CI : (0.7691, 0.9153)
##     No Information Rate : 0.5             
##     P-Value [Acc > NIR] : 8.267e-14       
##                                           
##                   Kappa : 0.7059          
##                                           
##  Mcnemar's Test P-Value : 0.001946        
##                                           
##             Sensitivity : 0.7255          
##             Specificity : 0.9804          
##          Pos Pred Value : 0.9737          
##          Neg Pred Value : 0.7812          
##              Prevalence : 0.5000          
##          Detection Rate : 0.3627          
##    Detection Prevalence : 0.3725          
##       Balanced Accuracy : 0.8529          
##                                           
##        'Positive' Class : 1               
## 

The “trimmed down” LDA model has an overall model accuracy of 85.29%, which is less than what we had for the full model. Its sensitivity and specificity scores are 72.55% and 98.04%, respectively.

We now turn to KNN with various flavors of K.

train.Boston.X <- cbind(Boston.train$zn, Boston.train$indus, Boston.train$chas, Boston.train$nox,
                        Boston.train$rm, Boston.train$age, Boston.train$dis, Boston.train$rad,
                        Boston.train$tax, Boston.train$ptratio, Boston.train$black,
                        Boston.train$lstat, Boston.train$medv)
test.Boston.X <- cbind(Boston.test$zn, Boston.test$indus, Boston.test$chas, Boston.test$nox,
                        Boston.test$rm, Boston.test$age, Boston.test$dis, Boston.test$rad,
                        Boston.test$tax, Boston.test$ptratio, Boston.test$black,
                        Boston.test$lstat, Boston.test$medv)
train.crim01 <- Boston.train$crim01

set.seed(1)

knn.crim01.pred <- knn(train.Boston.X, test.Boston.X, train.crim01, k = 5)

caret::confusionMatrix(knn.crim01.pred, as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 44  4
##          1  7 47
##                                           
##                Accuracy : 0.8922          
##                  95% CI : (0.8152, 0.9449)
##     No Information Rate : 0.5             
##     P-Value [Acc > NIR] : <2e-16          
##                                           
##                   Kappa : 0.7843          
##                                           
##  Mcnemar's Test P-Value : 0.5465          
##                                           
##             Sensitivity : 0.9216          
##             Specificity : 0.8627          
##          Pos Pred Value : 0.8704          
##          Neg Pred Value : 0.9167          
##              Prevalence : 0.5000          
##          Detection Rate : 0.4608          
##    Detection Prevalence : 0.5294          
##       Balanced Accuracy : 0.8922          
##                                           
##        'Positive' Class : 1               
## 

Overall model accuracy for KNN with k=5 is 89.22%. Sensitivity (predicted “1” over total reference “1”) is 92.16%, and specificity (predicted “0” over total reference “0”) is 86.27%.

# k=15
knn.crim01.pred <- knn(train.Boston.X, test.Boston.X, train.crim01, k = 15)

caret::confusionMatrix(knn.crim01.pred, as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 42 10
##          1  9 41
##                                          
##                Accuracy : 0.8137         
##                  95% CI : (0.7245, 0.884)
##     No Information Rate : 0.5            
##     P-Value [Acc > NIR] : 5.079e-11      
##                                          
##                   Kappa : 0.6275         
##                                          
##  Mcnemar's Test P-Value : 1              
##                                          
##             Sensitivity : 0.8039         
##             Specificity : 0.8235         
##          Pos Pred Value : 0.8200         
##          Neg Pred Value : 0.8077         
##              Prevalence : 0.5000         
##          Detection Rate : 0.4020         
##    Detection Prevalence : 0.4902         
##       Balanced Accuracy : 0.8137         
##                                          
##        'Positive' Class : 1              
## 

Overall accuracy of this KNN with k = 15 is 81.37%. Sensitivity and specificity are 80.39% and 82.35%, respectively.

# k=150
knn.crim01.pred <- knn(train.Boston.X, test.Boston.X, train.crim01, k = 150)

caret::confusionMatrix(knn.crim01.pred, as.factor(Boston.test$crim01), positive = "1")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  0  1
##          0 51 21
##          1  0 30
##                                           
##                Accuracy : 0.7941          
##                  95% CI : (0.7027, 0.8678)
##     No Information Rate : 0.5             
##     P-Value [Acc > NIR] : 8.549e-10       
##                                           
##                   Kappa : 0.5882          
##                                           
##  Mcnemar's Test P-Value : 1.275e-05       
##                                           
##             Sensitivity : 0.5882          
##             Specificity : 1.0000          
##          Pos Pred Value : 1.0000          
##          Neg Pred Value : 0.7083          
##              Prevalence : 0.5000          
##          Detection Rate : 0.2941          
##    Detection Prevalence : 0.2941          
##       Balanced Accuracy : 0.7941          
##                                           
##        'Positive' Class : 1               
## 

With KNN set for k=150, the overall accuracy drops to 79.41%. Its sensitivity and specificity are 58.82% and 100% respectively. I’m not surprised to see this lower overall accuracy, since the higher the value we set K, the more linear things get. Lower K values give us more flexibility…which can mean overfitting, so you have to be wary of that.