require(corrplot)
## Loading required package: corrplot
## corrplot 0.84 loaded
require(ISLR)
## Loading required package: ISLR
require(MASS)
## Loading required package: MASS
require(class)
## Loading required package: class
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.
Part A 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
attach(Weekly)
pairs(Weekly)
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
By the looks of the graph, it looks like there is a logarithm pattern between year and volume. After looking at the correlations, I see that there is a strong correlation year and volume only. There does not look like there’s any strong correlations between the other variables.
Part 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?
glm.fit<-glm(Direction~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data=Weekly, family="binomial")
summary(glm.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
The only statistically significant predictor is Lag2.
Part 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.
glm.probs<-predict(glm.fit, type="response")
glm.pred<-rep("Down", 1089)
glm.pred[glm.probs>0.5]="Up"
confustionmat<- table(glm.pred, Weekly$Direction)
confustionmat
##
## glm.pred Down Up
## Down 54 48
## Up 430 557
mean(glm.pred==Weekly$Direction)
## [1] 0.5610652
Based on the confusion matrix, we can see that our model correctly predicted that the market would go up 557 days and that it would go down 54 days, for a total of 661 correct predictions. The mean() function was used to compute the fraction of days for which the prediction was correct. In this case, the logistic regression correctly predicted the movement of the market 56.11% of the time. Meaning that our logistic regression model is working a little better than random guessing. However, these results are misleading considering the fact that we did not pull a training and testing dataset.
Part 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<=2008)
Weekly.2008<-Weekly[!train,]
Direction.2008<-Direction[!train]
glm.fit2<-glm(Direction~Lag2, data=Weekly, family="binomial", subset=train)
glm.probs2<-predict(glm.fit2, type="response", newdata=Weekly.2008)
glm.pred2<-rep("Down", 104)
glm.pred2[glm.probs2>0.5]="Up"
table(glm.pred2, Direction.2008)
## Direction.2008
## glm.pred2 Down Up
## Down 9 5
## Up 34 56
mean(glm.pred2==Direction.2008)
## [1] 0.625
Based on the confusion matrix, we can see that our model correctly predicted that the market would go up 56 days and that it would go down 9 days, for a total of 65 correct predictions. The mean() function was used to compute the fraction of days for which the prediction was correct. In this case, the logistic regression correctly predicted the movement of the market 62.5% of the time. Meaning that our logistic regression model is working a little better than random guessing. These results are great due to the fact that we were able to test the predictions of the logistic regression on a dataset that had not see the model prior.
Part E Repeat (d) using LDA.
library(MASS)
lda.fit<-lda(Direction~Lag2, data=Weekly, subset=train)
lda.pred<-predict(lda.fit, type="response", newdata=Weekly.2008)
table(lda.pred$class, Direction.2008)
## Direction.2008
## Down Up
## Down 9 5
## Up 34 56
mean(lda.pred$class==Direction.2008)
## [1] 0.625
The confusion matrix explains that our LDA model correctly predicted that the market would go up 56 days and that it would go down 9 days, for a total of 65 correct predictions. The mean() function was used to compute the fraction of days for which the prediction was correct. In this case, the LDA model correctly predicted the movement of the market 62.5% of the time.
Part F Repeat (d) using QDA.
qda.fit<-qda(Direction~Lag2, data=Weekly, subset=train)
qda.pred<-predict(qda.fit, type="response", newdata=Weekly.2008)
table(qda.pred$class, Direction.2008)
## Direction.2008
## Down Up
## Down 0 0
## Up 43 61
mean(qda.pred$class==Direction.2008)
## [1] 0.5865385
The confusion matrix explains that our QDA model correctly predicted that the market would go up 61 days and that it would go down 0 days, for a total of 61 correct predictions. The mean() function was used to compute the fraction of days for which the prediction was correct. In this case, the LDA model correctly predicted the movement of the market 58.65% of the time. This model does not predict the Direction of the market as well as the logistic and LDA models.
Part G Repeat (d) using KNN with K=1.
library(class)
attach(Weekly)
## The following objects are masked from Weekly (pos = 3):
##
## Direction, Lag1, Lag2, Lag3, Lag4, Lag5, Today, Volume, Year
Xtrain=as.matrix(Lag2[train])
Xtest=as.matrix(Lag2[!train])
train.Direction=Direction[train]
set.seed(1)
knn.pred<-knn(Xtrain, Xtest, train.Direction, k=1)
table(knn.pred, Direction.2008)
## Direction.2008
## knn.pred Down Up
## Down 21 30
## Up 22 31
mean(knn.pred==Direction.2008)
## [1] 0.5
The confusion matrix explains that our KNN model correctly predicted that the market would go up 31 days and that it would go down 21 days, for a total of 52 correct predictions. The mean() function was used to compute the fraction of days for which the prediction was correct. In this case, the KNN model correctly predicted the movement of the market 50% of the time.
Part H Which of these methods appears to provide the best results on this data?
The model that predicts the movement of the market the best is the logistic regrssion and LDA models.
Part 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.
glm.fit3<-glm(Direction~Lag1+Lag2+(Lag1*Lag2), data=Weekly, family="binomial", subset=train)
summary(glm.fit3)
##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + (Lag1 * Lag2), family = "binomial",
## data = Weekly, subset = train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.573 -1.259 1.003 1.086 1.596
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.211419 0.064589 3.273 0.00106 **
## Lag1 -0.051505 0.030727 -1.676 0.09370 .
## Lag2 0.053471 0.029193 1.832 0.06700 .
## Lag1:Lag2 0.001921 0.007460 0.257 0.79680
## ---
## 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: 1346.9 on 981 degrees of freedom
## AIC: 1354.9
##
## Number of Fisher Scoring iterations: 4
glm.probs3<-predict(glm.fit3, type="response", newdata=Weekly.2008)
glm.pred3<-rep("Down", 104)
glm.pred3[glm.probs3>0.5]="Up"
table(glm.pred3, Direction.2008)
## Direction.2008
## glm.pred3 Down Up
## Down 7 8
## Up 36 53
mean(glm.pred3==Direction.2008)
## [1] 0.5769231
library(MASS)
lda.fit2<-lda(Direction~Lag1+Lag2+(Lag1*Lag2), data=Weekly, subset=train)
lda.pred2<-predict(lda.fit2, type="response", newdata=Weekly.2008)
table(lda.pred2$class, Direction.2008)
## Direction.2008
## Down Up
## Down 7 8
## Up 36 53
mean(lda.pred2$class==Direction.2008)
## [1] 0.5769231
qda.fit2<-qda(Direction~Lag1+Lag2+(Lag1*Lag2), data=Weekly, subset=train)
qda.pred2<-predict(qda.fit2, type="response", newdata=Weekly.2008)
table(qda.pred2$class, Direction.2008)
## Direction.2008
## Down Up
## Down 23 36
## Up 20 25
mean(qda.pred2$class==Direction.2008)
## [1] 0.4615385
Xtrain2=cbind(Weekly$Lag1, Weekly$Lag2, (Weekly$Lag1 * Weekly$Lag2))[train,]
Xtest2=cbind(Weekly$Lag1, Weekly$Lag2, (Weekly$Lag1 * Weekly$Lag2))[!train,]
train.Direction2=Weekly$Direction[train]
test.Direction2=Weekly$Direction[!train]
set.seed(1)
knn.pred2<-knn(data.frame(Xtrain2), data.frame(Xtest2), train.Direction2, k=3)
table(knn.pred2, Direction.2008)
## Direction.2008
## knn.pred2 Down Up
## Down 23 33
## Up 20 28
mean(knn.pred2==Direction.2008)
## [1] 0.4903846
detach(Weekly)
Even with an interaction effect, the logistic regression and LDA models perform the best in terms of accuracy of the prediction for the direction of the market.
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.
Part 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.
## 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
library(ISLR)
attach(Auto)
## The following objects are masked from Auto (pos = 3):
##
## acceleration, cylinders, displacement, horsepower, mpg, name,
## origin, weight, year
mpg01<-as.numeric(ifelse(mpg>median(mpg), "1", "0"))
Auto=data.frame(Auto, mpg01)
head(Auto)
## mpg cylinders displacement horsepower weight acceleration year origin
## 1 18 8 307 130 3504 12.0 70 1
## 2 15 8 350 165 3693 11.5 70 1
## 3 18 8 318 150 3436 11.0 70 1
## 4 16 8 304 150 3433 12.0 70 1
## 5 17 8 302 140 3449 10.5 70 1
## 6 15 8 429 198 4341 10.0 70 1
## name mpg01
## 1 chevrolet chevelle malibu 0
## 2 buick skylark 320 0
## 3 plymouth satellite 0
## 4 amc rebel sst 0
## 5 ford torino 0
## 6 ford galaxie 500 0
Part 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.
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
pairs(Auto)
par(mfrow=c(2,3))
boxplot(cylinders~mpg01, data=Auto, main="Cylinders vs MPG01")
boxplot(displacement~mpg01, data=Auto, main="Displacement vs MPG01")
boxplot(horsepower~mpg01, data=Auto, main="Horsepower vs MPG01")
boxplot(weight~mpg01, data=Auto, main="Weight vs MPG01")
boxplot(acceleration~mpg01, data=Auto, main="Acceleration vs MPG01")
boxplot(year~mpg01, data=Auto, main="Year vs MPG01")
The graphs indicate that there are some association between mpg01 and cylinders, weight, horsepower, and displacement. These 4 variables show more of a distinct distinguishment between mpg01 where it equals 0 and mpg01 where it equals 1. When mpg01 equals 0, this means that the car has a low gas mileage. When mpg01 equals 1, this means that the car has high gas mileage.
Part C Split the data into a training set and a test set.
Part 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?
library(MASS)
autolda.fit<-lda(mpg01~cylinders+weight+horsepower+displacement, data =Autotrain)
autolda.pred<-predict(autolda.fit, Autotest)
table(autolda.pred$class, mpg01.test)
## mpg01.test
## 0 1
## 0 44 3
## 1 4 47
mean(autolda.pred$class!=mpg01.test)
## [1] 0.07142857
The LDA Model for the Auto dataset has a test error rate of 7.14%. The model accurately predicts that 44 cars had low gas mileage and that 47 cars had high gas mileage.
Part 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?
autoqda.fit<-qda(mpg01~cylinders+weight+horsepower+displacement, data = Autotrain)
autoqda.pred<-predict(autoqda.fit, Autotest)
table(autoqda.pred$class, mpg01.test)
## mpg01.test
## 0 1
## 0 46 4
## 1 2 46
mean(autoqda.pred$class!=mpg01.test)
## [1] 0.06122449
The QDA Model for the Auto dataset has a test error rate of 6.12%. The model accurately predicts that 46 cars had low gas mileage and that 46 cars had high gas mileage.
Part 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?
autoglm.fit<-glm(mpg01~cylinders+weight+displacement+horsepower, family= "binomial", data=Autotrain)
autoglm.probs<-predict(autoglm.fit, Autotest, type="response")
autoglm.pred<-rep(0,length(autoglm.probs))
autoglm.pred[autoglm.probs>0.5]=1
table(autoglm.pred, mpg01.test)
## mpg01.test
## autoglm.pred 0 1
## 0 46 5
## 1 2 45
mean(autoglm.pred!=mpg01.test)
## [1] 0.07142857
The Logistic Model has a test error rate of 7.14%. The model accurately predicts that 46 cars had low gas mileage and that 45 cars had high gas mileage.
Part 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?
library(class)
Xtrain=cbind(cylinders,weight,displacement,horsepower)[train,]
Xtest=cbind(cylinders, weight,displacement,horsepower)[test,]
train.mpg01=mpg01[train]
set.seed(1)
autoknn.pred=knn(Xtrain, Xtest, train.mpg01, k=1)
table(autoknn.pred, mpg01.test)
## mpg01.test
## autoknn.pred 0 1
## 0 44 6
## 1 4 44
mean(autoknn.pred!=mpg01.test)
## [1] 0.1020408
autoknn.pred2=knn(Xtrain, Xtest, train.mpg01, k=5)
table(autoknn.pred2, mpg01.test)
## mpg01.test
## autoknn.pred2 0 1
## 0 43 4
## 1 5 46
mean(autoknn.pred2!=mpg01.test)
## [1] 0.09183673
autoknn.pred3=knn(Xtrain, Xtest, train.mpg01, k=10)
table(autoknn.pred3, mpg01.test)
## mpg01.test
## autoknn.pred3 0 1
## 0 44 4
## 1 4 46
mean(autoknn.pred3!=mpg01.test)
## [1] 0.08163265
autoknn.pred4=knn(Xtrain, Xtest, train.mpg01, k=20)
table(autoknn.pred4, mpg01.test)
## mpg01.test
## autoknn.pred4 0 1
## 0 43 5
## 1 5 45
mean(autoknn.pred4!=mpg01.test)
## [1] 0.1020408
autoknn.pred5=knn(Xtrain, Xtest, train.mpg01, k=100)
table(autoknn.pred5, mpg01.test)
## mpg01.test
## autoknn.pred5 0 1
## 0 43 4
## 1 5 46
mean(autoknn.pred5!=mpg01.test)
## [1] 0.09183673
detach(Auto)
The KNN model with 1 K-Fold has a test error rate of 10.20%; this model accurately predicts that 44 cars had low gas mileage and 44 cars had high gas mileage. The KNN model with 5 K-Fold has a test error rate of 9.18%; this model accurately predicts that 43 cars had low gas mileage and 46 cars had high gas mileage. The KNN model with 10 K-Fold has a test error rate of 8.16%; this model accurately predicts that 44 cars had low gas mileage and 46 cars had high gas mileage. The KNN model with 20 K-Fold has a test error rate of 10.20%; this model accurately predicts that 43 cars had low gas mileage and 45 cars had high gas mileage. The KNN model with 100 K-Fold has a test error rate of 9.18%; this model accurately predicts that 43 cars had low gas mileage and 46 car had high gas mileage. It seems like the KNN model with 10 K-Folds performs the best.
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)
crimesub<-as.numeric(ifelse(crim>median(crim), "1", "0"))
Boston=data.frame(Boston, crimesub)
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 crimesub
## Min. : 1.73 Min. : 5.00 Min. :0.0
## 1st Qu.: 6.95 1st Qu.:17.02 1st Qu.:0.0
## Median :11.36 Median :21.20 Median :0.5
## Mean :12.65 Mean :22.53 Mean :0.5
## 3rd Qu.:16.95 3rd Qu.:25.00 3rd Qu.:1.0
## Max. :37.97 Max. :50.00 Max. :1.0
set.seed(100)
Bostontrain=sample(x=nrow(Boston), size=0.75*nrow(Boston), rep=FALSE)
Bostontest= -Bostontrain
Boston.train= Boston[Bostontrain,]
Boston.test= Boston[Bostontest,]
crimesub.test=crimesub[Bostontest]
dim(Boston)
## [1] 506 15
dim(Boston.train)
## [1] 379 15
dim(Boston.test)
## [1] 127 15
Logistic Regression
Bostonglm.fit<-glm(crimesub~zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, family="binomial", data=Boston, subset = Bostontrain)
Bostonglm.probs=predict(Bostonglm.fit, Boston.test, type="response")
Bostonglm.pred=rep(0, length(Bostonglm.probs))
Bostonglm.pred[Bostonglm.probs>0.5]=1
table(Bostonglm.pred, crimesub.test)
## crimesub.test
## Bostonglm.pred 0 1
## 0 62 9
## 1 5 51
mean(Bostonglm.pred!=crimesub.test)
## [1] 0.1102362
The logistic regression model for the crimesub is fit against all other variables with the exception of crim and itself. The test error for this model is 11.02%. This model accurately predicts that the crime rate in 62 suburbs were below the median and that the crime rate in 51 suburbs were above the median.
LDA
library(MASS)
Bostonlda.fit<-lda(crimesub~zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, data=Boston, subset = Bostontrain)
Bostonlda.pred<-predict(Bostonlda.fit, Boston.test)
table(Bostonlda.pred$class, crimesub.test)
## crimesub.test
## 0 1
## 0 64 17
## 1 3 43
mean(Bostonlda.pred$class!=crimesub.test)
## [1] 0.1574803
The LDA model for the crimsub is fit against all other variables with the exception of crim and itself. The test error for this model is 15.75%. This model accurately predicts that the crime rate in 64 suburbs were below the median and that the crime rate in 43 suburbs were above the median. This model does not predict as accurately as the logistic regression model above.
KNN
Xtrain3=cbind(zn,indus,chas,nox,rm,age,dis,rad,tax,ptratio,black,lstat,medv)[Bostontrain,]
Xtest3=cbind(zn,indus,chas,nox,rm,age,dis,rad,tax,ptratio,black,lstat,medv)[Bostontest,]
train.subcrim=crimesub[Bostontrain]
set.seed(1)
# KNN Model 1 K-Fold
Bostonknn.pred=knn(Xtrain3, Xtest3, train.subcrim, k=1)
table(Bostonknn.pred, crimesub.test)
## crimesub.test
## Bostonknn.pred 0 1
## 0 62 7
## 1 5 53
mean(Bostonknn.pred!=crimesub.test)
## [1] 0.09448819
# KNN Model 10 K-Fold
Bostonknn.pred2=knn(Xtrain3, Xtest3, train.subcrim, k=10)
table(Bostonknn.pred2, crimesub.test)
## crimesub.test
## Bostonknn.pred2 0 1
## 0 56 11
## 1 11 49
mean(Bostonknn.pred2!=crimesub.test)
## [1] 0.1732283
I tested K-Folds of 1 and 10. The model with 1 K-Fold performed best. In the model with 1 K-Fold, the model produced a test error of 9.45%. The 1 K-Fold KNN model accurately predicts that 62 suburbs had a low crime rate and that 53 suburbs had a high crime rate.
The KNN model with 1 K-Fold performed the best in regard to the most accurately predictions and lowest test error. I believe that a key reason is due to the fact that suburbs emmulate communities or environments that are near by. Because suburbs are a geographic location variable and factor, the KNN model works best and makes sense.
Additional Proof
Bostonglm.fit<-glm(crimesub~zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, family="binomial", data=Boston, subset = Bostontrain)
summary(Bostonglm.fit)
##
## Call:
## glm(formula = crimesub ~ zn + indus + chas + nox + rm + age +
## dis + rad + tax + ptratio + black + lstat + medv, family = "binomial",
## data = Boston, subset = Bostontrain)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.10721 -0.11995 0.00000 0.00075 2.50479
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -36.539707 8.028067 -4.551 5.33e-06 ***
## zn -0.102152 0.044694 -2.286 0.02228 *
## indus -0.066307 0.059454 -1.115 0.26474
## chas -0.140737 0.910947 -0.154 0.87722
## nox 56.479353 9.926008 5.690 1.27e-08 ***
## rm -0.667692 0.853860 -0.782 0.43423
## age 0.013427 0.014623 0.918 0.35852
## dis 0.787676 0.273534 2.880 0.00398 **
## rad 0.770994 0.186549 4.133 3.58e-05 ***
## tax -0.006917 0.003491 -1.981 0.04758 *
## ptratio 0.288534 0.145729 1.980 0.04771 *
## black -0.012426 0.006019 -2.065 0.03896 *
## lstat 0.062479 0.058315 1.071 0.28399
## medv 0.191587 0.080904 2.368 0.01788 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 525.28 on 378 degrees of freedom
## Residual deviance: 144.51 on 365 degrees of freedom
## AIC: 172.51
##
## Number of Fisher Scoring iterations: 9
Based on the above glm model, the only significant variables are zn, nox, dis, rad, tax, ptratio, black, and medv. For the remainder of the models, I will only use these statistically significant variables.
Bostonglm.fit2<-glm(crimesub~zn+nox+dis+rad+tax+ptratio+black+medv, family="binomial", data=Boston, subset = Bostontrain)
Bostonglm.probs2=predict(Bostonglm.fit2, Boston.test, type="response")
Bostonglm.pred2=rep(0, length(Bostonglm.probs2))
Bostonglm.pred2[Bostonglm.probs2>0.5]=1
table(Bostonglm.pred2, crimesub.test)
## crimesub.test
## Bostonglm.pred2 0 1
## 0 60 12
## 1 7 48
mean(Bostonglm.pred2!=crimesub.test)
## [1] 0.1496063
# LDA Model
library(MASS)
Bostonlda.fit2<-lda(crimesub~zn+nox+dis+rad+tax+ptratio+black+medv, data=Boston, subset = Bostontrain)
Bostonlda.pred2<-predict(Bostonlda.fit2, Boston.test)
table(Bostonlda.pred2$class, crimesub.test)
## crimesub.test
## 0 1
## 0 65 17
## 1 2 43
mean(Bostonlda.pred2$class!=crimesub.test)
## [1] 0.1496063
# KNN Model 1 K-Fold
Xtrain4=cbind(zn,nox,dis,rad,tax,ptratio,black,medv)[Bostontrain,]
Xtest4=cbind(zn,nox,dis,rad,tax,ptratio,black,medv)[Bostontest,]
train.subcrim2=crimesub[Bostontrain]
set.seed(1)
Bostonknn.pred3=knn(Xtrain4, Xtest4, train.subcrim2, k=1)
table(Bostonknn.pred3, crimesub.test)
## crimesub.test
## Bostonknn.pred3 0 1
## 0 64 6
## 1 3 54
mean(Bostonknn.pred3!=crimesub.test)
## [1] 0.07086614
# KNN Model 10 K-Fold
Bostonknn.pred4=knn(Xtrain4, Xtest4, train.subcrim2, k=10)
table(Bostonknn.pred4, crimesub.test)
## crimesub.test
## Bostonknn.pred4 0 1
## 0 62 9
## 1 5 51
mean(Bostonknn.pred4!=crimesub.test)
## [1] 0.1102362
Even with only significant variables to fit against crimesub, the KNN model with 1 K-Fold most accurately predicts the low or high crime rate given a suburb. The test error for the KNN model with 1 K-Fold is 7.09%.