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

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

str(Weekly)
## 'data.frame':    1089 obs. of  9 variables:
##  $ Year     : num  1990 1990 1990 1990 1990 1990 1990 1990 1990 1990 ...
##  $ Lag1     : num  0.816 -0.27 -2.576 3.514 0.712 ...
##  $ Lag2     : num  1.572 0.816 -0.27 -2.576 3.514 ...
##  $ Lag3     : num  -3.936 1.572 0.816 -0.27 -2.576 ...
##  $ Lag4     : num  -0.229 -3.936 1.572 0.816 -0.27 ...
##  $ Lag5     : num  -3.484 -0.229 -3.936 1.572 0.816 ...
##  $ Volume   : num  0.155 0.149 0.16 0.162 0.154 ...
##  $ Today    : num  -0.27 -2.576 3.514 0.712 1.178 ...
##  $ Direction: Factor w/ 2 levels "Down","Up": 1 1 2 2 2 1 2 2 2 1 ...
summary(Weekly)
##       Year           Lag1               Lag2               Lag3         
##  Min.   :1990   Min.   :-18.1950   Min.   :-18.1950   Min.   :-18.1950  
##  1st Qu.:1995   1st Qu.: -1.1540   1st Qu.: -1.1540   1st Qu.: -1.1580  
##  Median :2000   Median :  0.2410   Median :  0.2410   Median :  0.2410  
##  Mean   :2000   Mean   :  0.1506   Mean   :  0.1511   Mean   :  0.1472  
##  3rd Qu.:2005   3rd Qu.:  1.4050   3rd Qu.:  1.4090   3rd Qu.:  1.4090  
##  Max.   :2010   Max.   : 12.0260   Max.   : 12.0260   Max.   : 12.0260  
##       Lag4               Lag5              Volume            Today         
##  Min.   :-18.1950   Min.   :-18.1950   Min.   :0.08747   Min.   :-18.1950  
##  1st Qu.: -1.1580   1st Qu.: -1.1660   1st Qu.:0.33202   1st Qu.: -1.1540  
##  Median :  0.2380   Median :  0.2340   Median :1.00268   Median :  0.2410  
##  Mean   :  0.1458   Mean   :  0.1399   Mean   :1.57462   Mean   :  0.1499  
##  3rd Qu.:  1.4090   3rd Qu.:  1.4050   3rd Qu.:2.05373   3rd Qu.:  1.4050  
##  Max.   : 12.0260   Max.   : 12.0260   Max.   :9.32821   Max.   : 12.0260  
##  Direction 
##  Down:484  
##  Up  :605  
##            
##            
##            
## 
cor(Weekly[ ,-9])
##               Year         Lag1        Lag2        Lag3         Lag4
## Year    1.00000000 -0.032289274 -0.03339001 -0.03000649 -0.031127923
## Lag1   -0.03228927  1.000000000 -0.07485305  0.05863568 -0.071273876
## Lag2   -0.03339001 -0.074853051  1.00000000 -0.07572091  0.058381535
## Lag3   -0.03000649  0.058635682 -0.07572091  1.00000000 -0.075395865
## Lag4   -0.03112792 -0.071273876  0.05838153 -0.07539587  1.000000000
## Lag5   -0.03051910 -0.008183096 -0.07249948  0.06065717 -0.075675027
## Volume  0.84194162 -0.064951313 -0.08551314 -0.06928771 -0.061074617
## Today  -0.03245989 -0.075031842  0.05916672 -0.07124364 -0.007825873
##                Lag5      Volume        Today
## Year   -0.030519101  0.84194162 -0.032459894
## Lag1   -0.008183096 -0.06495131 -0.075031842
## Lag2   -0.072499482 -0.08551314  0.059166717
## Lag3    0.060657175 -0.06928771 -0.071243639
## Lag4   -0.075675027 -0.06107462 -0.007825873
## Lag5    1.000000000 -0.05851741  0.011012698
## Volume -0.058517414  1.00000000 -0.033077783
## Today   0.011012698 -0.03307778  1.000000000
anyNA(Weekly)
## [1] FALSE
plot(Weekly)

multi.hist(Weekly[,2:8])

There is no missing data and all numeric entries are normal except volume, which is right skewed. Also Volume appears to be correlated to the year resulting in a logarithmic function between the the two.

(b) Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary() function to print the results. Do any of the predictors appear to be statistically significant? If so,which ones?

glm.weekly.fit = glm(Direction ~ . - Year - Today, data = Weekly, family = binomial)
summary(glm.weekly.fit)
## 
## Call:
## glm(formula = Direction ~ . - Year - Today, family = binomial, 
##     data = Weekly)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6949  -1.2565   0.9913   1.0849   1.4579  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.26686    0.08593   3.106   0.0019 **
## Lag1        -0.04127    0.02641  -1.563   0.1181   
## Lag2         0.05844    0.02686   2.175   0.0296 * 
## Lag3        -0.01606    0.02666  -0.602   0.5469   
## Lag4        -0.02779    0.02646  -1.050   0.2937   
## Lag5        -0.01447    0.02638  -0.549   0.5833   
## Volume      -0.02274    0.03690  -0.616   0.5377   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1486.4  on 1082  degrees of freedom
## AIC: 1500.4
## 
## Number of Fisher Scoring iterations: 4

The only statistically significant predictor in this set is lag2, with a p-value of .0296, which is less than the .05 cut off.

(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.weekly.fit, type = "response")
glm.preds = rep("Down", length(glm.probs)) 
glm.preds[glm.probs > 0.5] = "Up"

table(glm.preds, Weekly$Direction)
##          
## glm.preds Down  Up
##      Down   54  48
##      Up    430 557
mean(glm.preds == Weekly$Direction) #accuracy
## [1] 0.5610652
557/(557+430) #precision
## [1] 0.5643364
557/(557+48) #recall
## [1] 0.9206612
54/(54+430) #false positive rate
## [1] 0.1115702

The confusion matrix shows that we have an accuracy score of .5610652, meaning that the logistic regression is correct 56.11% of the time. This only a slight improvement over random guessing. The model is very precise when it comes to predicting Up with a Recall score of 92.07%. When it comes to properly classifying Down though, the model is only correct 11.16% of the time. Also the Precision score is .5643364 which means that out of all the Up predictions, about 56.43% were correct.

(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.weekly.train = glm(Direction~Lag2, data=Weekly,family=binomial, subset=train)
summary(glm.weekly.train)
## 
## Call:
## glm(formula = Direction ~ Lag2, family = binomial, data = Weekly, 
##     subset = train)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.536  -1.264   1.021   1.091   1.368  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.20326    0.06428   3.162  0.00157 **
## Lag2         0.05810    0.02870   2.024  0.04298 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1354.7  on 984  degrees of freedom
## Residual deviance: 1350.5  on 983  degrees of freedom
## AIC: 1354.5
## 
## Number of Fisher Scoring iterations: 4
glm.probsd = predict(glm.weekly.train, weekly.test, type = "response")
glm.predsd = rep("Down", length(glm.probsd)) 
glm.predsd[glm.probsd > 0.5] = "Up"

table(glm.predsd, weekly.test$Direction)
##           
## glm.predsd Down Up
##       Down    9  5
##       Up     34 56
mean(glm.predsd == weekly.test$Direction) #accuracy
## [1] 0.625

The model has a 62.5% accuracy score, meaning that using lag 2 as the sole predictor of Direction and then training it on a large portion of the data nets this score for the test section of the data. This is another small improvement over the previous model and better than random guessing.

(e) Repeat (d) using LDA.

direction.test = Direction[!train]

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

lda.pred = predict(lda.weekly.fit, weekly.test)

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

The LDA model returns results that match those from the logistic model of part (d).

(f) Repeat (d) using QDA.

qda.weekly.fit = qda(Direction~Lag2, data=Weekly, subset=train)
qda.weekly.fit
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
qda.pred = predict(qda.weekly.fit, weekly.test)

qda.class=qda.pred$class
table(qda.class, direction.test)
##          direction.test
## qda.class Down Up
##      Down    0  0
##      Up     43 61
mean(qda.class==direction.test)
## [1] 0.5865385

The model’s accuracy has decrease from the .625 of LDA and logistic regression to only .5865385. Also the model only predicted up in its results, similar to random guessing.

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

train.lag2 = as.matrix(Lag2[train])
test.lag2 = as.matrix(Lag2[!train])
direction.train = Direction[train]

dim(train.lag2)
## [1] 985   1
dim(test.lag2)
## [1] 104   1
set.seed(1)

knn.pred=knn(train.lag2, test.lag2, direction.train, k=1)
table(knn.pred,direction.test)
##         direction.test
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred == direction.test)
## [1] 0.5

The model results in a 50% accuracy score, meaning that model acts like random guessing.

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

Logistic Regression and LDA as they both have 62.5% model accuracy for this scenario.

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

#Interaction of lag1 and lag2 with all terms
glm.weekly.int <-glm(Direction~. - Today -Year + Lag1:Lag2, data=Weekly,family=binomial, subset=train)
summary(glm.weekly.int)
## 
## Call:
## glm(formula = Direction ~ . - Today - Year + Lag1:Lag2, family = binomial, 
##     data = Weekly, subset = train)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.650  -1.249   0.977   1.084   1.567  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  0.334016   0.094312   3.542 0.000398 ***
## Lag1        -0.057932   0.031247  -1.854 0.063736 .  
## Lag2         0.044264   0.029978   1.477 0.139802    
## Lag3        -0.016404   0.029600  -0.554 0.579463    
## Lag4        -0.032939   0.029582  -1.113 0.265496    
## Lag5        -0.037754   0.029246  -1.291 0.196729    
## Volume      -0.090234   0.054202  -1.665 0.095960 .  
## Lag1:Lag2    0.003122   0.007615   0.410 0.681791    
## ---
## 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: 1342.2  on 977  degrees of freedom
## AIC: 1358.2
## 
## Number of Fisher Scoring iterations: 4
glm.probsi = predict(glm.weekly.train, weekly.test, type = "response")
glm.predsi = rep("Down", length(glm.probsi)) 
glm.predsi[glm.probsi > 0.5] = "Up"

table(glm.predsi, weekly.test$Direction)
##           
## glm.predsi Down Up
##       Down    9  5
##       Up     34 56
mean(glm.predsi == weekly.test$Direction) #accuracy
## [1] 0.625

This model returns the same accuracy score as the best models from before, but also none of the terms are significant within a .05 margin. Lag2 and Volume come close if we were using a .10 cutoff they would be significant.

glm.weekly.int <-glm(Direction~. - Today -Year - Volume + log(Volume), data=Weekly,family=binomial, subset=train)
summary(glm.weekly.int)
## 
## Call:
## glm(formula = Direction ~ . - Today - Year - Volume + log(Volume), 
##     family = binomial, data = Weekly, subset = train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.7794  -1.2475   0.9776   1.0881   1.5187  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.19325    0.06731   2.871  0.00409 **
## Lag1        -0.05918    0.02913  -2.031  0.04222 * 
## Lag2         0.04837    0.02950   1.639  0.10111   
## Lag3        -0.01267    0.02931  -0.432  0.66547   
## Lag4        -0.02827    0.02903  -0.974  0.33011   
## Lag5        -0.03497    0.02907  -1.203  0.22889   
## log(Volume) -0.10227    0.06593  -1.551  0.12084   
## ---
## 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: 1342.7  on 978  degrees of freedom
## AIC: 1356.7
## 
## Number of Fisher Scoring iterations: 4
glm.probsi = predict(glm.weekly.train, weekly.test, type = "response")
glm.predsi = rep("Down", length(glm.probsi)) 
glm.predsi[glm.probsi > 0.5] = "Up"

table(glm.predsi, weekly.test$Direction)
##           
## glm.predsi Down Up
##       Down    9  5
##       Up     34 56
mean(glm.predsi == weekly.test$Direction) #accuracy
## [1] 0.625

This model uses a log transformation on the Volume variable in hopes of correcting the right skew. In this case, the transformed variable is still not significant, but the significant variable is now Lag1. Also the model predicts with the same accuracy as the other best performing models.

direction.test = Direction[!train]

lda.weekly.fit = lda(Direction~. - Today -Year - Volume + log(Volume), data=Weekly, subset=train)
plot(lda.weekly.fit)

lda.pred = predict(lda.weekly.fit, weekly.test)

lda.class=lda.pred$class
table(lda.class, direction.test)
##          direction.test
## lda.class Down Up
##      Down   23 30
##      Up     20 31
mean(lda.class==direction.test)
## [1] 0.5192308

Using the transformation on the LDA model does not result in a better accuracy, most likely because the transformed variable still has no significant effect on the data.

train.lag2 = as.matrix(Lag2[train])
test.lag2 = as.matrix(Lag2[!train])
direction.train = Direction[train]

dim(train.lag2)
## [1] 985   1
dim(test.lag2)
## [1] 104   1
set.seed(1)

knn.pred=knn(train.lag2, test.lag2, direction.train, k=4)
table(knn.pred,direction.test)
##         direction.test
## knn.pred Down Up
##     Down   20 17
##     Up     23 44
mean(knn.pred == direction.test)
## [1] 0.6153846

Using the KNN method, this time with k=4 returns a result of .6153846 model accuracy, which is very close to the best performing models. Also its no longer only predicting Up.

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.

detach(Weekly)
attach(Auto)
## The following object is masked from package:ggplot2:
## 
##     mpg
summary(Auto)
##       mpg          cylinders      displacement     horsepower        weight    
##  Min.   : 9.00   Min.   :3.000   Min.   : 68.0   Min.   : 46.0   Min.   :1613  
##  1st Qu.:17.00   1st Qu.:4.000   1st Qu.:105.0   1st Qu.: 75.0   1st Qu.:2225  
##  Median :22.75   Median :4.000   Median :151.0   Median : 93.5   Median :2804  
##  Mean   :23.45   Mean   :5.472   Mean   :194.4   Mean   :104.5   Mean   :2978  
##  3rd Qu.:29.00   3rd Qu.:8.000   3rd Qu.:275.8   3rd Qu.:126.0   3rd Qu.:3615  
##  Max.   :46.60   Max.   :8.000   Max.   :455.0   Max.   :230.0   Max.   :5140  
##                                                                                
##   acceleration        year           origin                      name    
##  Min.   : 8.00   Min.   :70.00   Min.   :1.000   amc matador       :  5  
##  1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000   ford pinto        :  5  
##  Median :15.50   Median :76.00   Median :1.000   toyota corolla    :  5  
##  Mean   :15.54   Mean   :75.98   Mean   :1.577   amc gremlin       :  4  
##  3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000   amc hornet        :  4  
##  Max.   :24.80   Max.   :82.00   Max.   :3.000   chevrolet chevette:  4  
##                                                  (Other)           :365

(a) Create a binary variable, mpg01, that contains a 1 if mpg contains a value above its median, and a 0 if mpg contains a value below its median. You can compute the median using the median() function. Note you may find it helpful to use the data.frame() function to create a single data set containing both mpg01 and the other Auto variables.

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

(b) Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question.Describe your findings.

library(corrplot)
## Warning: package 'corrplot' was built under R version 4.0.3
## corrplot 0.84 loaded
corrplot(cor(Auto[,-9]), method="square")

multi.hist(Auto[c(1,3:6)])

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

Using Correlation plot, we can see that cylinders, displacement, horsepower, and weight are all strongly negatively correlated with mpg01, while origin seems to have a moderate positive correlation with mpg01.

Also, the numeric data distributions appear skewed to the right, with the exception of acceleration which has a normal bell shaped curved.

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

train = (Auto$year %% 2 == 0)
train.auto = Auto[train,]
test.auto = Auto[!train,]

(d) Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained?

lda.auto.fit = lda(mpg01~displacement+horsepower+weight+cylinders+origin, data=train.auto)
lda.pred = predict(lda.auto.fit, test.auto)
table(lda.pred$class, test.auto$mpg01)
##    
##      0  1
##   0 86 11
##   1 14 71
mean(lda.pred$class == test.auto$mpg01)
## [1] 0.8626374
1 - mean(lda.pred$class == test.auto$mpg01)
## [1] 0.1373626

The test error of the LDA model is 0.1373626.

(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.auto.fit = qda(mpg01~displacement+horsepower+weight+cylinders+origin, data=train.auto)

qda.auto.fit
## Call:
## qda(mpg01 ~ displacement + horsepower + weight + cylinders + 
##     origin, data = train.auto)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4571429 0.5428571 
## 
## Group means:
##   displacement horsepower   weight cylinders   origin
## 0     271.7396  133.14583 3604.823  6.812500 1.166667
## 1     111.6623   77.92105 2314.763  4.070175 2.035088
qda.pred = predict(qda.auto.fit, test.auto)

qda.class=qda.pred$class
table(qda.class, test.auto$mpg01)
##          
## qda.class  0  1
##         0 88 13
##         1 12 69
mean(qda.class==test.auto$mpg01)
## [1] 0.8626374
1 - mean(qda.class==test.auto$mpg01)
## [1] 0.1373626

The test error of the QDA model is 0.1373626.

(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.auto.fit = glm(mpg01~displacement+horsepower+weight+cylinders+origin, data=train.auto, family=binomial)

glm.probs = predict(glm.auto.fit, test.auto, type = "response")
glm.preds = rep(0, length(glm.probs)) 
glm.preds[glm.probs > 0.5] = 1

table(glm.preds, test.auto$mpg01)
##          
## glm.preds  0  1
##         0 89 11
##         1 11 71
mean(glm.preds == test.auto$mpg01) #accuracy
## [1] 0.8791209
1 - mean(glm.preds == test.auto$mpg01)
## [1] 0.1208791

The test error of the logistic regression model is 0.1208791.

(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.X = cbind(displacement,horsepower, weight, cylinders, origin)[train,]
test.X = cbind(displacement,horsepower, weight, cylinders, origin)[!train,]
train.mpg01 = mpg01[train]
test.mpg01 = mpg01[!train]

set.seed(1)

knn.pred=knn(train.X, test.X, train.mpg01, k=1)
table(knn.pred,test.mpg01)
##         test.mpg01
## knn.pred  0  1
##        0 83 11
##        1 17 71
1 - mean(knn.pred == test.mpg01)
## [1] 0.1538462
knn.pred=knn(train.X, test.X, train.mpg01, k=3)
table(knn.pred,test.mpg01)
##         test.mpg01
## knn.pred  0  1
##        0 84  9
##        1 16 73
1 - mean(knn.pred == test.mpg01)
## [1] 0.1373626
knn.pred=knn(train.X, test.X, train.mpg01, k=5)
table(knn.pred,test.mpg01)
##         test.mpg01
## knn.pred  0  1
##        0 82  9
##        1 18 73
1 - mean(knn.pred == test.mpg01)
## [1] 0.1483516
knn.pred=knn(train.X, test.X, train.mpg01, k=10)
table(knn.pred,test.mpg01)
##         test.mpg01
## knn.pred  0  1
##        0 79  7
##        1 21 75
1 - mean(knn.pred == test.mpg01)
## [1] 0.1538462

After testing out the K Nearest Neighbors method on different fold sizes (1,3,5 and 10), 3 performed the best with an error rate of 0.1373626. Also K=1 and K=10 had the same error rate for this model.

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

detach(Auto)
attach(Boston)
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
crim01 = rep(0, length(crim))
crim01[crim > median(crim)] = 1
Boston = data.frame(Boston, crim01)
corrplot(cor(Boston), method="square")

multi.hist(Boston[c(1:3, 5:14)])

cor(Boston)
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
## crim01   0.40939545 -0.43615103  0.60326017  0.070096774  0.72323480
##                  rm         age         dis          rad         tax    ptratio
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431  0.2899456
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332 -0.3916785
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018  0.3832476
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652 -0.1215152
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320  0.1889327
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783 -0.3555015
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559  0.2615150
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158 -0.2324705
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819  0.4647412
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000  0.4608530
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304  1.0000000
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801 -0.1773833
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341  0.3740443
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593 -0.5077867
## crim01  -0.15637178  0.61393992 -0.61634164  0.619786249  0.60874128  0.2535684
##               black      lstat       medv      crim01
## crim    -0.38506394  0.4556215 -0.3883046  0.40939545
## zn       0.17552032 -0.4129946  0.3604453 -0.43615103
## indus   -0.35697654  0.6037997 -0.4837252  0.60326017
## chas     0.04878848 -0.0539293  0.1752602  0.07009677
## nox     -0.38005064  0.5908789 -0.4273208  0.72323480
## rm       0.12806864 -0.6138083  0.6953599 -0.15637178
## age     -0.27353398  0.6023385 -0.3769546  0.61393992
## dis      0.29151167 -0.4969958  0.2499287 -0.61634164
## rad     -0.44441282  0.4886763 -0.3816262  0.61978625
## tax     -0.44180801  0.5439934 -0.4685359  0.60874128
## ptratio -0.17738330  0.3740443 -0.5077867  0.25356836
## black    1.00000000 -0.3660869  0.3334608 -0.35121093
## lstat   -0.36608690  1.0000000 -0.7376627  0.45326273
## medv     0.33346082 -0.7376627  1.0000000 -0.26301673
## crim01  -0.35121093  0.4532627 -0.2630167  1.00000000

Note that indus, nox, age, rad,and tax are all positively correlated with crim01 as well as dis being negatively correlated with crim01.

train = 1:(length(Boston$crim)[1]/2)
test = (length(Boston$crim)[1]/2 + 1):length(Boston$crim)[1]
train.Boston = Boston[train, ]
test.Boston = Boston[test, ]
crim01.test = crim01[test]
crim01.train = crim01[train]
glm.Boston.fit = glm(crim01~ indus+nox+age+dis+rad+tax, data=train.Boston,family=binomial)
summary(glm.Boston.fit)
## 
## Call:
## glm(formula = crim01 ~ indus + nox + age + dis + rad + tax, family = binomial, 
##     data = train.Boston)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -1.97810  -0.21406  -0.03454   0.47107   3.04502  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -42.214032   7.617440  -5.542 2.99e-08 ***
## indus        -0.213126   0.073236  -2.910  0.00361 ** 
## nox          80.868029  16.066473   5.033 4.82e-07 ***
## age           0.003397   0.012032   0.282  0.77772    
## dis           0.307145   0.190502   1.612  0.10690    
## rad           0.847236   0.183767   4.610 4.02e-06 ***
## tax          -0.013760   0.004956  -2.777  0.00549 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 329.37  on 252  degrees of freedom
## Residual deviance: 144.44  on 246  degrees of freedom
## AIC: 158.44
## 
## Number of Fisher Scoring iterations: 8
glm.probs = predict(glm.Boston.fit, test.Boston, type = "response")
glm.preds = rep(0, length(glm.probs))
glm.preds[glm.probs > 0.5] = 1
table(glm.preds, crim01.test)
##          crim01.test
## glm.preds   0   1
##         0  75   8
##         1  15 155
1 - mean(glm.preds == crim01.test)
## [1] 0.09090909
lda.Boston.fit <-lda(crim01~ indus+nox+age+dis+rad+tax, data=train.Boston, family=binomial)
lda.preds = predict(lda.Boston.fit, test.Boston)
lda.class=lda.preds$class
table(lda.class, crim01.test)
##          crim01.test
## lda.class   0   1
##         0  81  18
##         1   9 145
1 - mean(lda.class == crim01.test)
## [1] 0.1067194
qda.Boston.fit = qda(crim01~ indus+nox+age+dis+rad+tax, data=train.Boston)
qda.Boston.fit
## Call:
## qda(crim01 ~ indus + nox + age + dis + rad + tax, data = train.Boston)
## 
## Prior probabilities of groups:
##         0         1 
## 0.6442688 0.3557312 
## 
## Group means:
##       indus       nox      age      dis      rad      tax
## 0  7.042454 0.4702902 54.68957 4.843857 4.239264 300.4417
## 1 13.959778 0.6119889 85.67889 2.895154 5.155556 358.0111
qda.preds = predict(qda.Boston.fit, train.Boston)

qda.class=qda.preds$class
table(qda.class, crim01.test)
##          crim01.test
## qda.class  0  1
##         0 71 99
##         1 19 64
1 - mean(qda.class==crim01.test)
## [1] 0.4664032
train.X = cbind(indus,nox,age,dis,rad,tax)[train,]
test.X = cbind(indus,nox,age,dis,rad,tax)[test,]

set.seed(1)

knn.pred=knn(train.X, test.X, crim01.train, k=1)
table(knn.pred,crim01.test)
##         crim01.test
## knn.pred   0   1
##        0  82 151
##        1   8  12
1 - mean(knn.pred == crim01.test)
## [1] 0.6284585
knn.pred=knn(train.X, test.X, crim01.train, k=5)
table(knn.pred,crim01.test)
##         crim01.test
## knn.pred   0   1
##        0  80  22
##        1  10 141
1 - mean(knn.pred == crim01.test)
## [1] 0.1264822
knn.pred=knn(train.X, test.X, crim01.train, k=10)
table(knn.pred,crim01.test)
##         crim01.test
## knn.pred   0   1
##        0  83  23
##        1   7 140
1 - mean(knn.pred == crim01.test)
## [1] 0.1185771

4 methods of modeling were used to classify if where the data had a higher or lower crime rate than the median crime rate in Boston suburbs. Using Logistic Regression, LDA, QDA, and K Nearest Neighbors, the best model came from the implementation of the logistic regression. It had a mean error rate of 0.09090909. The worst model was the QDA (0.4664032 mean error rate) and KNN with k=1 (0.6284585 mean error rate). When the amount of folds for the KNN was increased to 10, the model performed a much better (0.1185771), almost on par with the second best model, LDA (0.1067194).