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.

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

summary(Weekly)
##       Year           Lag1               Lag2               Lag3         
##  Min.   :1990   Min.   :-18.1950   Min.   :-18.1950   Min.   :-18.1950  
##  1st Qu.:1995   1st Qu.: -1.1540   1st Qu.: -1.1540   1st Qu.: -1.1580  
##  Median :2000   Median :  0.2410   Median :  0.2410   Median :  0.2410  
##  Mean   :2000   Mean   :  0.1506   Mean   :  0.1511   Mean   :  0.1472  
##  3rd Qu.:2005   3rd Qu.:  1.4050   3rd Qu.:  1.4090   3rd Qu.:  1.4090  
##  Max.   :2010   Max.   : 12.0260   Max.   : 12.0260   Max.   : 12.0260  
##       Lag4               Lag5              Volume            Today         
##  Min.   :-18.1950   Min.   :-18.1950   Min.   :0.08747   Min.   :-18.1950  
##  1st Qu.: -1.1580   1st Qu.: -1.1660   1st Qu.:0.33202   1st Qu.: -1.1540  
##  Median :  0.2380   Median :  0.2340   Median :1.00268   Median :  0.2410  
##  Mean   :  0.1458   Mean   :  0.1399   Mean   :1.57462   Mean   :  0.1499  
##  3rd Qu.:  1.4090   3rd Qu.:  1.4050   3rd Qu.:2.05373   3rd Qu.:  1.4050  
##  Max.   : 12.0260   Max.   : 12.0260   Max.   :9.32821   Max.   : 12.0260  
##  Direction 
##  Down:484  
##  Up  :605  
##            
##            
##            
## 
pairs(Weekly)

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

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

Based on the p-value, only Lag 2 appears to be significant in the model.

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

Weekly$prob = predict(m1, type = "response")
Weekly$pred = ifelse(Weekly$prob > 0.5,"Up","Down")
caret::confusionMatrix(as.factor(Weekly$pred),as.factor(Weekly$Direction))
## 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.11157        
##             Specificity : 0.92066        
##          Pos Pred Value : 0.52941        
##          Neg Pred Value : 0.56434        
##              Prevalence : 0.44444        
##          Detection Rate : 0.04959        
##    Detection Prevalence : 0.09366        
##       Balanced Accuracy : 0.51612        
##                                          
##        'Positive' Class : Down           
## 

If we use 0.5 as cut-off, the logistic regression performs very poorly since it classifies 90% of weeks as “Up”. This results in a unacceptable sensitivity score (about 11%) and low accuracy overall (55.5%).

(d) Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010).

train= Weekly[Weekly$Year <2008,]
test = Weekly[Weekly$Year >=2008,]
m1 = glm(Direction ~ Lag2, data = train, family = "binomial")
test$prob = predict(m1, newdata = test, type = "response")
test$pred = ifelse(test$prob > 0.5,"Up","Down")
caret::confusionMatrix(as.factor(test$pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    7  5
##       Up     65 79
##                                           
##                Accuracy : 0.5513          
##                  95% CI : (0.4697, 0.6309)
##     No Information Rate : 0.5385          
##     P-Value [Acc > NIR] : 0.4056          
##                                           
##                   Kappa : 0.0401          
##                                           
##  Mcnemar's Test P-Value : 1.766e-12       
##                                           
##             Sensitivity : 0.09722         
##             Specificity : 0.94048         
##          Pos Pred Value : 0.58333         
##          Neg Pred Value : 0.54861         
##              Prevalence : 0.46154         
##          Detection Rate : 0.04487         
##    Detection Prevalence : 0.07692         
##       Balanced Accuracy : 0.51885         
##                                           
##        'Positive' Class : Down            
## 
plot(test$prob, col= ifelse(Weekly$Direction=="Down", "red","green"), pch=16)
abline(h = 0.5, lwd= 3)

(e) Repeat (d) using LDA.

m2 = lda(Direction ~ Lag2, data = train)
test$prob = predict(m2, newdata = test, type = "response")
test$pred = test$prob$class
caret::confusionMatrix(as.factor(test$pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    6  5
##       Up     66 79
##                                           
##                Accuracy : 0.5449          
##                  95% CI : (0.4633, 0.6247)
##     No Information Rate : 0.5385          
##     P-Value [Acc > NIR] : 0.4688          
##                                           
##                   Kappa : 0.0253          
##                                           
##  Mcnemar's Test P-Value : 1.074e-12       
##                                           
##             Sensitivity : 0.08333         
##             Specificity : 0.94048         
##          Pos Pred Value : 0.54545         
##          Neg Pred Value : 0.54483         
##              Prevalence : 0.46154         
##          Detection Rate : 0.03846         
##    Detection Prevalence : 0.07051         
##       Balanced Accuracy : 0.51190         
##                                           
##        'Positive' Class : Down            
## 

(f) Repeat (d) using QDA.

m3 = qda(Direction ~ Lag2, data = train)
test$prob = predict(m3, newdata = test, type = "response")
test$pred = test$prob$class
caret::confusionMatrix(as.factor(test$pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    0  0
##       Up     72 84
##                                           
##                Accuracy : 0.5385          
##                  95% CI : (0.4569, 0.6185)
##     No Information Rate : 0.5385          
##     P-Value [Acc > NIR] : 0.5328          
##                                           
##                   Kappa : 0               
##                                           
##  Mcnemar's Test P-Value : <2e-16          
##                                           
##             Sensitivity : 0.0000          
##             Specificity : 1.0000          
##          Pos Pred Value :    NaN          
##          Neg Pred Value : 0.5385          
##              Prevalence : 0.4615          
##          Detection Rate : 0.0000          
##    Detection Prevalence : 0.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : Down            
## 

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

set.seed(2)
train.X=cbind(train$Lag2) #predictor matrix for train 
test.X=cbind(test$Lag2) #predictor matrix for test
train.Y = train$Direction #labels
knn.pred = knn(train.X,test.X,train.Y, k=1)
caret::confusionMatrix(as.factor(knn.pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   32 38
##       Up     40 46
##                                         
##                Accuracy : 0.5           
##                  95% CI : (0.419, 0.581)
##     No Information Rate : 0.5385        
##     P-Value [Acc > NIR] : 0.8517        
##                                         
##                   Kappa : -0.008        
##                                         
##  Mcnemar's Test P-Value : 0.9099        
##                                         
##             Sensitivity : 0.4444        
##             Specificity : 0.5476        
##          Pos Pred Value : 0.4571        
##          Neg Pred Value : 0.5349        
##              Prevalence : 0.4615        
##          Detection Rate : 0.2051        
##    Detection Prevalence : 0.4487        
##       Balanced Accuracy : 0.4960        
##                                         
##        'Positive' Class : Down          
## 

(h) Which of these methods appears to provide the best results on this data?
While the logistic model has the best accuracy overall (56.11 %), KNN has the best balance between sensitivity and specificity.
(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.

m2 = glm(Direction ~ Lag2+ Lag2*Lag3, data = train, family =  "binomial")
test$prob = predict(m2, newdata = test, type = "response")
test$pred = ifelse(test$prob > 0.5,"Up","Down")
caret::confusionMatrix(as.factor(test$pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    7  6
##       Up     65 78
##                                           
##                Accuracy : 0.5449          
##                  95% CI : (0.4633, 0.6247)
##     No Information Rate : 0.5385          
##     P-Value [Acc > NIR] : 0.4688          
##                                           
##                   Kappa : 0.0274          
##                                           
##  Mcnemar's Test P-Value : 5.847e-12       
##                                           
##             Sensitivity : 0.09722         
##             Specificity : 0.92857         
##          Pos Pred Value : 0.53846         
##          Neg Pred Value : 0.54545         
##              Prevalence : 0.46154         
##          Detection Rate : 0.04487         
##    Detection Prevalence : 0.08333         
##       Balanced Accuracy : 0.51290         
##                                           
##        'Positive' Class : Down            
## 
m2 = lda(Direction ~ log(Lag2), data = train)
test$prob = predict(m2, newdata = test, type = "response")
test$pred = test$prob$class
caret::confusionMatrix(as.factor(test$pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    4  7
##       Up     30 41
##                                          
##                Accuracy : 0.5488         
##                  95% CI : (0.4349, 0.659)
##     No Information Rate : 0.5854         
##     P-Value [Acc > NIR] : 0.7842774      
##                                          
##                   Kappa : -0.0313        
##                                          
##  Mcnemar's Test P-Value : 0.0002983      
##                                          
##             Sensitivity : 0.11765        
##             Specificity : 0.85417        
##          Pos Pred Value : 0.36364        
##          Neg Pred Value : 0.57746        
##              Prevalence : 0.41463        
##          Detection Rate : 0.04878        
##    Detection Prevalence : 0.13415        
##       Balanced Accuracy : 0.48591        
##                                          
##        'Positive' Class : Down           
## 
m3 = qda(Direction ~ sqrt(Lag2), data = train)
test$prob = predict(m3, newdata = test, type = "response")
test$pred = test$prob$class
caret::confusionMatrix(as.factor(test$pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down    0  0
##       Up     34 48
##                                           
##                Accuracy : 0.5854          
##                  95% CI : (0.4712, 0.6932)
##     No Information Rate : 0.5854          
##     P-Value [Acc > NIR] : 0.5471          
##                                           
##                   Kappa : 0               
##                                           
##  Mcnemar's Test P-Value : 1.519e-08       
##                                           
##             Sensitivity : 0.0000          
##             Specificity : 1.0000          
##          Pos Pred Value :    NaN          
##          Neg Pred Value : 0.5854          
##              Prevalence : 0.4146          
##          Detection Rate : 0.0000          
##    Detection Prevalence : 0.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : Down            
## 
knn.pred = knn(train.X,test.X,train.Y, k=20)
caret::confusionMatrix(as.factor(knn.pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   32 25
##       Up     40 59
##                                           
##                Accuracy : 0.5833          
##                  95% CI : (0.5018, 0.6616)
##     No Information Rate : 0.5385          
##     P-Value [Acc > NIR] : 0.14821         
##                                           
##                   Kappa : 0.149           
##                                           
##  Mcnemar's Test P-Value : 0.08248         
##                                           
##             Sensitivity : 0.4444          
##             Specificity : 0.7024          
##          Pos Pred Value : 0.5614          
##          Neg Pred Value : 0.5960          
##              Prevalence : 0.4615          
##          Detection Rate : 0.2051          
##    Detection Prevalence : 0.3654          
##       Balanced Accuracy : 0.5734          
##                                           
##        'Positive' Class : Down            
## 
knn.pred = knn(train.X,test.X,train.Y, k=10)
caret::confusionMatrix(as.factor(knn.pred),as.factor(test$Direction))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down Up
##       Down   30 29
##       Up     42 55
##                                           
##                Accuracy : 0.5449          
##                  95% CI : (0.4633, 0.6247)
##     No Information Rate : 0.5385          
##     P-Value [Acc > NIR] : 0.4688          
##                                           
##                   Kappa : 0.0724          
##                                           
##  Mcnemar's Test P-Value : 0.1544          
##                                           
##             Sensitivity : 0.4167          
##             Specificity : 0.6548          
##          Pos Pred Value : 0.5085          
##          Neg Pred Value : 0.5670          
##              Prevalence : 0.4615          
##          Detection Rate : 0.1923          
##    Detection Prevalence : 0.3782          
##       Balanced Accuracy : 0.5357          
##                                           
##        'Positive' Class : Down            
## 

The KNN model with K=20 produced the best results overall: accuracy (60.9%), sensitivity (48.61%), specificity (71.43%)

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

Auto=na.omit(Auto)
median.mpg =median(Auto$mpg)
Auto$mpg01 = ifelse(Auto$mpg > median.mpg, 1, 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.

Auto1 = select_if(Auto, is.numeric)
cor(Auto1)
##                     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,2))
plot(Auto$year, Auto$acceleration, col= ifelse(Auto$mpg01==0, "red", "green"), pch = 16)
plot(Auto$year, Auto$weight, col= ifelse(Auto$mpg01==0, "red", "green"), pch = 16)
plot(Auto$year, Auto$horsepower, col= ifelse(Auto$mpg01==0, "red", "green"), pch = 16)
plot(Auto$year, Auto$displacement, col= ifelse(Auto$mpg01==0, "red", "green"), pch = 16)

Auto$mpg01 = as.factor(Auto$mpg01)
plot(Auto$mpg01, Auto$displacement)
plot(Auto$mpg01, Auto$cylinders)
plot(Auto$mpg01, Auto$horsepower)
plot(Auto$mpg01, Auto$weight)

Based on the plots, it looks like horsepower, displacement, acceleration, and weight can separate the two classes of mpg01 fairly well. (c) Split the data into a training set and a test set.

split<- sample(c(rep(0, 0.8 * nrow(Auto)), rep(1, 0.2 * nrow(Auto))))
train <- Auto[split == 0, ] # 314 obs.
test <- Auto[split == 1, ]  # 78 obs.

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

m1 = lda(mpg01 ~ weight+displacement+acceleration+horsepower, data = train)
test$prob = predict(m1, newdata = test, type = "response")
table(test$mpg01,test$prob$class)
##    
##      0  1
##   0 31  7
##   1  1 39
1- mean(test$prob$class == test$mpg01)
## [1] 0.1025641

The test error of the LDA model is 16.66667%.

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

m1 = qda(mpg01 ~ weight+displacement+acceleration+horsepower, data = train)
test$prob = predict(m1, newdata = test, type = "response")
table(test$mpg01,test$prob$class)
##    
##      0  1
##   0 32  6
##   1  2 38
1- mean(test$prob$class == test$mpg01)
## [1] 0.1025641

The test error of the QDA model is 10.25641$.
(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?

m1 = glm(mpg01 ~ weight+displacement+acceleration+horsepower, data = train, family = "binomial")
test$prob = predict(m1, newdata = test, type = "response")
test$pred = ifelse(test$prob > 0.5, 1,0)
table(test$mpg01,test$pred)
##    
##      0  1
##   0 32  6
##   1  4 36
1- mean(test$pred == test$mpg01)
## [1] 0.1282051

The test error of the logistic regression model is 11.53846$.
(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(train$weight,train$displacement,train$acceleration,train$horsepower)
test.X=cbind(test$weight,test$displacement,test$acceleration,test$horsepower) 
train.Y = train$mpg01
knn.pred = knn(train.X,test.X,train.Y, k=1)
table(test$mpg01,knn.pred)
##    knn.pred
##      0  1
##   0 34  4
##   1  4 36
1- mean(knn.pred == test$mpg01)
## [1] 0.1025641

The test error of the KKN model with K=1 is 12.82051%.

knn.pred = knn(train.X,test.X,train.Y, k=10)
table(test$mpg01,knn.pred)
##    knn.pred
##      0  1
##   0 31  7
##   1  4 36
1- mean(knn.pred == test$mpg01)
## [1] 0.1410256

The test error of the KKN model with K=10 is 17.94872%.

knn.pred = knn(train.X,test.X,train.Y, k=15)
table(test$mpg01,knn.pred)
##    knn.pred
##      0  1
##   0 31  7
##   1  3 37
1- mean(knn.pred == test$mpg01)
## [1] 0.1282051

The test error of the KKN model with K=10 is about 16.66667%. 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.

boston=na.omit(Boston)
median.crim =median(boston$crim)
boston$crim01 = ifelse(Boston$crim > median.crim, 1, 0)
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
split<- sample(c(rep(0, 0.8 * nrow(Auto)), rep(1, 0.2 * nrow(Auto))))
train <- boston[split == 0, ] # 400 obs.
test <- boston[split == 1, ]  # 106 obs.
m1= glm(crim01 ~ age+zn+tax, data=train, family = "binomial")
m1b = step(m1, direction = "backward")
## Start:  AIC=294.26
## crim01 ~ age + zn + tax
## 
##        Df Deviance    AIC
## <none>      286.26 294.26
## - zn    1   292.47 298.47
## - age   1   321.08 327.08
## - tax   1   361.46 367.46
test$prob = predict(m1b, newdata = test, type = "response")
test$pred = ifelse(test$prob >0.5,1,0)
table(test$pred,test$crim01)
##    
##      0  1
##   0 40 19
##   1  5 33
1-mean(test$pred==test$crim01)
## [1] 0.2474227

The test error of the logistic model using age,zn and tax is 21.42857%.

m1 = lda(crim01 ~ age+zn+tax, data=train)
prob = predict(m1, newdata = test, type = "response")
table(prob$class,test$crim01)
##    
##      0  1
##   0 41 20
##   1  4 32
1-mean(prob$class == test$crim01)
## [1] 0.2474227

The test error of the LDA model using age,zn and taxis 20.40816%.

train.X=cbind(train$age,train$zn,train$tax)
test.X=cbind(test$age,test$zn,test$tax) 
train.Y = train$crim01
knn.pred = knn(train.X,test.X,train.Y, k=1)
table(test$crim01,knn.pred)
##    knn.pred
##      0  1
##   0 43  2
##   1  6 46
1- mean(knn.pred == test$crim01) # 0.09433962
## [1] 0.08247423

The test error of the KNN model with K=1 using age,zn and taxis 9.433962%.

knn.pred = knn(train.X,test.X,train.Y, k=10)
table(test$crim01,knn.pred)
##    knn.pred
##      0  1
##   0 38  7
##   1  7 45
1- mean(knn.pred == test$crim01) # 0.09433962
## [1] 0.1443299

The test error of the KNN model with K=10 using age,zn and taxis 7.142857%.

m1= glm(crim01 ~ age+dis+rad, data=train, family = "binomial")
m1b = step(m1, direction = "backward")
## Start:  AIC=245.62
## crim01 ~ age + dis + rad
## 
##        Df Deviance    AIC
## <none>      237.62 245.62
## - dis   1   251.41 257.41
## - age   1   260.51 266.51
## - rad   1   338.97 344.97
test$prob = predict(m1b, newdata = test, type = "response")
test$pred = ifelse(test$prob >0.5,1,0)
table(test$pred,test$crim01)
##    
##      0  1
##   0 40 15
##   1  5 37
1-mean(test$pred==test$crim01) # 0.2142857
## [1] 0.2061856

The test error of the logistic model using age,dis and rad is 14.28571%.

m1 = lda(crim01 ~ age+dis+rad, data=train)
prob = predict(m1, newdata = test, type = "response")
table(prob$class,test$crim01)
##    
##      0  1
##   0 41 17
##   1  4 35
1-mean(prob$class == test$crim01)
## [1] 0.2164948

The test error of the LDA model using age,dis and rad is 20.40816%.

train.X=cbind(train$age,train$dis,train$rad)
test.X=cbind(test$age,test$dis,test$rad) 
train.Y = train$crim01
knn.pred = knn(train.X,test.X,train.Y, k=1)
table(test$crim01,knn.pred)
##    knn.pred
##      0  1
##   0 37  8
##   1 14 38
1- mean(knn.pred == test$crim01)
## [1] 0.2268041

The test error of the KNN model with K=1 using age,dis and rad is 26.53061%.

knn.pred = knn(train.X,test.X,train.Y, k=10)
table(test$crim01,knn.pred)
##    knn.pred
##      0  1
##   0 37  8
##   1 14 38
1- mean(knn.pred == test$crim01)
## [1] 0.2268041

The test error of the KNN model with K=10 using age,dis and rad is 24.4898%.

Overall, the KNN model with K=10 using age,zn and tax produced the best prediction by far. Interestingly, KNN was the worst model when I tried a different combination of variables.