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)
attach(Weekly)
(a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
Running our cor() Function through our data set really the only substantial correlation we find is Year and Volume.
With the plot below we find that over time the volume increases
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
plot(Volume)
(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?
With our results below, the only predictor that is statistically significant with in the .05 level is Lag2
glmfit= glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, family = binomial)
summary(glmfit)
##
## 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.
From our model below there is an overall correct prediction of around 56% of whether the market will go up or down.
glmprobs=predict(glmfit,type = "response")
glmpred=rep("Down" , length(glmprobs))
glmpred[glmprobs > 0.5] = "Up"
table(glmpred, Direction)
## Direction
## glmpred Down Up
## Down 54 48
## Up 430 557
mean(glmpred==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 = (Year < 2009)
Weekly.0910= Weekly[!train,]
Direction.0910= Direction[!train]
glmfit2=glm(Direction ~ Lag2, data = Weekly, family = binomial,subset = train)
summary(glmfit2)
##
## Call:
## glm(formula = Direction ~ Lag2, family = binomial, data = Weekly,
## subset = 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
glmprobs2= predict(glmfit2, Weekly.0910, type="response")
glmpred2= rep("down", length(glmprobs2))
glmpred2[glmprobs2 > .5]= "Up"
table(glmpred2, Direction.0910)
## Direction.0910
## glmpred2 Down Up
## down 9 5
## Up 34 56
mean(glmpred2 == Direction.0910)
## [1] 0.5384615
(e) Repeat (d) using LDA.
library(MASS)
ldafit= lda(Direction~Lag2,data=Weekly,subset=train)
ldafit
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = 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(ldafit)
ldapred=predict(ldafit, Weekly.0910)
ldaclass=ldapred$class
table(ldaclass,Direction.0910)
## Direction.0910
## ldaclass Down Up
## Down 9 5
## Up 34 56
mean(ldaclass==Direction.0910)
## [1] 0.625
(f) Repeat (d) using QDA.
qdafit=qda(Direction ~ Lag2, data =Weekly, subset = train)
qdafit
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2
## Down -0.03568254
## Up 0.26036581
qdapred=predict(qdafit, Weekly.0910)
table(qdapred$class, Direction.0910)
## Direction.0910
## Down Up
## Down 0 0
## Up 43 61
61/104
## [1] 0.5865385
(g) Repeat (d) using KNN with K = 1.
library(class)
train.x=as.matrix(Lag2[train])
test.x=as.matrix(Lag2[!train])
train.Direction=Direction [train]
set.seed(1)
knn.pred=knn(train.x,test.x,train.Direction, k=1)
table(knn.pred, Direction.0910)
## Direction.0910
## knn.pred Down Up
## Down 21 30
## Up 22 31
mean(knn.pred==Direction.0910)
## [1] 0.5
(h) Which of these methods appears to provide the best results on this data?
Therefore with our final results above we conclude that the best performing model was LDA predicting at 62.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.
Experimenting different combinations, the best performing model within the different combination I tested was using LDA and having the interaction between Lag2 and Lag1. The accuracy was at 57.7%
ldafit2 = lda(Direction ~ Lag2:Lag1, data = Weekly, subset = train)
ldapred2=predict(ldafit2, Weekly.0910)
mean(ldapred2$class == Direction.0910)
## [1] 0.5769231
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)
(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.
mpg01=rep(0, length(mpg))
mpg01[mpg>median(mpg)]=1
Auto=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.
With our results and plots below. cylinders, displacement , horsepower, and weight are good predictors for mpg01
cor(Auto[,-9])
## 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
par(mfrow = c(2,2))
boxplot(cylinders~mpg01)
boxplot(displacement~mpg01)
boxplot(horsepower~mpg01)
boxplot(weight~mpg01)
(c) Split the data into a training set and a test set.
train=(year%%2==0)
Autotrain=Auto[train,]
Autotest=Auto[!train,]
mpg01test=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?
when performing LDA on our training data we have a test error rate of 12.6%
ldafit=lda(mpg01~cylinders + displacement + horsepower + weight, data = Auto, subset = train)
ldafit
## Call:
## lda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto,
## subset = train)
##
## Prior probabilities of groups:
## 0 1
## 0.4571429 0.5428571
##
## Group means:
## cylinders displacement horsepower weight
## 0 6.812500 271.7396 133.14583 3604.823
## 1 4.070175 111.6623 77.92105 2314.763
##
## Coefficients of linear discriminants:
## LD1
## cylinders -0.6741402638
## displacement 0.0004481325
## horsepower 0.0059035377
## weight -0.0011465750
ldapred=predict(ldafit, Autotest)
table(ldapred$class, mpg01test)
## mpg01test
## 0 1
## 0 86 9
## 1 14 73
23/182
## [1] 0.1263736
(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?
when performing QDA on our training data we have a test error rate of 13.2%
qdafit=qda(mpg01~cylinders + displacement + horsepower + weight, data = Auto, subset = train)
qdafit
## Call:
## qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto,
## subset = train)
##
## Prior probabilities of groups:
## 0 1
## 0.4571429 0.5428571
##
## Group means:
## cylinders displacement horsepower weight
## 0 6.812500 271.7396 133.14583 3604.823
## 1 4.070175 111.6623 77.92105 2314.763
qdapred=predict(qdafit,Autotest)
table(qdapred$class,mpg01test)
## mpg01test
## 0 1
## 0 89 13
## 1 11 69
24/182
## [1] 0.1318681
(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?
when performing logistic regression on our training data we have a test error rate of 12.1%
glmfit= glm(mpg01~cylinders + displacement + horsepower + weight,family = binomial, data = Auto, subset = train)
summary(glmfit)
##
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower +
## weight, family = binomial, data = Auto, subset = train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.48027 -0.03413 0.10583 0.29634 2.57584
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 17.658730 3.409012 5.180 2.22e-07 ***
## cylinders -1.028032 0.653607 -1.573 0.1158
## displacement 0.002462 0.015030 0.164 0.8699
## horsepower -0.050611 0.025209 -2.008 0.0447 *
## weight -0.002922 0.001137 -2.569 0.0102 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 289.58 on 209 degrees of freedom
## Residual deviance: 83.24 on 205 degrees of freedom
## AIC: 93.24
##
## Number of Fisher Scoring iterations: 7
glmprobs=predict(glmfit, Autotest, type = "response")
glmpred=rep(0,length(glmprobs))
glmpred[glmprobs>.5]=1
table(glmpred,mpg01test)
## mpg01test
## glmpred 0 1
## 0 89 11
## 1 11 71
mean(glmpred!=mpg01test)
## [1] 0.1208791
(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?
when performing KNN and a value of K =1 on our training data we have a test error rate of 15.4%
train.x=cbind(cylinders,displacement,horsepower, weight)[train,]
test.x=cbind(cylinders,displacement,horsepower, weight)[!train,]
train.mpg01=mpg01[train]
set.seed(1)
knn.pred=knn(train.x,test.x,train.mpg01,k=1)
table(knn.pred,mpg01test)
## mpg01test
## knn.pred 0 1
## 0 83 11
## 1 17 71
mean(knn.pred!=mpg01test)
## [1] 0.1538462
If we change our value from K=1 to k=3 we have a better performing model by having a lower test error of 13.7 %
knn.pred=knn(train.x,test.x,train.mpg01,k=3)
table(knn.pred,mpg01test)
## mpg01test
## knn.pred 0 1
## 0 84 9
## 1 16 73
mean(knn.pred!=mpg01test)
## [1] 0.1373626
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)
attach(Boston)
crim01=rep(0, length(crim))
crim01[crim > median(crim)]=1
Boston=data.frame(Boston, crim01)
train=1:(length(crim)/2)
test=(length(crim)/2+1):length(crim)
Bostontrain=Boston[train,]
Bostontest=Boston[test,]
crim01test=crim01[test]
Logistic regression - test error rate 18.2%
glmfit= glm(crim01 ~ . -crim01 -crim, data = Boston, family = binomial, subset = train)
glmprobs=predict(glmfit, Bostontest, type="response")
glmpred= rep(0,length(glmprobs))
glmpred[glmprobs>.5]=1
table(glmpred,crim01test)
## crim01test
## glmpred 0 1
## 0 68 24
## 1 22 139
mean(glmpred!=crim01test)
## [1] 0.1818182
LDA - test error rate 13.4%
ldafit=lda(crim01~ . -crim01 -crim, data = Boston, subset=train)
ldapred=predict(ldafit, Bostontest)
table(ldapred$class, crim01test)
## crim01test
## 0 1
## 0 80 24
## 1 10 139
mean(ldapred$class!=crim01test)
## [1] 0.1343874
KNN - K = 1 test error rate 45.8%
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.crim01=crim01[train]
set.seed(1)
knn.pred=knn(train.x,test.x, train.crim01, k=1)
table(knn.pred, crim01test)
## crim01test
## knn.pred 0 1
## 0 85 111
## 1 5 52
mean(knn.pred!= crim01test)
## [1] 0.458498
KNN - K = 3 test error rate 11.1%
knn.pred=knn(train.x,test.x, train.crim01, k=9)
table(knn.pred, crim01test)
## crim01test
## knn.pred 0 1
## 0 83 21
## 1 7 142
mean(knn.pred!= crim01test)
## [1] 0.1106719