- 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.
- Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
library(ISLR)
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
## Min. :-18.1950 Min. :-18.1950 Min. :0.08747
## 1st Qu.: -1.1580 1st Qu.: -1.1660 1st Qu.:0.33202
## Median : 0.2380 Median : 0.2340 Median :1.00268
## Mean : 0.1458 Mean : 0.1399 Mean :1.57462
## 3rd Qu.: 1.4090 3rd Qu.: 1.4050 3rd Qu.:2.05373
## Max. : 12.0260 Max. : 12.0260 Max. :9.32821
## Today Direction
## Min. :-18.1950 Down:484
## 1st Qu.: -1.1540 Up :605
## Median : 0.2410
## Mean : 0.1499
## 3rd Qu.: 1.4050
## Max. : 12.0260
plot(Weekly)

attach(Weekly)
print("Here is a numeric summary and plots of our Data.")
## [1] "Here is a numeric summary and plots of our Data."
- Use the full data set to perform a logistic regression with Direction as the response and the ???ve lag variables plus Volume as predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically signi???cant? If so, which ones?
glm.fit<-glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag4+Lag5+Volume, data = Weekly, family = binomial)
summary(glm.fit)
##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + 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
print("It would appear only the Varible LAG2 is the only one that is significant, due to the p value being less then .05 . ")
## [1] "It would appear only the Varible LAG2 is the only one that is significant, due to the p value being less then .05 . "
- 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.
CM = predict(glm.fit, type = "response")
pred.glm <-rep("DOWN", length(CM))
pred.glm[CM>.5]="UP"
table(pred.glm, Direction)
## Direction
## pred.glm Down Up
## DOWN 54 48
## UP 430 557
print("The confusion matrix is telling me that we predictied 484 DOWNS, and 605 UPS, but the actual DOWNs was 102, and UPS was 987")
## [1] "The confusion matrix is telling me that we predictied 484 DOWNS, and 605 UPS, but the actual DOWNs was 102, and UPS was 987"
print("The overall fraction of correct prediction is [(54+557)/1089]*100 = 56.1065% ")
## [1] "The overall fraction of correct prediction is [(54+557)/1089]*100 = 56.1065% "
print("Giving us a training error of 100-((54+557)/1089)*100 = 43.89348%")
## [1] "Giving us a training error of 100-((54+557)/1089)*100 = 43.89348%"
- Now ???t 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)
Week0910<-(Year>=2009)
Direction.09.10<-Direction[!train]
glm.fit2<-glm(Direction~Lag2, data=Weekly,family = binomial, subset = train)
summary(glm.fit2)
##
## 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
print("For this confustion matrix we get 43 predictied Downs, 61 predicted Ups. 14 Actual Downs and 90 Actual Ups")
## [1] "For this confustion matrix we get 43 predictied Downs, 61 predicted Ups. 14 Actual Downs and 90 Actual Ups"
print("Giving us our overall fraction of correct prediction to be 62.5%")
## [1] "Giving us our overall fraction of correct prediction to be 62.5%"
- Repeat (d) using LDA.
library(MASS)
lda.fit<-lda(Direction~Lag2,data = Weekly,subset = train)
lda.fit
## 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
print("For this confustion matrix we get 43 predictied Downs, 61 predicted Ups. 14 Actual Downs and 90 Actual Ups")
## [1] "For this confustion matrix we get 43 predictied Downs, 61 predicted Ups. 14 Actual Downs and 90 Actual Ups"
print("We get them dame outcomes as we did in the GLM")
## [1] "We get them dame outcomes as we did in the GLM"
- Repeat (d) using QDA.
qda.fit<-qda(Direction~Lag2, data = Weekly, subset = train)
qda.fit
## 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
print("For this confustion matrix we get 43 predictied Downs, 61 predicted Ups. 0 Actual Downs and 104 Actual Ups")
## [1] "For this confustion matrix we get 43 predictied Downs, 61 predicted Ups. 0 Actual Downs and 104 Actual Ups"
print("Giving us our overall fraction of correct prediction to be 58.6538")
## [1] "Giving us our overall fraction of correct prediction to be 58.6538"
print("This model does not beat GLM and LDA")
## [1] "This model does not beat GLM and LDA"
- Repeat (d) using KNN with K = 1.
print("This confustion matrix gives us 43 predicted down's, 61 predicted Up's. and 51 actual downs,as well as 53 actual Up's")
## [1] "This confustion matrix gives us 43 predicted down's, 61 predicted Up's. and 51 actual downs,as well as 53 actual Up's"
print("Giving us our overall fraction of correct prediction to be 50% ")
## [1] "Giving us our overall fraction of correct prediction to be 50% "
- Which of these methods appears to provide the best results on this data?
print("it would appear by the models above that LDA and GLM have the samecorrect prediction equation, and the least error rates therefore they would be the best amoung THESE models.")
## [1] "it would appear by the models above that LDA and GLM have the samecorrect prediction equation, and the least error rates therefore they would be the best amoung THESE models."
- Experiment with di???erent 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 classi???er.
- 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.
- 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 ???nd it helpful to use the data.frame() function to create a single data set containing both mpg01 and the other Auto variables.
library(ISLR)
summary(Auto)
## mpg cylinders displacement horsepower
## Min. : 9.00 Min. :3.000 Min. : 68.0 Min. : 46.0
## 1st Qu.:17.00 1st Qu.:4.000 1st Qu.:105.0 1st Qu.: 75.0
## Median :22.75 Median :4.000 Median :151.0 Median : 93.5
## Mean :23.45 Mean :5.472 Mean :194.4 Mean :104.5
## 3rd Qu.:29.00 3rd Qu.:8.000 3rd Qu.:275.8 3rd Qu.:126.0
## Max. :46.60 Max. :8.000 Max. :455.0 Max. :230.0
##
## weight acceleration year origin
## Min. :1613 Min. : 8.00 Min. :70.00 Min. :1.000
## 1st Qu.:2225 1st Qu.:13.78 1st Qu.:73.00 1st Qu.:1.000
## Median :2804 Median :15.50 Median :76.00 Median :1.000
## Mean :2978 Mean :15.54 Mean :75.98 Mean :1.577
## 3rd Qu.:3615 3rd Qu.:17.02 3rd Qu.:79.00 3rd Qu.:2.000
## Max. :5140 Max. :24.80 Max. :82.00 Max. :3.000
##
## name
## amc matador : 5
## ford pinto : 5
## toyota corolla : 5
## amc gremlin : 4
## amc hornet : 4
## chevrolet chevette: 4
## (Other) :365
Auto$mpg01<-as.factor(ifelse(Auto$mpg>median(Auto$mpg),1,0))
table(Auto$mpg01)
##
## 0 1
## 196 196
- 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 fndings.
attach(Auto)
pairs(Auto)

plot(mpg01,horsepower,main = "Scatterplot 1", xlab= "MPG", ylab = "horsepower")

plot(mpg01,cylinders,main = "Scatterplot 2", xlab= "MPG", ylab = "Cylinders")

plot(mpg01,weight,main = "Scatterplot 3", xlab= "MPG", ylab = "Weight")

boxplot(cylinders~mpg01,data = Auto, main = "Cylinders vs MPG")

boxplot(displacement~mpg01,data = Auto, main = "Displacement vs MPG")

boxplot(horsepower~mpg01,data = Auto, main = "Horsepower vs MPG")

print("It would appear that the greatest influencers on MPG01 would be horsepower, weight , displacemnt and Cylinders")
## [1] "It would appear that the greatest influencers on MPG01 would be horsepower, weight , displacemnt and Cylinders"
- Split the data into a training set and a test set.
Auto1<-Auto[,-9]
train<-sample(nrow(Auto1),0.75*nrow(Auto1))
training<-Auto1[train,]
test<-Auto1[-train,]
dim(Auto1)
## [1] 392 9
dim(training)
## [1] 294 9
dim(test)
## [1] 98 9
- 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?
library(MASS)
lda.fit<-lda(mpg01~horsepower+cylinders+weight+displacement,data = Auto1, subset = train)
lda.fit
## Call:
## lda(mpg01 ~ horsepower + cylinders + weight + displacement, data = Auto1,
## subset = train)
##
## Prior probabilities of groups:
## 0 1
## 0.5170068 0.4829932
##
## Group means:
## horsepower cylinders weight displacement
## 0 130.49342 6.782895 3605.007 274.8684
## 1 77.75352 4.147887 2306.641 112.4225
##
## Coefficients of linear discriminants:
## LD1
## horsepower 0.0088332042
## cylinders -0.5288242431
## weight -0.0008472646
## displacement -0.0037786327
lda.pred<-predict(lda.fit,test)
mean(lda.pred$class!=test$mpg01)
## [1] 0.1326531
print("The Error rate we obtain is .1122449")
## [1] "The Error rate we obtain is .1122449"
- 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?
qda.fit<-qda(mpg01~cylinders+weight+displacement+horsepower, data = Auto1, subset = train)
qda.fit
## Call:
## qda(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto1,
## subset = train)
##
## Prior probabilities of groups:
## 0 1
## 0.5170068 0.4829932
##
## Group means:
## cylinders weight displacement horsepower
## 0 6.782895 3605.007 274.8684 130.49342
## 1 4.147887 2306.641 112.4225 77.75352
qda.pred<-predict(qda.fit,test)
ERROR<-mean(qda.pred$class != test$mpg01)
print("The error rate we will end up getting is ." )
## [1] "The error rate we will end up getting is ."
ERROR
## [1] 0.1122449
- 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?
glm.fit<-glm(mpg01~cylinders+weight+displacement+horsepower,data=Auto1, subset = train ,family = binomial)
glm.fit
##
## Call: glm(formula = mpg01 ~ cylinders + weight + displacement + horsepower,
## family = binomial, data = Auto1, subset = train)
##
## Coefficients:
## (Intercept) cylinders weight displacement horsepower
## 11.718930 0.175571 -0.001356 -0.026504 -0.046914
##
## Degrees of Freedom: 293 Total (i.e. Null); 289 Residual
## Null Deviance: 407.2
## Residual Deviance: 133.4 AIC: 143.4
glm.probs = predict(glm.fit, test,type = "response" )
glm.pred <- rep(0, length(glm.probs))
glm.pred[glm.probs>.5]=1
mean(glm.pred!=test$mpg01)
## [1] 0.1428571
print("Our error is .05102041" )
## [1] "Our error is .05102041"
- Using the Boston data set, ???t classi???cation 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 fndings.
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 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
crim1 = rep(0,length(Boston$crim))
crim1[Boston$crim>median(Boston$crim)]= 1
print("Now we create our our training and test sets...")
## [1] "Now we create our our training and test sets..."
train=1:(dim(Boston)[1]/2)
test=(dim(Boston)[1]/2 + 1):dim(Boston)[1]
Btrain=Boston[train,]
Btest=Boston[test, ]
crimtest=crim1[test]
print("Now to fit the these data sets to Linear Model, LDA and KNN.")
## [1] "Now to fit the these data sets to Linear Model, LDA and KNN."
glm.fit<-glm(crim1~.-crim1 - crim, data = Boston, family = binomial, subset = train)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
glm.probs<-predict(glm.fit,Btest, type = "response")
glm.pred<-rep(0, length(glm.probs))
glm.pred[glm.probs > .5] = 1
mean(glm.pred!=crimtest)
## [1] 0.1818182
glm.fit2<-glm(crim1~.-crim1 - crim - chas - tax, data = Boston, family = binomial, subset = train)
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
glm.probs2 = predict(glm.fit2, Btest, type = "response")
glm.pred2<-rep(0,length(glm.probs2))
glm.pred2[glm.probs2>.5] = 1
mean(glm.pred2!=crimtest)
## [1] 0.1857708
print("Now we will do the LDA Model")
## [1] "Now we will do the LDA Model"
print("Now we will do the KNN")
## [1] "Now we will do the KNN"
library(class)
tra.X = cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black,lstat, medv)[train, ]
te.X = cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black,lstat, medv)[test, ]
train.crim1 = crim1[train]
print("when K= 1 and the test error rate")
## [1] "when K= 1 and the test error rate"
knn.pred = knn(tra.X, te.X, train.crim1, k = 1)
mean(knn.pred != crimtest)
## [1] 0.458498
print("When K=10")
## [1] "When K=10"
knn.pred = knn(tra.X, te.X, train.crim1, k = 10)
mean(knn.pred != crimtest)
## [1] 0.1185771
print("WHen K=100 and the test error rate")
## [1] "WHen K=100 and the test error rate"
knn.pred = knn(tra.X, te.X, train.crim1, k = 100)
mean(knn.pred != crimtest)
## [1] 0.4940711