Problem 13: 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)

(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  
##            
##            
##            
## 
pairs(Weekly)

plot(Weekly$Volume, ylab = "Shares traded (in billions)")

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

With the exception of year and volume, the scatterplot shown above does not appear to show any relationship between the covariants. I attempted to calculate the increase in share volume over a 21-year period using the plot function. I made an effort to quantitatively find the collinear correlations between year and volume using the corelation matrix. Volume and Year’s lone significant value of 0.842 fits with the strong link shown in the scatterplot and correlation matrix above.
(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

With the “glm” function, we can calculate the logistic regression. Lag2 is the statistically significant predictor;  p-value of 0.0296 provides evidence at the 5% significance level to reject the null hypothesis that it is unrelated to the response Direction.
(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"
table(glm.pred,Weekly$Direction)
##         
## glm.pred Down  Up
##     Down   54  48
##     Up    430 557
mean(glm.pred==Weekly$Direction)
## [1] 0.5610652

This shows that the model properly forecasted the weekly market movement 56.11% of the time. Differentiating between how the model correctly forecasts the upward and downward trends. The model was 92.07% accurate in predicting the weekly uptrends (557/(48+557)=0.9207; up). On the other hand, just 11.15% of down weekly trends were accurately anticipated, or 54/(430+54)=0.1115.
(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)
head(train)
## [1] TRUE TRUE TRUE TRUE TRUE TRUE
tail(train)
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
Weekly.test=Weekly[!train,]
dim(Weekly)
## [1] 1089    9
dim(Weekly.test)
## [1] 104   9
Direction.test=Weekly$Direction[!train]
glm.fits=glm(Direction~Lag2, data=Weekly, subset=train, family=binomial)
glm.probs=predict(glm.fits, Weekly.test,type='response')
glm.pred=rep('Down',104)
glm.pred[glm.probs>0.5]='Up'
table(glm.pred,Direction.test)
##         Direction.test
## glm.pred Down Up
##     Down    9  5
##     Up     34 56
mean(glm.pred==Direction.test)
## [1] 0.625

The model successfully predicted weekly trends at a rate of 62.5% after dividing the entire Weekly dataset into a training and test dataset, which is a marginal improvement over the model that used the entire dataset. Although this model was able to slightly improve on correctly forecasting downward trends, it also performed better at predicting upward trends (56/(56+5)= 0.918: 91.80%) than downward ones (9/(34+9)=0.2093: 20.93%).
(e) 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
lda.pred=predict(lda.fit, Weekly.test)
table(lda.pred$class, Direction.test)
##       Direction.test
##        Down Up
##   Down    9  5
##   Up     34 56
mean(lda.pred$class==Direction.test)
## [1] 0.625

Similar outcomes were obtained when a classifying model was developed using linear discriminant analysis as compared to the logistic regression model developed in above section.
(f) 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
qda.class=predict(qda.fit, Weekly.test)$class
table(qda.class, Direction.test)
##          Direction.test
## qda.class Down Up
##      Down    0  0
##      Up     43 61
mean(qda.class==Direction.test)
## [1] 0.5865385

Compared to the earlier methods, quadratic linear analysis produced a model with a lower accuracy of 58.65%. Furthermore, this model only evaluated estimating the accuracy of weekly upward trends, degrading the weekly downward trends.
(g) Repeat (d) using KNN with K = 1.

library(class)
attach(Weekly)
train.X=as.matrix(Lag2[train])
test.X=as.matrix(Lag2[!train])
train.Direction=Direction[train]
dim(train.X)
## [1] 985   1
dim(test.X)
## [1] 104   1
set.seed(1)
knn.pred=knn(train.X,test.X,train.Direction,k=1)
table(knn.pred, Direction.test)
##         Direction.test
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred==Direction.test)
## [1] 0.5

A classification model created using K-Nearest Neighbors seemed to have an accuracy rate of 50%, which is the same as pure guessing.
(h) Repeat (d) using naive Bayes.

library(e1071)
nbayes=naiveBayes(Direction~Lag2, data=Weekly, subset=train)
nbayes
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Conditional probabilities:
##       Lag2
## Y             [,1]     [,2]
##   Down -0.03568254 2.199504
##   Up    0.26036581 2.317485
nbayes.class=predict(nbayes,Weekly.test)
table(nbayes.class, Direction.test)
##             Direction.test
## nbayes.class Down Up
##         Down    0  0
##         Up     43 61
mean(nbayes.class==Direction.test)
## [1] 0.5865385

A classification model created using Naive Bayes seemed to have an accuracy rate of 58.65%, which is the same as Quadratic Linear Analysis model.
(i) Which of these methods appears to provide the best results on this data?
It seems that the models that performed the best on this data were linear discriminant analysis and logistic regression, both of which were equally effective.
**(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.

#Logistic regression  
attach(Weekly)
Weekly.fit=glm(Direction~Lag2:Lag4+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    3  4
##           Up     40 57
mean(logWeekly.pred == Direction.test)
## [1] 0.5769231
#Linear Discriminant Analysis  
Weeklylda.fit=lda(Direction~Lag2:Lag4+Lag2, data=Weekly,family=binomial, subset=train)
Weeklylda.pred=predict(Weeklylda.fit, Weekly.test)
table(Weeklylda.pred$class, Direction.test)
##       Direction.test
##        Down Up
##   Down    3  3
##   Up     40 58
mean(Weeklylda.pred$class==Direction.test)
## [1] 0.5865385
#Quadratic Discriminant Analysis  
Weeklyqda.fit = qda(Direction ~ poly(Lag2,2), data = Weekly, subset = train)
Weeklyqda.pred = predict(Weeklyqda.fit, Weekly.test)$class
table(Weeklyqda.pred, Direction.test)
##               Direction.test
## Weeklyqda.pred Down Up
##           Down    7  3
##           Up     36 58
mean(Weeklyqda.pred==Direction.test)
## [1] 0.625
#KNN Neighbors for K=4 
Week.train=as.matrix(Lag2[train])
Week.test=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
Weekknn.pred=knn(Week.train,Week.test,train.Direction,k=4)
table(Weekknn.pred,Direction.test)
##             Direction.test
## Weekknn.pred Down Up
##         Down   20 17
##         Up     23 44
mean(Weekknn.pred==Direction.test)
## [1] 0.6153846
#K=10  
Week.train=as.matrix(Lag2[train])
Week.test=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
Weekknn.pred=knn(Week.train,Week.test,train.Direction,k=10)
table(Weekknn.pred,Direction.test)
##             Direction.test
## Weekknn.pred Down Up
##         Down   17 21
##         Up     26 40
mean(Weekknn.pred==Direction.test)
## [1] 0.5480769
detach(Weekly)

After trying different transformations for the different methods, the Quadratic Discriminant Analysis shows the best accuracy rate i.e. 62.5%. In the case of KNN Neighbors method for K=4 shows the next best prediction rate.
##Problem 14: 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(ISLR2)
library(MASS)
Auto=na.omit(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

(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)
mpg01=rep(0, length(mpg))
mpg01[mpg > median(mpg)]=1
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

(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.

par(mfrow = c(2, 3))
plot(factor(Auto$mpg01), Auto$cylinders, ylab = "Number of engine cylinders")
plot(factor(Auto$mpg01), Auto$displacement, ylab = "Engine displacement (cubic inches)")
plot(factor(Auto$mpg01), Auto$horsepower, ylab = "Horsepower")
plot(factor(Auto$mpg01), Auto$weight, ylab = "Weight (pounds)")
plot(factor(Auto$mpg01), Auto$acceleration, ylab = "Time to reach 60mpg (seconds)")
plot(factor(Auto$mpg01), Auto$year, ylab = "Manufacture year")
mtext("Boxplots for cars with above(1) and below(0) median mpg", outer = TRUE, line = -1)

As we can see in the box plot for manufacturing year and time there is a lot of overlap between the two categories of car based on median mpg. But with the other predictors there are no overlaps between the two categories. This suggest that cylinders, displacement, horsepower and weight would be the most useful in predicting mpg01.

par(mfrow = c(3, 2))
plot(Auto$cylinders, Auto$mpg01, xlab = "Number of engine cylinders")
plot(Auto$displacement, Auto$mpg01, xlab = "Engine displacement (cubic inches)")
plot(Auto$horsepower, Auto$mpg01, xlab = "Horsepower")
plot(Auto$weight, Auto$mpg01, xlab = "Weight (pounds)")
plot(Auto$acceleration, Auto$mpg01, xlab = "Time to reach 60mpg (seconds)")
plot(Auto$year, Auto$mpg01, xlab = "Manufacture year")
mtext("Scatterplots for cars with above(1) and below(0) median mpg", outer = TRUE, line = -1)

Further evidence that horsepower and weight will be helpful in predicting mpg01 can be found in scatterplots with mpg01 on the y-axis and the various quantitative variables on the x-axis. These scatterplots show clusters of above-median mpgs at the low ends and clusters of below-median mpgs at the high ends of each variable’s range. Cylinders and discplacement appear to be less useful on their own, at least for logistic regression, according to the scatterplots that show them.
(c) Split the data into a training set and a test set.

train = (year %% 2 == 0)
train.auto = Auto[train,]
test.auto = Auto[-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?

autolda.fit = lda(mpg01~displacement+horsepower+weight+cylinders, data=train.auto)
autolda.pred = predict(autolda.fit, test.auto)
table(autolda.pred$class, test.auto$mpg01)
##    
##       0   1
##   0 169  13
##   1  26 183
mean(autolda.pred$class != test.auto$mpg01)
## [1] 0.09974425

Using LDA method to create a classifying model using the variable that was most associated with the mpg01 in (b) resulted in a test error rate of 11.2%.
(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~displacement+horsepower+weight+cylinders, data=train.auto)
autoqda.pred <- predict(autoqda.fit, test.auto)
table(autoqda.pred$class, test.auto$mpg01)
##    
##       0   1
##   0 174  19
##   1  21 177
mean(autoqda.pred$class != test.auto$mpg01)
## [1] 0.1023018

Using QDA method to create a classifying model using the variable that was most associated with the mpg01 in (b) resulted in a test error rate of 11.5%.
(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?

auto.fit=glm(mpg01~displacement+horsepower+weight+cylinders, 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 176  15
##         1  19 181
mean(auto.pred != test.auto$mpg01)
## [1] 0.08695652

Using Logistic Regression method to create a classifying model using the variable that was most associated with the mpg01 in (b) resulted in a test error rate of 9.7%.
(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?

library(e1071)
nbayesauto=naiveBayes(mpg01~displacement+horsepower+weight+cylinders, data=train.auto)
nbayesauto
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##         0         1 
## 0.4571429 0.5428571 
## 
## Conditional probabilities:
##    displacement
## Y       [,1]     [,2]
##   0 271.7396 89.15194
##   1 111.6623 28.27696
## 
##    horsepower
## Y        [,1]     [,2]
##   0 133.14583 38.49319
##   1  77.92105 15.19731
## 
##    weight
## Y       [,1]     [,2]
##   0 3604.823 624.9159
##   1 2314.763 334.7228
## 
##    cylinders
## Y       [,1]      [,2]
##   0 6.812500 1.4165377
##   1 4.070175 0.3928408
nbayesauto.class=predict(nbayesauto,test.auto)
table(nbayesauto.class, test.auto$mpg01)
##                 
## nbayesauto.class   0   1
##                0 171  15
##                1  24 181
mean(nbayesauto.class !=test.auto$mpg01)
## [1] 0.09974425

Using Naive Bayes method to create a classifying model using the variable that was most associated with the mpg01 in (b) resulted in a test error rate of 11.2% which is same as LDA method.
(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?

library(class)
#K=1
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)
table(autok.pred,test.auto$mpg01)
##           
## autok.pred   0   1
##          0 178  11
##          1  17 185
mean(autok.pred != test.auto$mpg01)
## [1] 0.07161125
#K=8
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=8)
table(autok.pred,test.auto$mpg01)
##           
## autok.pred   0   1
##          0 159  12
##          1  36 184
mean(autok.pred != test.auto$mpg01)
## [1] 0.1227621
#K=15
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=15)
table(autok.pred,test.auto$mpg01)
##           
## autok.pred   0   1
##          0 157  15
##          1  38 181
mean(autok.pred != test.auto$mpg01)
## [1] 0.1355499
detach(Auto)

Looking into the results of the K-nearest neighbors, it seems that K=1 has the lowest error rate of 6.9% and with the increase in K value the error rate is also increasing.
#Problem 16: 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. Hint: You will have to create the response variable yourself, using the variables that are contained in the Boston data set.

attach(Boston)
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]
plot(Boston)

from the above plot we can see a correlation between nox,tax,rad,indus, and lstat.

#logistic Regression
set.seed(1)
Boston.fit = glm(crime1~nox + tax + rad + indus + lstat, data = Boston, 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  82  16
##           1   8 147
mean(Boston.pred == crime1.test)
## [1] 0.9051383

Logistic Regression shows 90% of accuracy rate based on the associated predictors.

#Linear Discriminant Analysis
ldaBoston.fit = lda(crime1~nox + tax + rad + indus + lstat, data =  Boston.train)
ldaBoston.pred = predict(ldaBoston.fit, Boston.test)
table(ldaBoston.pred$class, crime1.test)
##    crime1.test
##       0   1
##   0  80  18
##   1  10 145
mean(ldaBoston.pred$class == crime1.test)
## [1] 0.8893281

Linear Discriminant Analysis shows 88.9% of accuracy rate based on the associated predictors.

#Naive Bayes
nbBoston.fit = naiveBayes(crime1~nox + tax + rad + indus + lstat, data = Boston, subset = train)
nbBoston.class = predict(nbBoston.fit, Boston.test)
table(nbBoston.class, crime1.test)
##               crime1.test
## nbBoston.class   0   1
##              0  80  18
##              1  10 145
mean(nbBoston.class == crime1.test)
## [1] 0.8893281

Naive Bayes method shows similar accuracy rate as LDA i.e 88.9% based on the associated predictors.

#KNN for K=1
train.B = cbind(nox,tax,rad,indus,lstat)[train,]
test.B = cbind(nox,tax,rad,indus,lstat)[test,]
train.crime = crime1.test
set.seed(1)
Bostonknn.pred = knn(train.B, test.B, train.crime, k=1)
table(Bostonknn.pred, crime1.test)
##               crime1.test
## Bostonknn.pred   0   1
##              0  34 140
##              1  56  23
mean(Bostonknn.pred == crime1.test)
## [1] 0.2252964
#KNN for K=6
train.B = cbind(nox,tax,rad,indus,lstat)[train,]
test.B = cbind(nox,tax,rad,indus,lstat)[test,]
train.crime = crime1.test
set.seed(1)
Bostonknn.pred = knn(train.B, test.B, train.crime, k=6)
table(Bostonknn.pred, crime1.test)
##               crime1.test
## Bostonknn.pred   0   1
##              0  27  19
##              1  63 144
mean(Bostonknn.pred == crime1.test)
## [1] 0.6758893
#KNN for K=18
train.B = cbind(nox,tax,rad,indus,lstat)[train,]
test.B = cbind(nox,tax,rad,indus,lstat)[test,]
train.crime = crime1.test
set.seed(1)
Bostonknn.pred = knn(train.B, test.B, train.crime, k=18)
table(Bostonknn.pred, crime1.test)
##               crime1.test
## Bostonknn.pred   0   1
##              0  51  23
##              1  39 140
mean(Bostonknn.pred == crime1.test)
## [1] 0.7549407
#KNN for K=22
train.B = cbind(nox,tax,rad,indus,lstat)[train,]
test.B = cbind(nox,tax,rad,indus,lstat)[test,]
train.crime = crime1.test
set.seed(1)
Bostonknn.pred = knn(train.B, test.B, train.crime, k=22)
table(Bostonknn.pred, crime1.test)
##               crime1.test
## Bostonknn.pred   0   1
##              0  41  18
##              1  49 145
mean(Bostonknn.pred == crime1.test)
## [1] 0.7351779

In KNN method we can see for increasing value of K the accuracy rate tend to increase untill certain point and then it starts decreasing.