Exercise 13.

This question should be answered using the Weekly data set, which is part of the ISLR2 package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.

Exercise 13.(a)

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

Answer: There appears to be little correlation previous week and today. The only correlation is between Year and Volume.

library(ISLR2)

names(Weekly)  # Predictor's Name
## [1] "Year"      "Lag1"      "Lag2"      "Lag3"      "Lag4"      "Lag5"     
## [7] "Volume"    "Today"     "Direction"
dim(Weekly)    # Dimension of Data
## [1] 1089    9
summary(Weekly)  # Summary of Data
##       Year           Lag1               Lag2               Lag3         
##  Min.   :1990   Min.   :-18.1950   Min.   :-18.1950   Min.   :-18.1950  
##  1st Qu.:1995   1st Qu.: -1.1540   1st Qu.: -1.1540   1st Qu.: -1.1580  
##  Median :2000   Median :  0.2410   Median :  0.2410   Median :  0.2410  
##  Mean   :2000   Mean   :  0.1506   Mean   :  0.1511   Mean   :  0.1472  
##  3rd Qu.:2005   3rd Qu.:  1.4050   3rd Qu.:  1.4090   3rd Qu.:  1.4090  
##  Max.   :2010   Max.   : 12.0260   Max.   : 12.0260   Max.   : 12.0260  
##       Lag4               Lag5              Volume            Today         
##  Min.   :-18.1950   Min.   :-18.1950   Min.   :0.08747   Min.   :-18.1950  
##  1st Qu.: -1.1580   1st Qu.: -1.1660   1st Qu.:0.33202   1st Qu.: -1.1540  
##  Median :  0.2380   Median :  0.2340   Median :1.00268   Median :  0.2410  
##  Mean   :  0.1458   Mean   :  0.1399   Mean   :1.57462   Mean   :  0.1499  
##  3rd Qu.:  1.4090   3rd Qu.:  1.4050   3rd Qu.:2.05373   3rd Qu.:  1.4050  
##  Max.   : 12.0260   Max.   : 12.0260   Max.   :9.32821   Max.   : 12.0260  
##  Direction 
##  Down:484  
##  Up  :605  
##            
##            
##            
## 
pairs(Weekly)

cor(Weekly[, -9])  # Pairwise correlations
##               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
attach(Weekly)
plot(Volume)

Exercise 13.(b)

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

Answer: Lag2 has high corelation than other predictors

glm.fits <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly,  family = binomial)

summary(glm.fits)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Weekly)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.26686    0.08593   3.106   0.0019 **
## Lag1        -0.04127    0.02641  -1.563   0.1181   
## Lag2         0.05844    0.02686   2.175   0.0296 * 
## Lag3        -0.01606    0.02666  -0.602   0.5469   
## Lag4        -0.02779    0.02646  -1.050   0.2937   
## Lag5        -0.01447    0.02638  -0.549   0.5833   
## Volume      -0.02274    0.03690  -0.616   0.5377   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1486.4  on 1082  degrees of freedom
## AIC: 1500.4
## 
## Number of Fisher Scoring iterations: 4
coef(glm.fits)
## (Intercept)        Lag1        Lag2        Lag3        Lag4        Lag5 
##  0.26686414 -0.04126894  0.05844168 -0.01606114 -0.02779021 -0.01447206 
##      Volume 
## -0.02274153
summary(glm.fits)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Weekly)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.26686    0.08593   3.106   0.0019 **
## Lag1        -0.04127    0.02641  -1.563   0.1181   
## Lag2         0.05844    0.02686   2.175   0.0296 * 
## Lag3        -0.01606    0.02666  -0.602   0.5469   
## Lag4        -0.02779    0.02646  -1.050   0.2937   
## Lag5        -0.01447    0.02638  -0.549   0.5833   
## Volume      -0.02274    0.03690  -0.616   0.5377   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1486.4  on 1082  degrees of freedom
## AIC: 1500.4
## 
## Number of Fisher Scoring iterations: 4
glm.probs <- predict(glm.fits, type = "response") # predict probability
glm.probs[1:10]
##         1         2         3         4         5         6         7         8 
## 0.6086249 0.6010314 0.5875699 0.4816416 0.6169013 0.5684190 0.5786097 0.5151972 
##         9        10 
## 0.5715200 0.5554287
contrasts(Direction)
##      Up
## Down  0
## Up    1

Exercise 13.(c)

Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.

According to confusion matrix, the off-diagonals represent the incorrect prediction. (430+48)/1089 = 0.0489348

glm.pred <- ifelse(glm.probs > 0.5, "Up", "Down")

table(glm.pred, Direction)    # build a Confusion Matrix
##         Direction
## glm.pred Down  Up
##     Down   54  48
##     Up    430 557
(54+557)/1089  # Correct prediction
## [1] 0.5610652
(430+48)/1089  # Incorrect Prediction
## [1] 0.4389348

Exercise 13.(d)

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

Train <- Weekly$Year <= 2008
Test <- Weekly$Year > 2008

Weekly_Train <- Weekly[Train, ]
Weekly_Test <- Weekly[Test, ]


glm.fits_partial <- glm(Direction ~ Lag2, data = Weekly, subset = Train, family = binomial)

summary(glm.fits_partial)
## 
## Call:
## glm(formula = Direction ~ Lag2, family = binomial, data = Weekly, 
##     subset = Train)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.20326    0.06428   3.162  0.00157 **
## Lag2         0.05810    0.02870   2.024  0.04298 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1354.7  on 984  degrees of freedom
## Residual deviance: 1350.5  on 983  degrees of freedom
## AIC: 1354.5
## 
## Number of Fisher Scoring iterations: 4
plot(glm.fits_partial)

glm.probs_partial <- predict(glm.fits_partial, Weekly_Test, type = "response")
glm.probs_partial[1:10]
##       986       987       988       989       990       991       992       993 
## 0.5261291 0.6447364 0.4862159 0.4852001 0.5197667 0.5401255 0.6233482 0.4809930 
##       994       995 
## 0.4512204 0.4848808
contrasts(Weekly_Test$Direction)
##      Up
## Down  0
## Up    1
glm.pred_partial <- ifelse(glm.probs_partial > 0.5, "Up", "Down")

table(glm.pred_partial, Weekly_Test$Direction)    # build a Confusion Matrix
##                 
## glm.pred_partial Down Up
##             Down    9  5
##             Up     34 56
(9+56)/104
## [1] 0.625

Exercise 13.(e)

Repeat (d) using LDA

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
lda.fit <- lda(Direction ~ Lag2, data = Weekly, subset = Train)
lda.fit
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = Train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
## 
## Coefficients of linear discriminants:
##            LD1
## Lag2 0.4414162
plot(lda.fit)

lda.pred <- predict(lda.fit, Weekly_Test)
names(lda.pred)
## [1] "class"     "posterior" "x"
lda.class <- lda.pred$class
table(lda.class, Weekly_Test$Direction)
##          
## lda.class Down Up
##      Down    9  5
##      Up     34 56
(9+56)/104
## [1] 0.625

Exercise 13.(f)

Repeat (d) using QDA.

qda.fit <- qda(Direction ~ Lag2, data = Weekly, subset = Train)
qda.fit
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = Train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
qda.class <- predict(qda.fit, Weekly_Test)$class
table(qda.class, Weekly_Test$Direction)
##          
## qda.class Down Up
##      Down    0  0
##      Up     43 61
(0+61)/104
## [1] 0.5865385

Exercise 13.(g)

Repeat (d) using KNN with K = 1.

library(class)

Train.X <- data.frame(Lag2=Weekly_Train$Lag2)
Test.X <- data.frame(Lag2=Weekly_Test$Lag2)

Train.y <- Weekly_Train$Direction
Test.y <- Weekly_Test$Direction

set.seed(1)

knn.pred <- knn(Train.X, Test.X, Weekly_Train$Direction, k = 1 )

table(Predicted = knn.pred, Actual = Test.y)
##          Actual
## Predicted Down Up
##      Down   21 30
##      Up     22 31
(21+31)/104
## [1] 0.5

Exercise 13.(h)

Repeat (d) using naive Bayes.

library(e1071)
nb.fit <- naiveBayes(Direction ~ Lag2, data=Weekly, subset=Train)
nb.fit
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Conditional probabilities:
##       Lag2
## Y             [,1]     [,2]
##   Down -0.03568254 2.199504
##   Up    0.26036581 2.317485
nb.class <- predict(nb.fit, Weekly_Test)
table(nb.class, Weekly_Test$Direction)
##         
## nb.class Down Up
##     Down    0  0
##     Up     43 61
(0+61)/104
## [1] 0.5865385

Exercise 13.(i)

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

logistic regression and LDA have the best results

Exercise 13.(j)

Experiment with different combinations of predictors, including possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Note that you should also experiment with values for K in the KNN classifier.

**KNN with K=4 is best case

library(class)

Train.X <- data.frame(Lag2=Weekly_Train$Lag2)
Test.X <- data.frame(Lag2=Weekly_Test$Lag2)
#Train.X <- cbind(Lag1, Lag2)[Train,]
#Test.X <- cbind(Lag1, Lag2)[Test,]

Train.y <- Weekly_Train$Direction
Test.y <- Weekly_Test$Direction

set.seed(1)

knn.pred <- knn(Train.X, Test.X, Weekly_Train$Direction, k = 4 )

table(Predicted = knn.pred, Actual = Test.y)
##          Actual
## Predicted Down Up
##      Down   20 17
##      Up     23 44
(20+44)/104
## [1] 0.6153846

Add Predictor to lda => It does not work.

library(MASS)
lda.fit2 <- lda(Direction ~ Lag2+Lag1, data = Weekly, subset = Train)
lda.fit2
## Call:
## lda(Direction ~ Lag2 + Lag1, data = Weekly, subset = Train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2         Lag1
## Down -0.03568254  0.289444444
## Up    0.26036581 -0.009213235
## 
## Coefficients of linear discriminants:
##             LD1
## Lag2  0.2982579
## Lag1 -0.3013148
lda.pred2 <- predict(lda.fit2, Weekly_Test)
lda.class2 <- lda.pred2$class
table(lda.class2, Weekly_Test$Direction)
##           
## lda.class2 Down Up
##       Down    7  8
##       Up     36 53
(9+56)/104
## [1] 0.625

Exercise 14

In this problem, you will develop a model to predict whether a given car gets high or low gas mileage based on the Auto data set.

Exercise 14.(a)

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

mpg_median <- median(Auto$mpg)
mpg_median
## [1] 22.75
mpg_01 <- ifelse(Auto$mpg > mpg_median, 1, 0)


Auto_01 <- data.frame(Auto, mpg_01)
summary(Auto_01)
##       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  
##      mpg_01   
##  Min.   :0.0  
##  1st Qu.:0.0  
##  Median :0.5  
##  Mean   :0.5  
##  3rd Qu.:1.0  
##  Max.   :1.0  
## 

Exercise 14.(b)

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

Answer:displacement, horse power and weight are most useful predictor.

pairs(Auto_01)

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
## 
##     select
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
ggplot(Auto_01, aes(x=factor(mpg_01), y=displacement)) + geom_boxplot()

ggplot(Auto_01, aes(x=factor(mpg_01), y=horsepower)) + geom_boxplot()

ggplot(Auto_01, aes(x=factor(mpg_01), y=weight)) + geom_boxplot()

ggplot(Auto_01, aes(x=factor(mpg_01), y=acceleration)) + geom_boxplot()

ggplot(Auto_01, aes(x=factor(mpg_01), y=year)) + geom_boxplot()

ggplot(Auto_01, aes(x=mpg, y=year)) + geom_point()

ggplot(Auto_01, aes(x=mpg, y=cylinders)) + geom_point()

ggplot(Auto_01, aes(x=mpg, y=origin)) + geom_point()

Exercise 14.(c)

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

set.seed(1)

n <- length(Auto_01$mpg)

Select_Idx <- sample(1:n, size = 0.7 * n)

Auto_Train <- Auto_01[Select_Idx,]
Auto_Test <- Auto_01[-Select_Idx,]

Exercise 14.(d)

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

Answer: Test error rate is 12.71%

lda.mpg.fit <- lda(Auto_Train$mpg_01 ~ displacement + horsepower + weight + acceleration + year, data = Auto_Train)
lda.mpg.fit
## Call:
## lda(Auto_Train$mpg_01 ~ displacement + horsepower + weight + 
##     acceleration + year, data = Auto_Train)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4927007 0.5072993 
## 
## Group means:
##   displacement horsepower   weight acceleration     year
## 0     271.9333  129.13333 3611.052     14.71556 74.47407
## 1     116.8129   79.27338 2342.165     16.57338 77.60432
## 
## Coefficients of linear discriminants:
##                        LD1
## displacement -0.0102367198
## horsepower    0.0124774848
## weight       -0.0010441618
## acceleration -0.0005208118
## year          0.1116760488
lda.mpg.pred <- predict(lda.mpg.fit, Auto_Test)
lda.mpg.class <- lda.mpg.pred$class
table(lda.mpg.class, Auto_Test$mpg_01)
##              
## lda.mpg.class  0  1
##             0 47  1
##             1 14 56
mean(lda.mpg.class != Auto_Test$mpg_01)
## [1] 0.1271186

Exercise 14.(e)

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

Answer: Test Error Rate is 12.71%

qda.mpg.fit <- qda(mpg_01 ~ displacement + horsepower + weight + acceleration + year, data = Auto_Train)
qda.mpg.fit
## Call:
## qda(mpg_01 ~ displacement + horsepower + weight + acceleration + 
##     year, data = Auto_Train)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4927007 0.5072993 
## 
## Group means:
##   displacement horsepower   weight acceleration     year
## 0     271.9333  129.13333 3611.052     14.71556 74.47407
## 1     116.8129   79.27338 2342.165     16.57338 77.60432
qda.mpg.pred <- predict(qda.mpg.fit, Auto_Test)
qda.mpg.class <- qda.mpg.pred$class

table(qda.mpg.class, Auto_Test$mpg_01)
##              
## qda.mpg.class  0  1
##             0 51  5
##             1 10 52
mean(qda.mpg.class != Auto_Test$mpg_01)
## [1] 0.1271186

Exercise 14.(f)

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

Answer: Test Error Rate is 10.17%

glm.mpg.fit <- glm(mpg_01 ~ displacement + horsepower + weight + acceleration + year, data=Auto_Train, family = binomial)
glm.mpg.prob <- predict(glm.mpg.fit, Auto_Test, type = "response")
glm.mpg.class <- ifelse(glm.mpg.prob > 0.5, 1, 0)

table(glm.mpg.class, Auto_Test$mpg_01)
##              
## glm.mpg.class  0  1
##             0 53  4
##             1  8 53
mean(glm.mpg.class != Auto_Test$mpg_01)
## [1] 0.1016949

Exercise 14.(g)

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

Answer: Test Error Rate: 11.02%

nb.mpg.fit <- naiveBayes(mpg_01 ~ displacement + horsepower + weight + acceleration + year, data = Auto_Train)
nb.mpg.pred <- predict(nb.mpg.fit, Auto_Test)

table(nb.mpg.pred, Auto_Test$mpg_01)
##            
## nb.mpg.pred  0  1
##           0 49  1
##           1 12 56
mean(nb.mpg.pred != Auto_Test$mpg_01)
## [1] 0.1101695

Exercise 14.(h)

Perform KNN on the training data, with several values of K, in order to predict mpg01. Use only the variables that seemed most associated with mpg01 in (b). What test errors do you obtain? Which value of K seems to perform the best on this data set?

Answer: Test Error Rate is 10.17% with K=3

Train.mpg.X <- Auto_Train[, c("displacement", "horsepower", "weight", "acceleration", "year")]
Test.mpg.X <- Auto_Test[, c("displacement", "horsepower", "weight", "acceleration", "year")]

Train.mpg.X <- as.data.frame(Train.mpg.X)
Test.mpg.X <- as.data.frame(Test.mpg.X)

Train.mpg.Y <- Auto_Train$mpg_01
Test.mpg.Y <- Auto_Test$mpg_01

# k = 1 case
knn.mpg.pred <- knn(Train.mpg.X, Test.mpg.X, cl = Train.mpg.Y, k = 1)

table(Predicted = knn.mpg.pred, Actual = Test.mpg.Y)
##          Actual
## Predicted  0  1
##         0 51  6
##         1 10 51
mean(knn.mpg.pred != Test.mpg.Y)
## [1] 0.1355932
# k = 2 case
knn.mpg.pred <- knn(Train.mpg.X, Test.mpg.X, cl = Train.mpg.Y, k = 2)

table(Predicted = knn.mpg.pred, Actual = Test.mpg.Y)
##          Actual
## Predicted  0  1
##         0 52  9
##         1  9 48
mean(knn.mpg.pred != Test.mpg.Y)
## [1] 0.1525424
# k = 3 case
knn.mpg.pred <- knn(Train.mpg.X, Test.mpg.X, cl = Train.mpg.Y, k = 3)

table(Predicted = knn.mpg.pred, Actual = Test.mpg.Y)
##          Actual
## Predicted  0  1
##         0 52  3
##         1  9 54
mean(knn.mpg.pred != Test.mpg.Y)
## [1] 0.1016949
# k = 4 case
knn.mpg.pred <- knn(Train.mpg.X, Test.mpg.X, cl = Train.mpg.Y, k = 4)

table(Predicted = knn.mpg.pred, Actual = Test.mpg.Y)
##          Actual
## Predicted  0  1
##         0 51  4
##         1 10 53
mean(knn.mpg.pred != Test.mpg.Y)
## [1] 0.1186441
# k = 5 case
knn.mpg.pred <- knn(Train.mpg.X, Test.mpg.X, cl = Train.mpg.Y, k = 5)

table(Predicted = knn.mpg.pred, Actual = Test.mpg.Y)
##          Actual
## Predicted  0  1
##         0 51  5
##         1 10 52
mean(knn.mpg.pred != Test.mpg.Y)
## [1] 0.1271186
# k = 6 case
knn.mpg.pred <- knn(Train.mpg.X, Test.mpg.X, cl = Train.mpg.Y, k = 6)

table(Predicted = knn.mpg.pred, Actual = Test.mpg.Y)
##          Actual
## Predicted  0  1
##         0 50  4
##         1 11 53
mean(knn.mpg.pred != Test.mpg.Y)
## [1] 0.1271186

Exercise 16

Using the Boston data set, fit classification models in order to predict whether a given census tract has a crime rate above or below the median. Explore logistic regression, LDA, naive Bayes, and KNN models using various subsets of the predictors. Describe your findings. Hint: You will have to create the response variable yourself, using the variables that are contained in the Boston data set.

library(MASS)        # for Boston dataset and LDA/QDA
library(class)       # for KNN
library(e1071)       # for Naive Bayes
library(dplyr)       # for data manipulation
data(Boston)

median_crim <- median(Boston$crim)  # Calc Median Value

Boston$crim_01 <- ifelse(Boston$crim > median_crim, 1, 0)

pairs(Boston)

all_predictors <- c('zn', 'indus', 'chas', 'nox', 'rm', 'age', 'dis', 'rad', 'tax', 'ptratio', 'black', 'lstat')
cor_related   <- c('nox', 'rad', 'tax', 'dis', 'lstat', 'black')
small_subset  <- c('nox', 'rad', 'tax', 'dis')

Boston_wo <- Boston %>% select(-crim)
set.seed(1)

n <- nrow(Boston)
train_idx <- sample(1:n, size = 0.7 * n)
Boston_train <- Boston[train_idx, ]
Boston_test  <- Boston[-train_idx, ]

Logistic Regression

#  ===== case all_predictors ==== #
predictor_set <- all_predictors 

# Build formula dynamically
formula <- as.formula(
  paste("crim_01 ~", paste(predictor_set, collapse = " + "))
)

# Train logistic regression model
glm.fit  <- glm(formula, data = Boston_train, family = binomial)

# Predict probabilities on test set
glm.prob <- predict(glm.fit, Boston_test, type = "response")

# Convert probabilities to class labels
glm.pred <- ifelse(glm.prob > 0.5, 1, 0)

# Confusion matrix and accuracy
table(Predicted = glm.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 61  6
##         1 12 73
mean(glm.pred == Boston_test$crim_01)  # Accuracy
## [1] 0.8815789
#  ===== case cor_related ==== #
predictor_set <- cor_related

# Build formula dynamically
formula <- as.formula(
  paste("crim_01 ~", paste(predictor_set, collapse = " + "))
)

# Train logistic regression model
glm.fit  <- glm(formula, data = Boston_train, family = binomial)

# Predict probabilities on test set
glm.prob <- predict(glm.fit, Boston_test, type = "response")

# Convert probabilities to class labels
glm.pred <- ifelse(glm.prob > 0.5, 1, 0)

# Confusion matrix and accuracy
table(Predicted = glm.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 58 13
##         1 15 66
mean(glm.pred == Boston_test$crim_01)  # Accuracy
## [1] 0.8157895
#  ===== case Small Subset ==== #
predictor_set <- small_subset

# Build formula dynamically
formula <- as.formula(
  paste("crim_01 ~", paste(predictor_set, collapse = " + "))
)

# Train logistic regression model
glm.fit  <- glm(formula, data = Boston_train, family = binomial)

# Predict probabilities on test set
glm.prob <- predict(glm.fit, Boston_test, type = "response")

# Convert probabilities to class labels
glm.pred <- ifelse(glm.prob > 0.5, 1, 0)

# Confusion matrix and accuracy
table(Predicted = glm.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 58 14
##         1 15 65
mean(glm.pred == Boston_test$crim_01)  # Accuracy
## [1] 0.8092105

LDA

#  ===== case all_predictors ==== #
predictor_set <- all_predictors 
formula <- as.formula(  paste("crim_01 ~", paste(predictor_set, collapse = " + ")))

lda.fit  <- lda(formula, data = Boston_train)
lda.pred <- predict(lda.fit, Boston_test)$class

# Confusion matrix & accuracy
table(Predicted = lda.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 71 19
##         1  2 60
mean(lda.pred == Boston_test$crim_01)
## [1] 0.8618421
#  ===== case cor_related ==== #
predictor_set <- cor_related
formula <- as.formula(  paste("crim_01 ~", paste(predictor_set, collapse = " + ")))

lda.fit  <- lda(formula, data = Boston_train)
lda.pred <- predict(lda.fit, Boston_test)$class

# Confusion matrix & accuracy
table(Predicted = lda.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 69 20
##         1  4 59
mean(lda.pred == Boston_test$crim_01)
## [1] 0.8421053
#  ===== case Small Subset ==== #
predictor_set <- small_subset
formula <- as.formula(  paste("crim_01 ~", paste(predictor_set, collapse = " + ")))

lda.fit  <- lda(formula, data = Boston_train)
lda.pred <- predict(lda.fit, Boston_test)$class

# Confusion matrix & accuracy
table(Predicted = lda.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 69 19
##         1  4 60
mean(lda.pred == Boston_test$crim_01)
## [1] 0.8486842

Naive Bayes

#  ===== case all_predictors ==== #
predictor_set <- all_predictors 

nb.fit <- naiveBayes(crim_01 ~ . -crim_01, data = Boston_train)
nb.pred <- predict(nb.fit, newdata = Boston_test)

table(Predicted = nb.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 70  5
##         1  3 74
mean(nb.pred == Boston_test$crim_01)
## [1] 0.9473684
#  ===== case cor_related ==== #
predictor_set <- cor_related

nb.fit <- naiveBayes(crim_01 ~ . -crim_01, data = Boston_train)
nb.pred <- predict(nb.fit, newdata = Boston_test)

table(Predicted = nb.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 70  5
##         1  3 74
mean(nb.pred == Boston_test$crim_01)
## [1] 0.9473684
#  ===== case Small Subset ==== #
predictor_set <- small_subset

nb.fit <- naiveBayes(crim_01 ~ . -crim_01, data = Boston_train)
nb.pred <- predict(nb.fit, newdata = Boston_test)

table(Predicted = nb.pred, Actual = Boston_test$crim_01)
##          Actual
## Predicted  0  1
##         0 70  5
##         1  3 74
mean(nb.pred == Boston_test$crim_01)
## [1] 0.9473684

KNN

#  ===== case all_predictors ==== #
predictor_set <- all_predictors 

train.X <- scale(Boston_train[, predictor_set])
test.X  <- scale(
  Boston_test[, predictor_set],
  center = attr(train.X, "scaled:center"),
  scale  = attr(train.X, "scaled:scale")
)
train.y <- Boston_train$crim_01
test.y  <- Boston_test$crim_01


for (k in 1:5) {
  knn.pred <- knn(train = train.X,
                  test  = test.X,
                  cl    = train.y,
                  k     = k)
  cat("all_predictors  ","K =", k, "Accuracy =", mean(knn.pred == test.y), "\n")
}
## all_predictors   K = 1 Accuracy = 0.9276316 
## all_predictors   K = 2 Accuracy = 0.9078947 
## all_predictors   K = 3 Accuracy = 0.9605263 
## all_predictors   K = 4 Accuracy = 0.9539474 
## all_predictors   K = 5 Accuracy = 0.9407895
#  ===== case cor_related ==== #
predictor_set <- cor_related

train.X <- scale(Boston_train[, predictor_set])
test.X  <- scale(
  Boston_test[, predictor_set],
  center = attr(train.X, "scaled:center"),
  scale  = attr(train.X, "scaled:scale")
)
train.y <- Boston_train$crim_01
test.y  <- Boston_test$crim_01

for (k in 1:5) {
  knn.pred <- knn(train = train.X,
                  test  = test.X,
                  cl    = train.y,
                  k     = k)
  cat("cor_related     ","K =", k, "Accuracy =", mean(knn.pred == test.y), "\n")
}
## cor_related      K = 1 Accuracy = 0.9473684 
## cor_related      K = 2 Accuracy = 0.9342105 
## cor_related      K = 3 Accuracy = 0.9407895 
## cor_related      K = 4 Accuracy = 0.9144737 
## cor_related      K = 5 Accuracy = 0.9473684
#  ===== case Small Subset ==== #
predictor_set <- small_subset

train.X <- scale(Boston_train[, predictor_set])
test.X  <- scale(
  Boston_test[, predictor_set],
  center = attr(train.X, "scaled:center"),
  scale  = attr(train.X, "scaled:scale")
)
train.y <- Boston_train$crim_01
test.y  <- Boston_test$crim_01

for (k in 1:5) {
  knn.pred <- knn(train = train.X,
                  test  = test.X,
                  cl    = train.y,
                  k     = k)
  cat("Small Subset    ","K =", k, "Accuracy =", mean(knn.pred == test.y), "\n")
}
## Small Subset     K = 1 Accuracy = 0.9605263 
## Small Subset     K = 2 Accuracy = 0.9539474 
## Small Subset     K = 3 Accuracy = 0.9605263 
## Small Subset     K = 4 Accuracy = 0.9539474 
## Small Subset     K = 5 Accuracy = 0.9605263