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.
library(ISLR2)
library(MASS)##
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
##
## Boston
library(corrplot)## corrplot 0.92 loaded
library(class)
library(e1071)(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
##
##
##
##
plot(Weekly)(b) Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically significant? If so, which ones?
“Yes, the intercept and lag 2 are statistically significant, due to the fact that they have a p-value < 0.05, therefore less significant.”
attach(Weekly)
Weekly.fit<-glm(Direction~Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, family = binomial)
summary(Weekly.fit)##
## 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 model here tends to predict market Up trends better, so on average, the responses are shown to be predicted correctly 56% of the time."
Weekly.probs = predict(Weekly.fit, type = "response")
Weekly.pred = rep("Down", length(Weekly.probs))
Weekly.pred[Weekly.probs > 0.5] <- "Up"
table(Weekly.pred, Weekly$Direction)##
## Weekly.pred Down Up
## Down 54 48
## Up 430 557
mean(Weekly.pred == Weekly$Direction)## [1] 0.5610652
(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 < 2009)
Weekly.test <- Weekly[!train,]
Weekly.fit <- glm(Direction~Lag2, data = Weekly,family = binomial, subset = train)
logWeekly.prob= predict(Weekly.fit, Weekly.test, type = "response")
logWeekly.pred = rep("Down", length(logWeekly.prob))
logWeekly.pred[logWeekly.prob > 0.5] = "Up"
Direction.test = Direction[!train]
table(logWeekly.pred, Direction.test)## Direction.test
## logWeekly.pred Down Up
## Down 9 5
## Up 34 56
mean(logWeekly.pred == Direction.test)## [1] 0.625
(e) Repeat (d) using LDA.
Weekly.LDA.fit <- lda(Direction~Lag2, data = Weekly,family = binomial, subset = train)
Weekly.LDA.pred <- predict(Weekly.LDA.fit, Weekly.test)
table(Weekly.LDA.pred$class, Direction.test)## Direction.test
## Down Up
## Down 9 5
## Up 34 56
mean(Weekly.LDA.pred$class == Direction.test)## [1] 0.625
(f) Repeat (d) using QDA.
Weekly.QDA.fit = qda(Direction ~ Lag2, data = Weekly, subset = train)
Weekly.QDA.pred = predict(Weekly.QDA.fit, Weekly.test)$class
table(Weekly.QDA.pred, Direction.test)## Direction.test
## Weekly.QDA.pred Down Up
## Down 0 0
## Up 43 61
mean(Weekly.QDA.pred==Direction.test)## [1] 0.5865385
(g) Repeat (d) using KNN with K = 1.
Week.train=as.matrix(Lag2[train])
Week.test=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
Week.KNN.pred=knn(Week.train,Week.test,train.Direction,k=1)
table(Week.KNN.pred,Direction.test)## Direction.test
## Week.KNN.pred Down Up
## Down 21 30
## Up 22 31
(h) Repeat (d) using naive Bayes.
Weekly.NaiveBayes.fit = naiveBayes(Direction~Lag2, data = Weekly, subset = train)
Weekly.NaiveBayes.pred = predict(Weekly.NaiveBayes.fit,Weekly.test)
table(Weekly.NaiveBayes.pred, Direction.test)## Direction.test
## Weekly.NaiveBayes.pred Down Up
## Down 0 0
## Up 43 61
mean(Weekly.NaiveBayes.pred==Direction.test)## [1] 0.5865385
(i) Which of these methods appears to provide the best results on this data?
"In this specific case, Logistic Regression and Linear Discriminant Analysis gave the best result due to the 62.5% of the observations being correctly classified. On the other hand, the KKN method gave the worst results due to the 50% of the observations being correctly classified."
(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.
Weekly.fit <- glm(Direction~Lag2:Lag5+Lag2, data = Weekly,family = binomial, subset = train)
logWeekly.prob= predict(Weekly.fit, Weekly.test, type = "response")
logWeekly.pred = rep("Down", length(logWeekly.prob))
logWeekly.pred[logWeekly.prob > 0.5] = "Up"
Direction.test = Direction[!train]
table(logWeekly.pred, Direction.test)## Direction.test
## logWeekly.pred Down Up
## Down 9 4
## Up 34 57
mean(logWeekly.pred == Direction.test)## [1] 0.6346154
LDA [63%]
Weekly.LDA.fit <- lda(Direction~Lag2:Lag5+Lag2, data = Weekly,family = binomial, subset = train)
Weekly.LDA.pred <- predict(Weekly.LDA.fit, Weekly.test)
table(Weekly.LDA.pred$class, Direction.test)## Direction.test
## Down Up
## Down 9 4
## Up 34 57
mean(Weekly.LDA.pred$class == Direction.test)## [1] 0.6346154
QDA [50%]
Weekly.QDA.fit = qda(Direction ~ Lag2:Lag5+Lag2, data = Weekly, subset = train)
Weekly.QDA.pred = predict(Weekly.QDA.fit, Weekly.test)$class
table(Weekly.QDA.pred, Direction.test)## Direction.test
## Weekly.QDA.pred Down Up
## Down 5 13
## Up 38 48
mean(Weekly.QDA.pred==Direction.test)## [1] 0.5096154
KNN
Week.train=as.matrix(Lag2[train])
Week.test=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
Week.KNN.pred=knn(Week.train,Week.test,train.Direction,k=15)
table(Week.KNN.pred,Direction.test)## Direction.test
## Week.KNN.pred Down Up
## Down 20 20
## Up 23 41
Naive Bayes [48%]
Weekly.NaiveBayes.fit = naiveBayes(Direction~Lag5, data = Weekly, subset = train)
Weekly.NaiveBayes.pred = predict(Weekly.NaiveBayes.fit,Weekly.test)
table(Weekly.NaiveBayes.pred, Direction.test)## Direction.test
## Weekly.NaiveBayes.pred Down Up
## Down 2 13
## Up 41 48
mean(Weekly.NaiveBayes.pred==Direction.test)## [1] 0.4807692
detach(Weekly)"In all of these instances, LDA had the best prediction rate of 63% after testing all different methods."
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.
library(ISLR)## Warning: package 'ISLR' was built under R version 4.2.3
##
## Attaching package: 'ISLR'
## The following objects are masked from 'package:ISLR2':
##
## Auto, Credit
library(tibble)
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
(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.
attach(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
Auto <- as_tibble(ISLR::Auto)
mpg01 <- Auto %>%
mutate(mpg01 = ifelse(mpg > median(mpg), 1, 0))(b) Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings
corrplot(cor(Auto[,-9]), method="circle")(c) Split the data into a training set and a test set.
train <- (mpg01$year %% 2 == 0)
train.auto <- mpg01[train,]
test.auto <- mpg01[-train,](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?
auto.LDA.fit <- lda(mpg01~displacement+horsepower+weight+year+cylinders+origin, data=train.auto)
auto.LDA.pred <- predict(auto.LDA.fit, test.auto)
table(auto.LDA.pred$class, test.auto$mpg01)##
## 0 1
## 0 169 7
## 1 26 189
mean(auto.LDA.pred$class != test.auto$mpg01)## [1] 0.08439898
(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?
"The test error is 9.97%"
auto.QDA.fit <- qda(mpg01~displacement+horsepower+weight+year+cylinders+origin, data=train.auto)
auto.QDA.pred <- predict(auto.QDA.fit, test.auto)
table(auto.QDA.pred$class, test.auto$mpg01)##
## 0 1
## 0 176 20
## 1 19 176
mean(auto.QDA.pred$class != test.auto$mpg01)## [1] 0.09974425
(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?
"The test error is 8.4%"
auto.fit<-glm(mpg01~displacement+horsepower+weight+year+cylinders+origin, data=train.auto,family=binomial)
auto.probs = predict(auto.fit, test.auto, type = "response")
auto.pred = rep(0, length(auto.probs))
auto.pred[auto.probs > 0.5] = 1
table(auto.pred, test.auto$mpg01)##
## auto.pred 0 1
## 0 174 12
## 1 21 184
mean(auto.pred != test.auto$mpg01)## [1] 0.08439898
(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?
"The test error is 9.97%"
auto.NaiveBayes.fit <- naiveBayes(mpg01~displacement+horsepower+weight+year+cylinders+origin, data=train.auto)
auto.NaiveBayes.pred <- predict(auto.NaiveBayes.fit, test.auto)
table(auto.NaiveBayes.pred, test.auto$mpg01)##
## auto.NaiveBayes.pred 0 1
## 0 171 15
## 1 24 181
mean(auto.NaiveBayes.pred != test.auto$mpg01)## [1] 0.09974425
(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?
The test errors are:
K1 = 7%
K4 = 13%
K8 = 12%
attach(Auto)## The following objects are masked from Auto (pos = 3):
##
## acceleration, cylinders, displacement, horsepower, mpg, name,
## origin, weight, year
train.K= cbind(displacement,horsepower,weight,cylinders)[train,]
test.K=cbind(displacement,horsepower,weight,cylinders)[-train,]
set.seed(1)
autok.pred=knn(train.K,test.K,train.auto$mpg01,k=1)
mean(autok.pred != test.auto$mpg01)## [1] 0.07161125
autok.pred=knn(train.K,test.K,train.auto$mpg01,k=4)
mean(autok.pred != test.auto$mpg01)## [1] 0.1278772
autok.pred=knn(train.K,test.K,train.auto$mpg01,k=8)
mean(autok.pred != test.auto$mpg01)## [1] 0.1227621
detach(Auto)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.
summary(Boston)## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08205 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 black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
attach(Boston)Binary Crim Variable
Crime1 <- rep(0, length(crim))
Crime1[crim > median(crim)] <- 1
Boston= data.frame(Boston,Crime1)
train = 1:(dim(Boston)[1]/2)
test = (dim(Boston)[1]/2 + 1):dim(Boston)[1]
Boston.train = Boston[train, ]
Boston.test = Boston[test, ]
Crime1.test = Crime1[test]
corrplot(cor(Boston), method="circle")Logistic Regression “The test error is 9.5%”
set.seed(1)
Boston.fit <-glm(Crime1~ indus+nox+age+rad+tax, data=Boston.train,family=binomial)
Boston.probs = predict(Boston.fit, Boston.test, type = "response")
Boston.pred = rep(0, length(Boston.probs))
Boston.pred[Boston.probs > 0.5] = 1
table(Boston.pred, Crime1.test)## Crime1.test
## Boston.pred 0 1
## 0 72 6
## 1 18 157
mean(Boston.pred != Crime1.test)## [1] 0.09486166
LDA “The test error is 10.7%”
Boston.LDA.fit <-lda(Crime1~ indus+nox+age+rad+tax, data=Boston.train,family=binomial)
Boston.LDA.pred = predict(Boston.LDA.fit, Boston.test)
table(Boston.LDA.pred$class, Crime1.test)## Crime1.test
## 0 1
## 0 81 18
## 1 9 145
mean(Boston.LDA.pred$class != Crime1.test)## [1] 0.1067194
Naive Bayes “The test error is 10.7%”
Boston.NaiveBayes.fit <- naiveBayes(Crime1~ indus+nox+age+rad+tax, data=Boston.train)
Boston.NaiveBayes.pred <- predict(Boston.NaiveBayes.fit, Boston.test)
table(Boston.NaiveBayes.pred, Boston.test$Crime1)##
## Boston.NaiveBayes.pred 0 1
## 0 81 18
## 1 9 145
mean(Boston.NaiveBayes.pred != Boston.test$Crime1)## [1] 0.1067194
KNN “The test error is 84.6%”
train.K=cbind(indus,nox,age,rad,tax)[train,]
test.K=cbind(indus,nox,age,rad,tax)[test,]
Bosknn.pred=knn(train.K, test.K, Crime1.test, k=1)
table(Bosknn.pred,Crime1.test)## Crime1.test
## Bosknn.pred 0 1
## 0 31 155
## 1 59 8
mean(Bosknn.pred != Crime1.test)## [1] 0.8458498
KNN 2 “The test error is 25.7%”
train.K=cbind(indus,nox,age,rad,tax)[train,]
test.K=cbind(indus,nox,age,rad,tax)[test,]
Bosknn.pred=knn(train.K, test.K, Crime1.test, k=50)
table(Bosknn.pred,Crime1.test)## Crime1.test
## Bosknn.pred 0 1
## 0 38 13
## 1 52 150
mean(Bosknn.pred != Crime1.test)## [1] 0.256917
…