library(class)
library(MASS)
library(ISLR2)
## 
## Attaching package: 'ISLR2'
## The following object is masked from 'package:MASS':
## 
##     Boston

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

(a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns? The minimums and maximums are the same for lag1-4 , the median values start to differ by a little bit in lag 4 and 5. The scatter plot also shows that the percentage returns stay constant throughout the year. Most of the returns stay between -5 to 5 percent throughout the years.

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  
##            
##            
##            
## 
par(mfrow = c(4,4))
plot(Weekly)

attach(Weekly)
plot(Lag1, Year)

plot(Lag5,Year)

(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? Lag2 is statistically significant

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

(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. The confusion matrix tells us how many correct or incorrect predictions our model produced. The model correctly predicted that the market would go up 557 times and correctly predicted that the market would go down 54 times.

LogR.prob <- predict(LogR, type = "response")
LogR.predict =rep("Down", length(LogR.prob))
LogR.predict[LogR.prob > 0.5] = "Up"
table(LogR.predict, Direction)
##             Direction
## LogR.predict Down  Up
##         Down   54  48
##         Up    430 557

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

train <- (Year < 2008)
weekly.2008 <- Weekly[!train,]
dim(weekly.2008)
## [1] 156   9
direction.2008 <- Direction[!train]
LogR.fit <- glm(Direction ~ Lag2, data=Weekly, family = binomial, subset = train)
LogR.fit.prob <- predict(LogR.fit, weekly.2008, type = "response")
LogR.fit.predict =rep("Down", length(LogR.fit.prob))
LogR.fit.predict[LogR.fit.prob > 0.5] = "Up"
table(LogR.fit.predict, direction.2008)
##                 direction.2008
## LogR.fit.predict Down Up
##             Down    7  5
##             Up     65 79

(e) Repeat (d) using LDA.

library(MASS)
LogR.lda <- lda(Direction ~ Lag2, data=Weekly, family = binomial, subset = train)
LogR.lda.prob <- predict(LogR.lda, weekly.2008)$class
table(LogR.lda.prob, direction.2008)
##              direction.2008
## LogR.lda.prob Down Up
##          Down    6  5
##          Up     66 79
mean(LogR.lda.prob == direction.2008)
## [1] 0.5448718

(f) Repeat (d) using QDA.

LogR.qda <- qda(Direction ~ Lag2, data=Weekly, family = binomial, subset = train)
LogR.qda.prob <- predict(LogR.qda, weekly.2008)$class
table(LogR.qda.prob, direction.2008)
##              direction.2008
## LogR.qda.prob Down Up
##          Down    0  0
##          Up     72 84
mean(LogR.qda.prob==direction.2008)
## [1] 0.5384615

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

library(class)
knn.train=cbind(Lag2[train])
knn.test=cbind(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
knn.pred=knn(knn.train,knn.test,train.Direction,k=1)
table(knn.pred,direction.2008)
##         direction.2008
## knn.pred Down Up
##     Down   32 38
##     Up     40 46
mean(knn.pred==direction.2008)
## [1] 0.5

(h) Repeat (d) using naive Bayes.

library(e1071)
nb.fit <- naiveBayes(Direction ~ Lag2 , data = Weekly, subset = train)
nb.class <- predict(nb.fit, weekly.2008)
table(nb.class, direction.2008)
mean(nb.class==direction.2008)
## [1] 0.5384615

(i) Which of these methods appears to provide the best results on this data? Linear discriminant analysis has the best results with a 54% prediction accuracy

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

train <- (Year < 2003)
weekly.2003 <- Weekly[!train,]
dim(weekly.2003)
## [1] 417   9
direction.2003 <- Direction[!train]

Using LDA

lda2 <- lda(Direction ~ Lag5, data=Weekly, family = binomial, subset = train)
lda.prob2 <- predict(lda2, weekly.2003)$class
table(lda.prob2, direction.2003)
##          direction.2003
## lda.prob2 Down  Up
##      Down    9  12
##      Up    174 222
mean(lda.prob2==direction.2003)
## [1] 0.5539568

Using KNN

knn.train2=cbind(Lag2[train])
knn.test2=cbind(Lag2[!train])
train.Direction2 =Direction[train]
set.seed(1)
knn.pred2=knn(knn.train2,knn.test2,train.Direction2,k=4)
table(knn.pred2,direction.2003)
##          direction.2003
## knn.pred2 Down  Up
##      Down   83  85
##      Up    100 149
mean(knn.pred2== direction.2003)
## [1] 0.5563549

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

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

library(ISLR2)
data("Auto")
summary(Auto)
##       mpg          cylinders      displacement     horsepower        weight    
##  Min.   : 9.00   Min.   :3.000   Min.   : 68.0   Min.   : 46.0   Min.   :1613  
##  1st Qu.:17.00   1st Qu.:4.000   1st Qu.:105.0   1st Qu.: 75.0   1st Qu.:2225  
##  Median :22.75   Median :4.000   Median :151.0   Median : 93.5   Median :2804  
##  Mean   :23.45   Mean   :5.472   Mean   :194.4   Mean   :104.5   Mean   :2978  
##  3rd Qu.:29.00   3rd Qu.:8.000   3rd Qu.:275.8   3rd Qu.:126.0   3rd Qu.:3615  
##  Max.   :46.60   Max.   :8.000   Max.   :455.0   Max.   :230.0   Max.   :5140  
##                                                                                
##   acceleration        year           origin                      name    
##  Min.   : 8.00   Min.   :70.00   Min.   :1.000   amc matador       :  5  
##  1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000   ford pinto        :  5  
##  Median :15.50   Median :76.00   Median :1.000   toyota corolla    :  5  
##  Mean   :15.54   Mean   :75.98   Mean   :1.577   amc gremlin       :  4  
##  3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000   amc hornet        :  4  
##  Max.   :24.80   Max.   :82.00   Max.   :3.000   chevrolet chevette:  4  
##                                                  (Other)           :365
library(ISLR2)
attach(Auto)
mpg01 <- ifelse(mpg > 22.75, 1 , 0)
Auto2 <- data.frame(Auto, mpg01)

(b) Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings. There is an association between cylinders and mpg, the cars that have an mpg less than 22.75 have cylinders between 6-8. If they have an mpg of more than 22.75 they are 4 cylinder vehicles. There is an association between horsepower and mpg, the cars that have an mpg less than 22.75 have horsepower between 100-150. If they have an mpg of more than 22.75 they have horsepower between 80-100. There is also an association between weight and mpg as well as acceleration and year.

par(mfrow = c(4,4))
plot(Auto2)

par(mfrow = c(3,3))
boxplot(cylinders ~ mpg01, data = Auto2)
boxplot(displacement ~ mpg01, data = Auto2)
boxplot(horsepower ~ mpg01, data = Auto2)
boxplot(weight ~ mpg01, data = Auto2)
boxplot(acceleration ~ mpg01, data = Auto2)
boxplot(year ~ mpg01, data = Auto2)

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

set.seed(1)
auto.train <- sample(1:dim(Auto2)[1], dim(Auto2)[1]*.75, rep=FALSE)
auto.test <- -auto.train
training_data<- Auto2[auto.train, ]
testing_data <- Auto2[auto.test, ]
mpg01.test <- mpg01[auto.test]

(d) Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in

auto.lda <- lda(mpg01 ~ cylinders, data = training_data)
auto.predict<- predict(auto.lda, testing_data)$class
table(auto.predict, mpg01.test)
##             mpg01.test
## auto.predict  0  1
##            0 45  3
##            1  8 42

(b). What is the test error of the model obtained?

mean(auto.predict != mpg01.test)
## [1] 0.1122449

(e) Perform QDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in

auto.qda <- qda(mpg01 ~ cylinders, data = training_data)
auto.qda.prob <- predict(auto.qda, testing_data)$class
table(auto.qda.prob, mpg01.test)
##              mpg01.test
## auto.qda.prob  0  1
##             0 45  3
##             1  8 42

(b). What is the test error of the model obtained?

mean(auto.qda.prob != mpg01.test)
## [1] 0.1122449

(f) Perform logistic regression on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in

LogR.auto<- glm(mpg01 ~ cylinders, data=training_data, family = binomial)
LogR.auto.prob <- predict(LogR.auto, training_data, type = "response")
LogR.auto.predict <- predict(LogR.auto, testing_data)
table(LogR.auto.predict, mpg01.test)
##                    mpg01.test
## LogR.auto.predict    0  1
##   -4.34469714129446 25  0
##   -1.20201612021664 20  3
##   0.369324390322266  1  0
##   1.94066490086117   7 41
##   3.51200541140008   0  1

(b). What is the test error of the model obtained?

mean(LogR.auto.predict != mpg01.test)
## [1] 1

(g) Perform naive Bayes on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in

library(e1071)
nb.auto <- naiveBayes(mpg01 ~ cylinders , data = training_data)
nb.class.auto <- predict(nb.auto, testing_data)
table(nb.class.auto, mpg01.test)
##              mpg01.test
## nb.class.auto  0  1
##             0 45  3
##             1  8 42

(b). What is the test error of the model obtained?

mean(nb.class.auto != mpg01.test)
## [1] 0.1122449

(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

library(class)
attach(Auto2)
## The following object is masked _by_ .GlobalEnv:
## 
##     mpg01
## The following objects are masked from Auto:
## 
##     acceleration, cylinders, displacement, horsepower, mpg, name,
##     origin, weight, year
knn.train.X <-cbind(cylinders,horsepower)[auto.train,]
knn.test.X <-cbind(cylinders, horsepower)[auto.test,]
knn.train.mpg01 <- mpg01[auto.train]
set.seed(1)
knn.pred.auto <- knn(knn.train.X, knn.test.X, knn.train.mpg01, k = 5)
mean(knn.pred.auto != mpg01.test)
## [1] 0.1428571
knn.train.X <-cbind(cylinders,horsepower)[auto.train,]
knn.test.X <-cbind(cylinders, horsepower)[auto.test,]
knn.train.mpg01 <- mpg01[auto.train]
set.seed(1)
knn.pred.auto <- knn(knn.train.X, knn.test.X, knn.train.mpg01, k = 8)
mean(knn.pred.auto != mpg01.test)
## [1] 0.1530612
knn.train.X <-cbind(cylinders,horsepower)[auto.train,]
knn.test.X <-cbind(cylinders, horsepower)[auto.test,]
knn.train.mpg01 <- mpg01[auto.train]
set.seed(1)
knn.pred.auto <- knn(knn.train.X, knn.test.X, knn.train.mpg01, k = 1)
mean(knn.pred.auto != mpg01.test)
## [1] 0.1326531

(b). What test errors do you obtain? Which value of K seems to perform the best on this data set? With K= 5 there is test error of .14, K=8 has a test error rate of .15, and K=1 has a test error rate of .13. The K=1 value performs the best with the data.

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

attach(Boston)
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          lstat      
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   : 1.73  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.: 6.95  
##  Median : 5.000   Median :330.0   Median :19.05   Median :11.36  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :12.65  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:16.95  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :37.97  
##       medv      
##  Min.   : 5.00  
##  1st Qu.:17.02  
##  Median :21.20  
##  Mean   :22.53  
##  3rd Qu.:25.00  
##  Max.   :50.00
crim2 <- ifelse(crim > .25651, 1 , 0)
boston2 <- data.frame(Boston, crim2)
set.seed(3)
boston2.train <- sample(1:dim(boston2)[1], dim(boston2)[1]*.65, rep=FALSE)
boston2.test <- -boston2.train
training_boston2<- boston2[boston2.train, ]
testing_boston2 <- boston2[boston2.test, ]
crim2.test <- crim2[boston2.test]

using LDA

boston2.lda <- lda(crim2 ~ medv, data = boston2)
boston2.predict <- predict(boston2.lda, boston2)$class
table(boston2.predict, crim2)
##                crim2
## boston2.predict   0   1
##               0 139  70
##               1 114 183
mean(boston2.predict != crim2)
## [1] 0.3636364

Using Bayes

nb.boston2 <- naiveBayes(crim2 ~ age , data = boston2)
nb.class.boston2 <- predict(nb.boston2, boston2)
table(nb.class.boston2, crim2)
##                 crim2
## nb.class.boston2   0   1
##                0 177  31
##                1  76 222
mean(nb.class.boston2 != crim2)
## [1] 0.2114625