Libraries

library(ISLR2)
library(MASS)
library(class)
library(e1071)
library(dplyr)
library(ggplot2)

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

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

The only pattern that is obvious is between volume and year.

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

Lag2 is statistically significant.

  1. 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.
prob = predict(logreg, type="response")
pred = rep("Down", 1089)
pred[prob > 0.5]="Up"
table(pred, Weekly$Direction)
##       
## pred   Down  Up
##   Down   54  48
##   Up    430 557
mean(pred == Weekly$Direction)
## [1] 0.5610652

That the model was only accurate in predicting the direction 56.1%

  1. 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 < 2009)
fit= glm(Direction ~ Lag2, data=Weekly, subset=train, family="binomial")
prob= predict(fit, Weekly[!train, ], type="response")
pred= rep("Down", dim(Weekly[!train, ])[1])
pred[prob > .5]= "Up"
table(pred, Weekly[!train, ]$Direction)
##       
## pred   Down Up
##   Down    9  5
##   Up     34 56
mean(pred == Weekly[!train, ]$Direction)
## [1] 0.625
  1. Repeat (d) using LDA.
lfit = lda(Direction ~ Lag2, data=Weekly, subset=train)
lpred = predict(lfit, Weekly[!train, ])
table(lpred$class, Weekly[!train, ]$Direction)
##       
##        Down Up
##   Down    9  5
##   Up     34 56
mean(lpred$class == Weekly[!train, ]$Direction)
## [1] 0.625
  1. Repeat (d) using QDA.
qfit = qda(Direction ~ Lag2, data = Weekly, subset = train)
qpred = predict(qfit, Weekly[!train, ])
table(qpred$class, Weekly[!train, ]$Direction)
##       
##        Down Up
##   Down    0  0
##   Up     43 61
mean(qpred$class == Weekly[!train, ]$Direction)
## [1] 0.5865385
  1. Repeat (d) using KNN with K = 1.
train.X= data.frame(Weekly[train, ]$Lag2)
test.X= data.frame(Weekly[!train, ]$Lag2)
train.Direction= Weekly[train, ]$Direction
set.seed(1)
knnpred= knn(train.X, test.X, train.Direction, k = 1)
table(knnpred, Weekly[!train, ]$Direction)
##        
## knnpred Down Up
##    Down   21 30
##    Up     22 31
mean(knnpred == Weekly[!train, ]$Direction)
## [1] 0.5
  1. Repeat (d) using naive Bayes.
nbfit= naiveBayes(Direction~Lag2, data=Weekly, subset=train)
nbclass= predict(nbfit , Weekly[!train , ])
table(nbclass , Weekly[!train, ]$Direction)
##        
## nbclass Down Up
##    Down    0  0
##    Up     43 61
mean(nbclass == Weekly[!train, ]$Direction)
## [1] 0.5865385
  1. Which of these methods appears to provide the best results on this data?

The logical regression and linear discriminant analysis provided the best prediction accuracy at 62.5%. The quadratic discriminant analysis and naive bayes were after that at 58.7%. The KNN was last with a prediction accuracy of 50%.

  1. 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.
knnpred= knn(train.X, test.X, train.Direction, k = 3)
table(knnpred, Weekly[!train, ]$Direction)
##        
## knnpred Down Up
##    Down   16 19
##    Up     27 42
mean(knnpred == Weekly[!train, ]$Direction)
## [1] 0.5576923

Using a K = 3 improves the prediction accuracy from 50% to 55.8%, but still not as good as the other methods used.

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

  1. 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$origin= factor(Auto$origin)
mpg01 = rep(0, dim(Auto)[1])
mpg01[Auto$mpg > median(Auto$mpg)] = 1
Auto = data.frame(Auto, mpg01)
  1. 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.
plot(factor(Auto$mpg01), Auto$cylinders)

plot(factor(Auto$mpg01), Auto$displacement)

plot(factor(Auto$mpg01), Auto$horsepower)

plot(factor(Auto$mpg01), Auto$weight)

plot(factor(Auto$mpg01), Auto$acceleration)

plot(factor(Auto$mpg01), Auto$year)

plot(factor(Auto$mpg01), Auto$origin)

plot(Auto$cylinders , Auto$mpg01)

plot(Auto$displacement, Auto$mpg01)

plot(Auto$horsepower, Auto$mpg01)

plot(Auto$weight, Auto$mpg01)

plot(Auto$acceleration, Auto$mpg01)

plot(Auto$year, Auto$mpg01)

plot(Auto$origin, Auto$mpg01)

After looking at some boxplots and scatterplots, the best indicators in predicting the mpg01 would be cylinders, displacement, horsepower, weight, year, and origin.

  1. Split the data into a training set and a test set.
set.seed(1)
rows= sample(x=nrow(Auto), size=.75*nrow(Auto))
trainset= Auto[rows, ]
testset= Auto[-rows, ]
  1. 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?
lfit= lda(mpg01~cylinders+displacement+horsepower+weight+year+origin, data=trainset)
lpred= predict(lfit, testset)
table(lpred$class, testset$mpg01)
##    
##      0  1
##   0 41  0
##   1 12 45
1-mean(lpred$class==testset$mpg01)
## [1] 0.122449

There was a 13.2% test error when using the LDA method.

  1. 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?
qfit= qda(mpg01~cylinders+displacement+horsepower+weight+year+origin, data=trainset)
qpred= predict(qfit, testset)
table(qpred$class, testset$mpg01)
##    
##      0  1
##   0 42  2
##   1 11 43
1-mean(qpred$class==testset$mpg01)
## [1] 0.1326531

There was a 11.2% test error when using the QDA method.

  1. 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?
logreg= glm(mpg01~cylinders+displacement+horsepower+weight+year+origin, data=trainset, family="binomial")
loprob= predict(logreg, testset, type="response")
lopred= rep(0, dim(testset)[1])
lopred[loprob>.5]=1
table(lopred, testset$mpg01)
##       
## lopred  0  1
##      0 45  1
##      1  8 44
1-mean(lopred==testset$mpg01)
## [1] 0.09183673

There was a 9.2% test error with the logical regression method.

  1. 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?
nbfit= naiveBayes(mpg01~cylinders+displacement+horsepower+weight+year+origin, data=trainset)
nbclass= predict(nbfit , testset)
table(nbclass, testset$mpg01)
##        
## nbclass  0  1
##       0 44  2
##       1  9 43
1-mean(nbclass==testset$mpg01)
## [1] 0.1122449

There was a 12.2% test error using the naive bayes method.

  1. 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?
v= which(names(trainset)%in%c("cylinders", "displacement", "horsepower", "weight", "year", "origin"))
set.seed(1)
knnpred= knn(trainset[, v], testset[, v], trainset$mpg01, k = 1)
table(knnpred, testset$mpg01)
##        
## knnpred  0  1
##       0 43  4
##       1 10 41
1-mean(knnpred==testset$mpg01)
## [1] 0.1428571
knnpred= knn(trainset[, v], testset[, v], trainset$mpg01, k = 3)
table(knnpred, testset$mpg01)
##        
## knnpred  0  1
##       0 44  3
##       1  9 42
1-mean(knnpred==testset$mpg01)
## [1] 0.122449
knnpred= knn(trainset[, v], testset[, v], trainset$mpg01, k = 5)
table(knnpred, testset$mpg01)
##        
## knnpred  0  1
##       0 45  5
##       1  8 40
1-mean(knnpred==testset$mpg01)
## [1] 0.1326531
knnpred= knn(trainset[, v], testset[, v], trainset$mpg01, k = 7)
table(knnpred, testset$mpg01)
##        
## knnpred  0  1
##       0 43  3
##       1 10 42
1-mean(knnpred==testset$mpg01)
## [1] 0.1326531

I used the KNN method with 4 different values for K and the best test error was when k=3, which was 12.2%.

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

Boston$crim1= rep("No", dim(Boston)[1])
Boston$crim1[Boston$crim>median(Boston$crim)]="Yes"

set.seed(1)
rows= sample(x=nrow(Boston), size=.75*nrow(Boston))
trainset= Boston[rows, ]
testset= Boston[-rows, ]

fit= glm(as.factor(crim1) ~ zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, data=trainset, family="binomial")
prob= predict(fit, testset, type="response")
pred= rep("No", dim(testset)[1])
pred[prob > .5]= "Yes"
table(pred, testset$crim1)
##      
## pred  No Yes
##   No  51   5
##   Yes 12  59
1-mean(pred == testset$crim1)
## [1] 0.1338583
lfit= lda(as.factor(crim1) ~ zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, data=trainset)
lpred= predict(lfit, testset)
table(lpred$class, testset$crim1)
##      
##       No Yes
##   No  59  15
##   Yes  4  49
1-mean(lpred$class==testset$crim1)
## [1] 0.1496063
nbfit= naiveBayes(as.factor(crim1) ~ zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, data=trainset)
nbclass= predict(nbfit , testset)
table(nbclass, testset$crim1)
##        
## nbclass No Yes
##     No  59  18
##     Yes  4  46
1-mean(nbclass==testset$crim1)
## [1] 0.1732283

Using logical regression I got a test error of 13.3%. The LDA got a test error of 14.9%. The naive bayes got a test error of 17.3%. So, out of the three methods the logical regression was the best.