Chapter 4

Problem 10

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  
##            
##            
##            
## 
cor(Weekly[,1:8])
##               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
pairs(Weekly[,1:8])

df_vol <- Weekly %>% group_by(Year) %>% summarise(Vol   = mean(Volume),
                                                .groups = "drop" ) 

gg_cor <- ggplot(df_vol,aes(Year,Vol)) +
          geom_point()+
          geom_smooth()+
          labs(title = "Scatterplot of Average Volume of Shares and Year ",
           x     = "Year",
           y     = "Avg. Volume(in billions)")

    
print(gg_cor)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

A) From the Summary Statistics, We can see that the Min and Max for Lag1,Lag2,Lag3,Lag4,Lag5 and Today are same at -18.1950 and 12.0260 respectively. Looking at the correlation coefficients and pairs plot, there is not strong correlation and pattern between variables with the exception of strong positive correlation between year and volume traded.

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

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

A) H0: Predictor “Lag2” has no significant relationship with Direction or βLag2 = 0
Ha: Predictor “Lag2” has significant relationship with Direction or βLag2 ≠ 0 Significant level at 0.05, we can reject the null hypothesis for Lag2 alone as rest of the predictors are not significant.

Logistic regression summary indicates that Lag2 alone is statistically significant

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

logistic.probs=predict(logistic_full,type="response")


logistic.pred=rep("Down",1089)

logistic.pred[logistic.probs > .5]= "Up"

table(logistic.pred ,Weekly$Direction )
##              
## logistic.pred Down  Up
##          Down   54  48
##          Up    430 557

A) Looking at the confusion matrix for the Accuracy that the logistic regression model has is calculated as \[ Overall\ Accuracy\% = \frac{54+557}{1089}\approx 56\% \] Based on the accuracy we can say that it is very slightly better than random guessing. It is important to look at the individual error rates for each classes predicted:

\[ Predicting "Up" Correct(Positive\ prediction) = \frac{557}{(430+557)}\approx56.4\% \] \[ Predicting "Down" Correct(Negative\ prediction) = \frac{54}{(54+48)}\approx52.9\% \]

Either case it is meagerly better than random chance.

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

Weekly_train <- Weekly %>% filter(Year <= 2008)
Weekly_test <- Weekly %>% filter(Year > 2008)

logistic_train = glm(Direction ~ Lag2, data=Weekly_train, family=binomial)
summary(logistic_train)
## 
## Call:
## glm(formula = Direction ~ Lag2, family = binomial, data = Weekly_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
test.probs=predict(logistic_train,Weekly_test,type="response")


test.pred=rep("Down",104)

test.pred[test.probs > .5]= "Up"

table(test.pred ,Weekly_test$Direction )
##          
## test.pred Down Up
##      Down    9  5
##      Up     34 56

A) Looking at the confusion matrix for the Accuracy that the logistic regression model has is calculated as \[ Overall\ Accuracy\% = \frac{9+56}{104}= 62.5\% \] Over all accuracy is much better than the result seen in problem (c).

(e) Repeat (d) using LDA.

lda_l2=lda(Direction ~ Lag2 ,data=Weekly_train)
lda_l2
## Call:
## lda(Direction ~ Lag2, data = Weekly_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_l2)

#prediction on test

lda_l2_pred=predict(lda_l2,Weekly_test)

lda_l2_class <- lda_l2_pred$class

table(lda_l2_class,Weekly_test$Direction)
##             
## lda_l2_class Down Up
##         Down    9  5
##         Up     34 56

A) Looking at the confusion matrix for the Accuracy that the LDA model is calculated as \[ LDA\ Accuracy\% = \frac{9+56}{104}= 62.5\% \]

(f) Repeat (d) using QDA.

qda_fit <-  qda(Direction ~ Lag2, data=Weekly_train)
#prediction
qda_pred <-  predict(qda_fit,Weekly_test)
#
qda_class <-  qda_pred$class
#confusion matrix(QDA)
table(qda_class,Weekly_test$Direction)
##          
## qda_class Down Up
##      Down    0  0
##      Up     43 61

A) Looking at the confusion matrix for the Accuracy that the QDA model is calculated as \[ QDA\ Accuracy\% = \frac{0+61}{104}= 58.65\% \] QDA classifier is not performing as good as the LDA and logistic regression. It is very slightly better than random guessing.

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

#preparing the data frames with just `lag2` for both test and train sets
#With standardizing the predictor(just a try as this is not needed with single predictor)
train_x = data.frame(Lag2 = scale( Weekly_train[,c('Lag2')]))
test_x = data.frame(Lag2 = scale( Weekly_test[,c('Lag2')]))

#Standardizing is not needed as there is only one predictor
train_x = data.frame(Lag2 = Weekly_train$Lag2)
test_x = data.frame(Lag2 = Weekly_test$Lag2)
set.seed(1)
knn.pred=knn(train_x,test_x,Weekly_train$Direction ,k=1)
table(knn.pred ,Weekly_test$Direction)
##         
## knn.pred Down Up
##     Down   21 30
##     Up     22 31

A) Looking at the confusion matrix for the Accuracy that the KNN model with K=1 is calculated as \[ KNN\ with\ K=1:: Accuracy\% = \frac{21+31}{104}= 50.00\% \] A)The results using K = 1 are not very good, since only 50 % of the observations are correctly predicted. Of course, it may be that K = 1 results in an overly flexible fit to the data.

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

A) Based on the accuracy scores from the confusion matrix Logistic Regression and Linear Discriminate Analysis have the best results(62.5%) in predicting the direction.

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

# first looking into the KNN with different `K` values::
k_itr <- c(2,3,4,5,6,7,8,9)
i <- 1

while(i <= length(k_itr))
{
knn.pred=knn(train_x,test_x,Weekly_train$Direction ,k=k_itr[i])
cat("Confusion matrix for K=",k_itr[i] )

tmp <- table(knn.pred,Weekly_test$Direction)
print(tmp)
i <- i + 1

}
## Confusion matrix for K= 2        
## knn.pred Down Up
##     Down   18 25
##     Up     25 36
## Confusion matrix for K= 3        
## knn.pred Down Up
##     Down   16 20
##     Up     27 41
## Confusion matrix for K= 4        
## knn.pred Down Up
##     Down   20 19
##     Up     23 42
## Confusion matrix for K= 5        
## knn.pred Down Up
##     Down   15 22
##     Up     28 39
## Confusion matrix for K= 6        
## knn.pred Down Up
##     Down   16 21
##     Up     27 40
## Confusion matrix for K= 7        
## knn.pred Down Up
##     Down   15 20
##     Up     28 41
## Confusion matrix for K= 8        
## knn.pred Down Up
##     Down   15 20
##     Up     28 41
## Confusion matrix for K= 9        
## knn.pred Down Up
##     Down   17 21
##     Up     26 40

Increasing the K from 2 to 9 we see that the maximum accuracy is 55.77%, not useful as it is same as random guessing.

lda_l12=lda(Direction ~ Lag2+Lag1+Year,data=Weekly_train)
lda_l12
## Call:
## lda(Direction ~ Lag2 + Lag1 + Year, data = Weekly_train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2         Lag1     Year
## Down -0.03568254  0.289444444 1999.295
## Up    0.26036581 -0.009213235 1998.853
## 
## Coefficients of linear discriminants:
##              LD1
## Lag2  0.25881823
## Lag1 -0.28676692
## Year -0.07702931
#prediction on test

lda_l12_pred=predict(lda_l12,Weekly_test)

lda_l12_class <- lda_l12_pred$class

table(lda_l12_class,Weekly_test$Direction)
##              
## lda_l12_class Down Up
##          Down   20 19
##          Up     23 42

Performing LDA with Lag1, Lag2and Year increases the accuracy to 59.6% compared to the LDA with Lag2 alone

logistic_alt= glm(Direction ~ I(Lag1^2)+Lag2, data=Weekly_train, family=binomial)
summary(logistic_alt)
## 
## Call:
## glm(formula = Direction ~ I(Lag1^2) + Lag2, family = binomial, 
##     data = Weekly_train)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.587  -1.259   1.015   1.093   1.338  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept) 0.181618   0.068622   2.647  0.00813 **
## I(Lag1^2)   0.004079   0.004583   0.890  0.37339   
## Lag2        0.065085   0.029785   2.185  0.02888 * 
## ---
## 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: 1349.7  on 982  degrees of freedom
## AIC: 1355.7
## 
## Number of Fisher Scoring iterations: 4
alt_probs=predict(logistic_alt,Weekly_test,type="response")


alt_pred=rep("Down",104)

alt_pred[alt_probs > .5]= "Up"

table(alt_pred ,Weekly_test$Direction )
##         
## alt_pred Down Up
##     Down    8  2
##     Up     35 59

Logistic regression with Lag1^2^ and Lag2 has a better accuracy of 64.42% \[ Logistic \ regression \ with\ transformation\ of Lag1 :: Accuracy\% = \frac{8+59}{104}= 64.42\% \]

logistic_alt= glm(Direction ~ I(Lag1^2)+Lag2+Lag1*Lag2, data=Weekly_train, family=binomial)
summary(logistic_alt)
## 
## Call:
## glm(formula = Direction ~ I(Lag1^2) + Lag2 + Lag1 * Lag2, family = binomial, 
##     data = Weekly_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6147  -1.2544   0.9978   1.0900   1.5193  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.197232   0.069904   2.821  0.00478 **
## I(Lag1^2)    0.002675   0.005111   0.523  0.60071   
## Lag2         0.057773   0.030373   1.902  0.05716 . 
## Lag1        -0.049855   0.031005  -1.608  0.10784   
## Lag2:Lag1    0.001260   0.007763   0.162  0.87109   
## ---
## 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: 1346.6  on 980  degrees of freedom
## AIC: 1356.6
## 
## Number of Fisher Scoring iterations: 4
alt_probs=predict(logistic_alt,Weekly_test,type="response")


alt_pred=rep("Down",104)

alt_pred[alt_probs > .5]= "Up"

table(alt_pred ,Weekly_test$Direction )
##         
## alt_pred Down Up
##     Down    6  6
##     Up     37 55

Logistic regression with interaction term gives an accuracy of 58.65% and also none of the predictors are significant.

Problem 11

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.

median_mpg <- median(Auto$mpg)

myAuto <- Auto %>% mutate(mpg01 = if_else(mpg > median_mpg,1,0))

# myAuto$mpg01 <- as.factor(myAuto$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.

cor(myAuto[,c(1:8,10)])
##                     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
pairs((myAuto[,c(1:8,10)]))

myAuto$mpg01 <- as.factor(myAuto$mpg01)

ggplot(myAuto,aes(mpg01,displacement)) +
geom_boxplot()+
ggthemes::theme_fivethirtyeight()+
labs(title = "mpg01 vs Displacement ",
     x     = "mpg01",
     y     = "Displacement")

ggplot(myAuto,aes(mpg01,cylinders)) +
geom_boxplot()+
ggthemes::theme_fivethirtyeight()+
labs(title = "mpg01 vs cylinders ",
     x     = "mpg01",
     y     = "cylinders")

ggplot(myAuto,aes(mpg01,horsepower)) +
geom_boxplot()+
ggthemes::theme_fivethirtyeight()+
labs(title = "mpg01 vs horsepower ",
     x     = "mpg01",
     y     = "horsepower")

ggplot(myAuto,aes(mpg01,weight)) +
geom_boxplot()+
ggthemes::theme_fivethirtyeight()+
labs(title = "mpg01 vs weight ",
     x     = "mpg01",
     y     = "weight")

A) Based on the correlation coefficientsmpg01 has a strong negative correlation with displacement,cylinders,horsepower and weight. For the box plots and classification analysis converted mpg01 to a qualitative variable.

Box plots show us that for the category of mpg01 is 0(less than median mpg) have higher median for displacement,cylinders,horsepower and weight confirming the negative correlation.

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

set.seed(452)
sample_cl = sample.split(myAuto$mpg01, SplitRatio = 0.75)
auto_train<-subset(myAuto,sample_cl==TRUE)
auto_test<-subset(myAuto,sample_cl==FALSE)

(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 for mpg01 using cylinders+displacement+horsepower+weight

lda_auto=lda(mpg01 ~ cylinders+displacement+horsepower+weight ,data=auto_train)

#prediction on test

lda_auto_pred=predict(lda_auto,auto_test)

lda_auto_class <- lda_auto_pred$class

table(lda_auto_class,auto_test$mpg01)
##               
## lda_auto_class  0  1
##              0 43  5
##              1  6 44

LDA accuracy with predictors thought to be highly correlated using the descriptive analysis. mpg01 ~ cylinders+displacement+horsepower+weight

\[ LDA:: Accuracy\% = \frac{43+44}{98}= 88.77\% \] \[ LDA :: Error\% = 11.22\% \] (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 for mpg01 using cylinders+displacement+horsepower+weight

qda_auto <-  qda(mpg01 ~ cylinders+displacement+horsepower+weight, data=auto_train)
#prediction
qda_auto_pred <-  predict(qda_auto,auto_test)
#
qda_auto_class <-  qda_auto_pred$class
#confusion matrix(QDA)
table(qda_auto_class,auto_test$mpg01)
##               
## qda_auto_class  0  1
##              0 43  5
##              1  6 44

A) QDA error rate is 11.22% same as the outcome of LDA. \[ QDA:: Accuracy\% = \frac{43+44}{98}= 88.77\% \] \[ QDA :: Error\% = 11.22\% \] (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?

logistic_auto= glm(mpg01~cylinders+displacement+horsepower+weight, data=auto_train, family=binomial)
summary(logistic_auto)
## 
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower + 
##     weight, family = binomial, data = auto_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4849  -0.1461   0.0589   0.3862   3.3940  
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  12.3086145  2.0425864   6.026 1.68e-09 ***
## cylinders    -0.3357736  0.4196765  -0.800  0.42367    
## displacement -0.0086694  0.0101218  -0.857  0.39172    
## horsepower   -0.0424586  0.0159688  -2.659  0.00784 ** 
## weight       -0.0018044  0.0008004  -2.254  0.02418 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 407.57  on 293  degrees of freedom
## Residual deviance: 156.50  on 289  degrees of freedom
## AIC: 166.5
## 
## Number of Fisher Scoring iterations: 7
auto_probs=predict(logistic_auto,auto_test,type="response")


auto_pred=rep(0,98)

auto_pred[auto_probs > .5]= 1

table(auto_pred,auto_test$mpg01 )
##          
## auto_pred  0  1
##         0 43  4
##         1  6 45

A) Logistic Regression seems to be the best with the predictors selected in (b) with the error rate of 10.2% \[ Logistic\ Regression :: Error\% = 10.2\% \]

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

#preparing the data frames with predictors selected in (b) for both test and train sets
#With standardizing the predictor
train_std <- scale(auto_train[ ,c("cylinders","displacement","weight","horsepower")])
test_std <- scale(auto_test[ ,c("cylinders","displacement","weight","horsepower")])

auto_train_x = data.frame(train_std[,c("cylinders","displacement","weight","horsepower")])
auto_test_x = data.frame(test_std[,c("cylinders","displacement","weight","horsepower")])

#Standardizing is needed as there are more than one predictor

set.seed(1)
auto_knn_pred=knn(auto_train_x,auto_test_x,auto_train$mpg01, k=1)
table(auto_knn_pred ,auto_test$mpg01)
##              
## auto_knn_pred  0  1
##             0 46  7
##             1  3 42

A) KNN with standardized predictors for K=1 the error rate is 10.2%, this is same as the logistic regression \[ KNN\ Regression\ K=1 :: Error\ Rate = 10.2\% \]

set.seed(1)
auto_knn_pred=knn(auto_train_x,auto_test_x,auto_train$mpg01, k=4)
table(auto_knn_pred ,auto_test$mpg01)
##              
## auto_knn_pred  0  1
##             0 43  3
##             1  6 46

A) KNN with standardized predictors for K=4 the error rate is 9.18%, this is better than K=1 and logistic regression \[ KNN\ Regression\ K=4 :: Error\ Rate = 9.18\% \]

set.seed(1)
auto_knn_pred=knn(auto_train_x,auto_test_x,auto_train$mpg01, k=6)
table(auto_knn_pred ,auto_test$mpg01)
##              
## auto_knn_pred  0  1
##             0 42  3
##             1  7 46

A) KNN with standardized predictors for K=6 the error rate goes back to 10.2% \[ KNN\ Regression\ K=6 :: Error\ Rate = 10.2\% \] KNN with K = 4 is the best classification model of all with the lowest error rate.

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

Step 1: Created a new qualitative variable crim01 to classify if the crime rate of a suburb is above or below the median

median_crim <- median(Boston$crim)

myBoston <- Boston %>% mutate(crim01 = if_else(crim > median_crim,1,0))

Step 2: Analysis of crim01 against other predictors

cor(myBoston$crim01,myBoston)
##           crim        zn     indus       chas       nox         rm       age
## [1,] 0.4093955 -0.436151 0.6032602 0.07009677 0.7232348 -0.1563718 0.6139399
##             dis       rad       tax   ptratio      black     lstat       medv
## [1,] -0.6163416 0.6197862 0.6087413 0.2535684 -0.3512109 0.4532627 -0.2630167
##      crim01
## [1,]      1

Looking at the correlation coefficients,below is the list of predictors which seem to have either positive or negative correlation with crim01:

  1. indus
  2. nox
  3. age
  4. dis
  5. rad
  6. tax

Step 3: Prepare training and test data sets

#Convert the classifier as factor for `crim01`
myBoston$crim01 = as.factor(myBoston$crim01)

set.seed(452)
bostn_cl = sample.split(myBoston$crim01, SplitRatio = 0.75)
bostn_train<-subset(myBoston,bostn_cl==TRUE)
bostn_test<-subset(myBoston,bostn_cl==FALSE)

Step 4: Performing Logistic Regression on crim01 using the predictors identified above(note that these predictors are not selected using a comprehensive model selection process

logistic_bostn = glm(crim01~indus+nox+age+dis+rad+tax, data=bostn_train, family=binomial)
summary(logistic_bostn)
## 
## Call:
## glm(formula = crim01 ~ indus + nox + age + dis + rad + tax, family = binomial, 
##     data = bostn_train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -1.90852  -0.33642  -0.01924   0.01005   2.63939  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -22.932193   4.063775  -5.643 1.67e-08 ***
## indus        -0.055904   0.043852  -1.275  0.20236    
## nox          38.474654   7.367672   5.222 1.77e-07 ***
## age           0.017979   0.009795   1.836  0.06641 .  
## dis           0.275872   0.168794   1.634  0.10218    
## rad           0.569926   0.128231   4.445 8.81e-06 ***
## tax          -0.007495   0.002555  -2.934  0.00335 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 526.79  on 379  degrees of freedom
## Residual deviance: 195.61  on 373  degrees of freedom
## AIC: 209.61
## 
## Number of Fisher Scoring iterations: 8
bostn_probs=predict(logistic_bostn,bostn_test,type="response")


bostn_pred=rep(0,126)

bostn_pred[bostn_probs > .5]= 1

table(bostn_pred,bostn_test$crim01 )
##           
## bostn_pred  0  1
##          0 56  4
##          1  7 59

A) H0: Predictor “nox” has no significant relationship with Direction or βnox = 0
Ha: Predictor “nox” has significant relationship with Direction or βnox ≠ 0 Significant level at 0.05, we can reject the null hypothesis for nox and similarly for rad and tax.

\[ Logistic Regression:: Error\ Rate = \frac{4+7}{126}= 8.73\% \] Error rate from the above model is impressive but in quest to explore other models we will try LDA,QDA and KNN as well

Step 5: Performing Logistic Regression on crim01 using the predictors identified as significant above

logistic_bostn1 = glm(crim01~nox+rad+tax, data=bostn_train, family=binomial)
summary(logistic_bostn1)
## 
## Call:
## glm(formula = crim01 ~ nox + rad + tax, family = binomial, data = bostn_train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -1.84055  -0.42604  -0.01928   0.00862   2.43579  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -17.867895   2.391692  -7.471 7.97e-14 ***
## nox          32.024376   4.508471   7.103 1.22e-12 ***
## rad           0.618906   0.123520   5.011 5.43e-07 ***
## tax          -0.007901   0.002354  -3.357 0.000789 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 526.79  on 379  degrees of freedom
## Residual deviance: 202.08  on 376  degrees of freedom
## AIC: 210.08
## 
## Number of Fisher Scoring iterations: 8
bostn_probs1=predict(logistic_bostn1,bostn_test,type="response")


bostn_pred1=rep(0,126)

bostn_pred1[bostn_probs1 > .5]= 1

table(bostn_pred1,bostn_test$crim01 )
##            
## bostn_pred1  0  1
##           0 60  7
##           1  3 56

Logistic Regression with only the significant terms has an improved low error rate as shown below: \[ Logistic\ Regression:: Error\ Rate = \frac{3+7}{126}= 7.93\% \] Step 6: Performing LDA using the significant terms

lda_bostn=lda(crim01 ~ nox + rad + tax ,data=bostn_train)

#prediction on test

lda_bostn_pred=predict(lda_bostn,bostn_test)

lda_bostn_class <- lda_bostn_pred$class

table(lda_bostn_class,bostn_test$crim01)
##                
## lda_bostn_class  0  1
##               0 63 26
##               1  0 37

LDA using the same significant predictors as discovered fitting the logistic regression, has an error rate of 20.83% \[ LDA:: Error\ Rate = \frac{26+0}{126}= 20.63\% \]

Step 7: Performing QDA using the significant terms

qda_bostn=qda(crim01 ~ nox + rad + tax ,data=bostn_train)

#prediction on test

qda_bostn_pred=predict(qda_bostn,bostn_test)

qda_bostn_class <- qda_bostn_pred$class

table(qda_bostn_class,bostn_test$crim01)
##                
## qda_bostn_class  0  1
##               0 62 26
##               1  1 37

QDA using the same significant predictors as discovered fitting the logistic regression, has an error rate of 21.43%. \[ LDA:: Error\ Rate = \frac{26+1}{126}= 21.43\% \] Step 8: Performing KNN using the significant terms

#preparing the data frames with predictors selected in (b) for both test and train sets
#With standardizing the predictor
train_std <- scale(bostn_train[ ,c("nox","rad","tax")])
test_std <- scale(bostn_test[ ,c("nox","rad","tax")])

bostn_train_x = data.frame(train_std[,c("nox","rad","tax")])
bostn_test_x = data.frame(test_std[,c("nox","rad","tax")])

#Standardizing is needed as there are more than one predictor

set.seed(1)
bostn_knn_pred=knn(bostn_train_x,bostn_test_x,bostn_train$crim01, k=1)
table(bostn_knn_pred ,bostn_test$crim01)
##               
## bostn_knn_pred  0  1
##              0 62  1
##              1  1 62

KNN Classifier with K=1 produces the error rate lowest so far at 1.59%, suspecting that there is over fitting \[ KNN\ K=1:: Error\ Rate = \frac{1+1}{126}= 1.59\% \]

Step 9: Trying KNN with K = 3

set.seed(1)
bostn_knn_pred=knn(bostn_train_x,bostn_test_x,bostn_train$crim01, k=3)
table(bostn_knn_pred ,bostn_test$crim01)
##               
## bostn_knn_pred  0  1
##              0 62  1
##              1  1 62

KNN Classifier with K=3 produces the same error rate which is the lowest so far at 1.59% \[ KNN\ K=3:: Error\ Rate = \frac{1+1}{126}= 1.59\% \] Conclusion:: After fitting different classification models in order to predict whether a given suburb has a crime rate above or below the median, I found that predictors(listed below) when modeled with KNN classifier with K = 1 or 3 has a very good prediction and low error rate.

  1. nox - nitrogen oxides concentration
  2. rad - index of accessibility to radial highways
  3. tax - full-value property-tax rate per \$10,000