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.
library(ISLR)
library(MASS)
library(tidyverse)
attach(Weekly)
set.seed(42)
names(Weekly)
## [1] "Year" "Lag1" "Lag2" "Lag3" "Lag4" "Lag5"
## [7] "Volume" "Today" "Direction"
dim(Weekly)
## [1] 1089 9
(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[,-9])
## 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)
There is no discernible pattern in the
Lag predictors. We can see that Volume increased over time and that Direction has a binary response.
(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?
fit_glm <- glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume,data=Weekly,family=binomial)
summary(fit_glm)
##
## 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
Of the six predictors, only Lag2 appears to be 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.
The confusion matrix is showing that the percentage of correct and incorrect responses. For the correct response percentage, we use the upper left (54) and add it to the bottom right (557) then divide it by all resources (1089). This will give us a correct response percentage of ~56.1%. We can then subtract 100 from 56.1 to obtain the percentage of incorrect responses ~43.9%.
table(glm_pred,Direction)
## Direction
## glm_pred Down Up
## Down 54 48
## Up 430 557
mean(glm_pred==Direction)
## [1] 0.5610652
mean(glm_pred!=Direction)
## [1] 0.4389348
(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).
This will give us a correct response percentage of 62.5% and incorrect response percentage of 37.5%.
table(glm_pred2,direction_8)
## direction_8
## glm_pred2 Down Up
## Down 9 5
## Up 34 56
mean(glm_pred2==direction_8)
## [1] 0.625
mean(glm_pred2!=direction_8)
## [1] 0.375
(e) Repeat (d) using LDA. LDA performs similar to the GLM as it produced a correct response percentage of 62.5% and incorrect response percentage of 37.5%.
ldafit <- lda(Direction~Lag2,data=Weekly,subset=train)
lda_pred <- predict(ldafit, weekly_8)
names(lda_pred)
## [1] "class" "posterior" "x"
lda_class=lda_pred$class
table(lda_class,direction_8)
## direction_8
## lda_class Down Up
## Down 9 5
## Up 34 56
mean(lda_class==direction_8)
## [1] 0.625
mean(lda_class!=direction_8)
## [1] 0.375
(f) Repeat (d) using QDA.
QDA dropped the correct response percentage to ~58.7% and incorrect response percentage to ~41.3%.
qdafit <- qda(Direction~Lag2,data=Weekly,subset=train)
qda_pred <- predict(qdafit, weekly_8)
names(qda_pred)
## [1] "class" "posterior"
qda_class=qda_pred$class
table(qda_class,direction_8)
## direction_8
## qda_class Down Up
## Down 0 0
## Up 43 61
mean(qda_class==direction_8)
## [1] 0.5865385
mean(qda_class!=direction_8)
## [1] 0.4134615
(g) Repeat (d) using KNN with K = 1. the KNN dropped the correct response percentage even further to 50% and incorrect response percentage to 50%.
library(class)
## Warning: package 'class' was built under R version 3.6.3
Xtrain = as.matrix(Lag2[train])
Xtest = as.matrix(Lag2[!train])
train.Direction = Direction[train]
knn_pred = knn(Xtrain, Xtest, train.Direction, k = 1)
table(knn_pred, direction_8)
## direction_8
## knn_pred Down Up
## Down 21 30
## Up 22 31
mean(knn_pred == direction_8)
## [1] 0.5
mean(knn_pred != direction_8)
## [1] 0.5
(h) Which of these methods appears to provide the best results on this data? Both GLM and LDA have very similar error rates and performed the best.
mean(glm_pred2!= direction_8)
## [1] 0.375
mean(lda_class!= direction_8)
## [1] 0.375
mean(qda_class!= direction_8)
## [1] 0.4134615
mean(knn_pred != direction_8)
## [1] 0.5
(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.
fit_glm2 <- glm(Direction~Lag2:Lag4,data=Weekly,family=binomial, subset=train)
glm_probs2 <- predict(fit_glm2,weekly_8,type="response")
glm_pred2 <- rep("Down",length(glm_probs2))
glm_pred2[glm_probs2>.5]="Up"
table(glm_pred2,direction_8)
## direction_8
## glm_pred2 Down Up
## Down 1 4
## Up 42 57
mean(glm_pred2==direction_8)
## [1] 0.5576923
mean(glm_pred2!=direction_8)
## [1] 0.4423077
fit_glm2 <- glm(Direction~log(Lag2),data=Weekly,family=binomial, subset=train)
## Warning in log(Lag2): NaNs produced
glm_probs2 <- predict(fit_glm2,weekly_8,type="response")
## Warning in log(Lag2): NaNs produced
glm_pred2 <- rep("Down",length(glm_probs2))
glm_pred2[glm_probs2>.5]="Up"
table(glm_pred2,direction_8)
## direction_8
## glm_pred2 Down Up
## Down 21 30
## Up 22 31
mean(glm_pred2==direction_8)
## [1] 0.5
mean(glm_pred2!=direction_8)
## [1] 0.5
Xtrain = as.matrix(Lag2[train])
Xtest = as.matrix(Lag2[!train])
train.Direction = Direction[train]
knn_pred = knn(Xtrain, Xtest, train.Direction, k = 10)
table(knn_pred, direction_8)
## direction_8
## knn_pred Down Up
## Down 17 22
## Up 26 39
mean(knn_pred == direction_8)
## [1] 0.5384615
mean(knn_pred != direction_8)
## [1] 0.4615385
Xtrain = as.matrix(Lag2[train])
Xtest = as.matrix(Lag2[!train])
train.Direction = Direction[train]
knn_pred = knn(Xtrain, Xtest, train.Direction, k = 100)
table(knn_pred, direction_8)
## direction_8
## knn_pred Down Up
## Down 9 12
## Up 34 49
mean(knn_pred == direction_8)
## [1] 0.5576923
mean(knn_pred != direction_8)
## [1] 0.4423077
ldafit <- lda(Direction~sqrt(abs(Lag2)),data=Weekly,subset=train)
lda_pred <- predict(ldafit, weekly_8)
names(lda_pred)
## [1] "class" "posterior" "x"
lda_class=lda_pred$class
table(lda_class,direction_8)
## direction_8
## lda_class Down Up
## Down 0 0
## Up 43 61
mean(lda_class==direction_8)
## [1] 0.5865385
mean(lda_class!=direction_8)
## [1] 0.4134615
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.
attach(Auto)
## The following object is masked from package:ggplot2:
##
## mpg
names(Auto)
## [1] "mpg" "cylinders" "displacement" "horsepower" "weight"
## [6] "acceleration" "year" "origin" "name"
dim(Auto)
## [1] 392 9
(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(dplyr)
set.seed(42)
dt_1 <- Auto %>% data.frame()
# head(dt_1)
dt_1$origin <- as.factor(dt_1$origin)
med <- median((dt_1$mpg))
dt_1$mpg0_1 <- ifelse(dt_1$mpg > med, 1, 0)
mpg0_1 <- dt_1$mpg0_1
dt_1$mpg0_1 <- as.factor(dt_1$mpg0_1)
(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. Looking at all numeric features, except mpg, I notice displacement, horsepower, and year may be the most useful when predicting mpg01.
ggplot(dt_1, aes(mpg0_1,displacement)) +
geom_boxplot()
ggplot(dt_1, aes(mpg0_1,cylinders)) +
geom_boxplot()
ggplot(dt_1, aes(mpg0_1,horsepower)) +
geom_boxplot()
ggplot(dt_1, aes(mpg0_1,weight)) +
geom_boxplot()
ggplot(dt_1, aes(mpg0_1,acceleration)) +
geom_boxplot()
ggplot(dt_1, aes(mpg0_1,year)) +
geom_boxplot()
(c) Split the data into a training set and a test set.
train <- (year%%2 == 0)
test <- !train
Xtrain <- data.frame(dt_1[train,])
Xtest <- data.frame(dt_1[test,])
Ytest <- mpg0_1[test]
(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?
The error rate is ~12.1%
lda_mod1 <- lda(mpg0_1~displacement+horsepower+acceleration, data = Xtrain)
pred_lda_mod1 <- predict(lda_mod1, Xtest)
class_lda_mod1 <- pred_lda_mod1$class
table(class_lda_mod1, Ytest)
## Ytest
## class_lda_mod1 0 1
## 0 84 6
## 1 16 76
mean(class_lda_mod1!=Ytest)
## [1] 0.1208791
(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 error rate is ~11.5%
qda_mod1 <- qda(mpg0_1~displacement+horsepower+acceleration, data = Xtrain)
pred_qda_mod1 <- predict(qda_mod1, Xtest)
class_qda_mod1 <- pred_qda_mod1$class
table(class_qda_mod1, Ytest)
## Ytest
## class_qda_mod1 0 1
## 0 84 5
## 1 16 77
mean(class_qda_mod1!=Ytest)
## [1] 0.1153846
(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 error rate is ~13.2%
glm_mod1 <- glm(mpg0_1~displacement+horsepower+acceleration, data = Xtrain, family = binomial)
summary(glm_mod1)
##
## Call:
## glm(formula = mpg0_1 ~ displacement + horsepower + acceleration,
## family = binomial, data = Xtrain)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.70075 -0.03336 0.08950 0.28662 2.13624
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 20.256260 4.625899 4.379 1.19e-05 ***
## displacement -0.029678 0.006865 -4.323 1.54e-05 ***
## horsepower -0.099006 0.028131 -3.519 0.000432 ***
## acceleration -0.367003 0.160700 -2.284 0.022385 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 289.577 on 209 degrees of freedom
## Residual deviance: 86.324 on 206 degrees of freedom
## AIC: 94.324
##
## Number of Fisher Scoring iterations: 8
prods_glm_mod1 <- predict(glm_mod1, Xtest, type = "response")
pred_glm_mod1 <- rep(0, length(prods_glm_mod1))
pred_glm_mod1[prods_glm_mod1 > 0.5] = 1
mean(pred_glm_mod1!=Ytest)
## [1] 0.1318681
(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? I tested five k=n and observed the test error rate rise after k=01, but began to lower around k=10, and at k=20 (k=19 to be exact) the error rate become lower than k=01.
k=01, ~12% k=05, ~14% k=10, ~13% k=15, ~12% k=20, ~11%
library(class)
Xtrain_knn <- cbind(displacement, horsepower, acceleration)[train,]
Xtest_knn <- cbind(displacement, horsepower, acceleration)[test,]
Ytrain_knn <- mpg0_1[train]
set.seed(42)
# KNN(k=1)
pred_knn = knn(Xtrain_knn, Xtest_knn, Ytrain_knn, k = 1)
table(pred_knn, Ytest)
## Ytest
## pred_knn 0 1
## 0 90 11
## 1 10 71
mean(pred_knn != Ytest)
## [1] 0.1153846
library(class)
Xtrain_knn <- cbind(displacement, horsepower, acceleration)[train,]
Xtest_knn <- cbind(displacement, horsepower, acceleration)[test,]
Ytrain_knn <- mpg0_1[train]
set.seed(42)
# KNN(k=1)
pred_knn = knn(Xtrain_knn, Xtest_knn, Ytrain_knn, k = 5)
mean(pred_knn != Ytest)
## [1] 0.1428571
library(class)
Xtrain_knn <- cbind(displacement, horsepower, acceleration)[train,]
Xtest_knn <- cbind(displacement, horsepower, acceleration)[test,]
Ytrain_knn <- mpg0_1[train]
set.seed(42)
# KNN(k=1)
pred_knn = knn(Xtrain_knn, Xtest_knn, Ytrain_knn, k = 10)
mean(pred_knn != Ytest)
## [1] 0.1263736
library(class)
Xtrain_knn <- cbind(displacement, horsepower, acceleration)[train,]
Xtest_knn <- cbind(displacement, horsepower, acceleration)[test,]
Ytrain_knn <- mpg0_1[train]
set.seed(42)
# KNN(k=1)
pred_knn = knn(Xtrain_knn, Xtest_knn, Ytrain_knn, k = 15)
mean(pred_knn != Ytest)
## [1] 0.1208791
library(class)
Xtrain_knn <- cbind(displacement, horsepower, acceleration)[train,]
Xtest_knn <- cbind(displacement, horsepower, acceleration)[test,]
Ytrain_knn <- mpg0_1[train]
set.seed(42)
# KNN(k=1)
pred_knn = knn(Xtrain_knn, Xtest_knn, Ytrain_knn, k = 20)
mean(pred_knn != Ytest)
## [1] 0.1098901
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.
library(MASS)
names(Boston)
## [1] "crim" "zn" "indus" "chas" "nox" "rm" "age"
## [8] "dis" "rad" "tax" "ptratio" "black" "lstat" "medv"
# summary(Boston)
Like we did with the other questions, we create a charter vector and variables to separate train and test.
attach(Boston)
set.seed(42)
crime01 <- rep(0, length(crim))
crime01[crim > median(crim)] <- 1
Boston <- data.frame(Boston, crime01)
train <- 1:(dim(Boston)[1]/2)
test <-(dim(Boston)[1]/2 + 1):dim(Boston)[1]
Boston.train <- Boston[train, ]
Boston.test <- Boston[test, ]
crime01.test <- crime01[test]
glm.fit <- glm(crime01 ~ . - crime01 - crim - chas - tax, data = Boston, family = binomial,
subset = train)
Logistic Regression has an error rate of ~18.6%
glm.probs <- predict(glm.fit, Boston.test, type = "response")
glm.pred <- rep(0, length(glm.probs))
glm.pred[glm.probs > 0.5] <- 1
table(glm.pred, crime01.test)
## crime01.test
## glm.pred 0 1
## 0 67 24
## 1 23 139
mean(glm.pred == crime01.test)
## [1] 0.8142292
mean(glm.pred != crime01.test)
## [1] 0.1857708
LDA with two variables has an error rate of ~13.4%
lda.fit <- lda(crime01 ~ . - crime01 - crim, data = Boston, subset = train)
lda.pred <- predict(lda.fit, Boston.test)
table(lda.pred$class,crime01.test)
## crime01.test
## 0 1
## 0 80 24
## 1 10 139
mean(lda.pred$class == crime01.test)
## [1] 0.8656126
mean(lda.pred$class != crime01.test)
## [1] 0.1343874
QDA with four variables has an error rate of ~68%
qda_mod2 <- qda(crime01 ~ . - crime01 - crim - chas - tax, data = Boston, subset = train)
pred_qda_mod2 <- predict(qda_mod2, Boston.test)
class_qda_mod2 <- pred_qda_mod2$class
table(class_qda_mod2, crime01.test)
## crime01.test
## class_qda_mod2 0 1
## 0 77 159
## 1 13 4
mean(class_qda_mod2!=crime01.test)
## [1] 0.6798419
LDA with seven variables has an error rate of ~11.9%
lda.fit <- lda(crime01 ~ . - crime01 - crim - chas - tax - lstat - indus - age,
data = Boston, subset = train)
lda.pred <- predict(lda.fit, Boston.test)
mean(lda.pred$class != crime01.test)
## [1] 0.1185771
Setting up KNN
library(class)
train.X <- cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black,
lstat, medv)[train, ]
test.X <- cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black,
lstat, medv)[test, ]
train.crime01 <- crime01[train]
set.seed(42)
k=1 has an error rate of ~45.8%
knn.pred <- knn(train.X, test.X, train.crime01, k = 1)
table(knn.pred, crime01.test)
## crime01.test
## knn.pred 0 1
## 0 85 111
## 1 5 52
mean(knn.pred == crime01.test)
## [1] 0.541502
mean(knn.pred != crime01.test)
## [1] 0.458498
k=10 has an error rate of ~11.1%
knn.pred <- knn(train.X, test.X, train.crime01, k = 10)
table(knn.pred, crime01.test)
## crime01.test
## knn.pred 0 1
## 0 83 21
## 1 7 142
mean(knn.pred == crime01.test)
## [1] 0.8893281
mean(knn.pred != crime01.test)
## [1] 0.1106719
I scanned the numbers from k=2-9 and discovered the optimal is k=9 at error rate of ~11.1%, as shown below.
knn.pred <- knn(train.X, test.X, train.crime01, k = 9)
table(knn.pred, crime01.test)
## crime01.test
## knn.pred 0 1
## 0 83 21
## 1 7 142
mean(knn.pred == crime01.test)
## [1] 0.8893281
mean(knn.pred != crime01.test)
## [1] 0.1106719