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.

plot(Weekly)

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  
##            
##            
##            
## 

There appears to be a linear correlation with year and volume. Since technology is constantly advancing as years pass by, it makes it more accessible for people to trade more.

13b. 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?

## 
## 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 intercept and lag2 are statistically significant since they are less than the significance level 0.05.

13c. 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.

contrasts(Weekly$Direction)
##      Up
## Down  0
## Up    1
p_hat <- predict(five_lag_model, newdata = Weekly, type = "response")
y_hat <- rep("Down", length(p_hat))
y_hat[p_hat > 0.5] <- "Up"
CM <- table(predicted = y_hat, truth = Weekly$Direction)
CM
##          truth
## predicted Down  Up
##      Down   54  48
##      Up    430 557

The confusion matrix shows that 611 observations were correctly classified however 478 observations were incorrectly classified. 56.11% of the observations were classfied correctly.

13d 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).

Weekly.train <- (Weekly$Year >= 1990) & (Weekly$Year <= 2008)  # our training set 
Weekly.test <- (Weekly$Year >= 2009)  # our testing set 
lag2_model <- glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = Weekly.train)

# CM on test data :
p_hat <- predict(lag2_model, newdata = Weekly[Weekly.test, ], type = "response")
y_hat <- rep("Down", length(p_hat))
y_hat[p_hat > 0.5] <- "Up"
CM <- table(predicted = y_hat, truth = Weekly[Weekly.test, ]$Direction)
CM
##          truth
## predicted Down Up
##      Down    9  5
##      Up     34 56

After only keeping the signifcant predictors, we have 65 observations correctly classfied. We went from 56.11% to 62.5% correctly classified.

13e Repeat (d) using LDA

library(class)
library(MASS)

lda.fit <- lda(Direction ~ Lag2, data = Weekly, subset = Weekly.train)

lda.predict <- predict(lda.fit, newdata = Weekly[Weekly.test, ])
CM <- table(predicted = lda.predict$class, truth = Weekly[Weekly.test, ]$Direction)
CM
##          truth
## predicted Down Up
##      Down    9  5
##      Up     34 56

We still get the same percentage, 62.5%, of observations correctly classified given by the linear discriminant anaylsis.

13f Repeat (d) using QDA.

qda.fit <- qda(Direction ~ Lag2, data = Weekly, subset = Weekly.train)

qda.predict <- predict(qda.fit, newdata = Weekly[Weekly.test, ])
CM <- table(predicted = qda.predict$class, truth = Weekly[Weekly.test, ]$Direction)
CM
##          truth
## predicted Down Up
##      Down    0  0
##      Up     43 61

Here we can see that 58.65% of the observations are correctly classified using the quadratic discriminant anaylsis.

13g Repeat (d) using KNN with K = 1.

X.train <- data.frame(Lag2 = Weekly[Weekly.train, ]$Lag2)
Y.train <- Weekly[Weekly.train, ]$Direction

X.test <- data.frame(Lag2 = Weekly[Weekly.test, ]$Lag2)

y_hat_k_1 <- knn(X.train, X.test, Y.train, k = 1)

CM <- table(predicted = y_hat_k_1, truth = Weekly[Weekly.test, ]$Direction)
CM
##          truth
## predicted Down Up
##      Down   21 30
##      Up     22 31

There are 52 observations that were correctly classfied and 52 incorrectly classified. 50% of observations were correctly classified using the KNN method.

13h Repeat (d) using naive Bayes.

library(e1071)
train <- (Weekly$Year < 2009)
test <- Weekly[!train,]
test.target <- Weekly$Direction[!train]


nb.fit <- naiveBayes(Direction ~ Lag2,
                     data = Weekly,
                     subset = train)
nb.fit
## 
## 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
nb.class <- predict(nb.fit, test)
table(nb.class, test.target)
##         test.target
## nb.class Down Up
##     Down    0  0
##     Up     43 61
mean(nb.class == test.target)
## [1] 0.5865385

With the naive Bayes classier, we achieve an accuracy of 58.6%.

13i Which of these methods appears to provide the best results on this data?

The linear discriminant analysis and Logistic Regression gave the best result for this data by having 62.5% of the observations correctly classified. The KNN method produced the worst results of 50% of the observations being correctly classified.

13j 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.

cor(Weekly[1:8])
##               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
lr.fit <- glm(Direction ~ Lag2 + poly(Year,3),
              data = Weekly,
              family = binomial,
              subset = train)
lr.prob <- predict(lr.fit,
                   test,
                   type = "response")
lr.pred <- rep("Down", 104)
lr.pred[lr.prob > .5] <- "Up"


table(lr.pred, test.target)
##        test.target
## lr.pred Down Up
##    Down   10  5
##    Up     33 56
mean(lr.pred == test.target)
## [1] 0.6346154

For Logistic Regression, there is an accuracy of 63.46% when using the variable Lag 2 and poly(Year, 3). An improvement from only using the variable Lag 2 and the intercept.

names(Weekly)
## [1] "Year"      "Lag1"      "Lag2"      "Lag3"      "Lag4"      "Lag5"     
## [7] "Volume"    "Today"     "Direction"
qda.fit <- qda(Direction ~ poly(Lag2,2),
               data = Weekly,
               subset = train)
qda.pred <- predict(qda.fit,
                    test,
                    type = "response")

qda.class <- qda.pred$class

table(qda.class, test.target)
##          test.target
## qda.class Down Up
##      Down    7  3
##      Up     36 58
mean(qda.class == test.target)
## [1] 0.625

Using Quadratic Discriminant Analysis, an accuracy of 62.5% with the variables poly(Lag 2, 2). Again, an improvement is seen from only using Lag 2 and the intercept.

nb.fit <- naiveBayes(Direction ~ Lag2,
                     data = Weekly,
                     subset = train)
nb.fit
## 
## 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
nb.class <- predict(nb.fit, test)
table(nb.class, test.target)
##         test.target
## nb.class Down Up
##     Down    0  0
##     Up     43 61
mean(nb.class == test.target)
## [1] 0.5865385

Naive Bayes Classier has the same accuracy of 58.65%.

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.

14a 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)
## The following object is masked from package:ggplot2:
## 
##     mpg
mpgMed <- median(Auto$mpg)

# Create mpg01
mpg01 <- rep(0,392)
mpg01[Auto$mpg > mpgMed] <- 1

mod_df <- Auto
mod_df$mpg01 <- mpg01

# Add mpg01 to Auto data set
Auto$mpg01 <- mpg01

14b 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, 2))

# Examine relationship between mpg01 & cylinders
plot(as.factor(Auto$mpg01), Auto$cylinders, xlab="mpg01", ylab="cylinders")

# Examine relationship between mpg01 & displacement
plot(as.factor(Auto$mpg01), Auto$displacement, xlab="mpg01", ylab="displacement")

# Examine relationship between mpg01 & horsepower
plot(as.factor(Auto$mpg01), Auto$horsepower, xlab="mpg01", ylab="horsepower")

# Examine relationship between mpg01 & weight
plot(as.factor(Auto$mpg01), Auto$weight, xlab="mpg01", ylab="weight")

mod_df <- subset(mod_df, select = -c(mpg))


cor(mod_df[, names(mod_df) != "name"])
##               cylinders displacement horsepower     weight acceleration
## cylinders     1.0000000    0.9508233  0.8429834  0.8975273   -0.5046834
## displacement  0.9508233    1.0000000  0.8972570  0.9329944   -0.5438005
## horsepower    0.8429834    0.8972570  1.0000000  0.8645377   -0.6891955
## weight        0.8975273    0.9329944  0.8645377  1.0000000   -0.4168392
## acceleration -0.5046834   -0.5438005 -0.6891955 -0.4168392    1.0000000
## year         -0.3456474   -0.3698552 -0.4163615 -0.3091199    0.2903161
## origin       -0.5689316   -0.6145351 -0.4551715 -0.5850054    0.2127458
## mpg01        -0.7591939   -0.7534766 -0.6670526 -0.7577566    0.3468215
##                    year     origin      mpg01
## cylinders    -0.3456474 -0.5689316 -0.7591939
## displacement -0.3698552 -0.6145351 -0.7534766
## horsepower   -0.4163615 -0.4551715 -0.6670526
## weight       -0.3091199 -0.5850054 -0.7577566
## acceleration  0.2903161  0.2127458  0.3468215
## year          1.0000000  0.1815277  0.4299042
## origin        0.1815277  1.0000000  0.5136984
## mpg01         0.4299042  0.5136984  1.0000000
pairs(mod_df[, names(mod_df) != "name"], col=2)

We can see that cylinders, horsepower, weight and displacement appear to have a negative correlation with mpg01. From the boxplots we can see that, horsepower, weight, and displacement may be related to a higher mpg than the median mpg. However cylinders seems to be an excpetion and possibly inconclusive.

14c Split the data into a training set and a test set.

train <- (1:(392*.8))
test <- mod_df[(392*.8):392,]
test.target <- mpg01[(392*.8):392]

14d 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?

lda.fit <- lda(mpg01 ~ cylinders + weight + displacement + horsepower,
               data = mod_df,
               subset = train)
lda.pred <- predict(lda.fit,
                    test,
                    type = "response")

lda.class <- lda.pred$class

table(lda.class, test.target)
##          test.target
## lda.class  0  1
##         0  5 11
##         1  0 63
1 - mean(lda.class == test.target)
## [1] 0.1392405

We have a 13.92% error of the model using linear discriminant analysis.

14e 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 = mod_df,
               subset = train)
qda.pred <- predict(qda.fit,
                    test,
                    type = "response")

qda.class <- qda.pred$class

table(qda.class, test.target)
##          test.target
## qda.class  0  1
##         0  5 11
##         1  0 63
1 - mean(qda.class == test.target)
## [1] 0.1392405

We get the same error rate of 13.92% for the quadratic discriminant anaylsis.

14f 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?

lr.fit <- glm(mpg01 ~ cylinders + displacement + weight,
              data = mod_df,
              family = binomial,
              subset = train)
lr.prob <- predict(lr.fit,
                   test,
                   type = "response")
lr.pred <- rep(0, 102)
lr.pred[lr.prob > .5] <- 1


mean(lr.pred == test.target)
## Warning in lr.pred == test.target: longer object length is not a multiple of
## shorter object length
## [1] 0.7843137

There is a 78.43% error rate when using the a logistic regression.

14g 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)

nb.fit <- naiveBayes(mpg01 ~ cylinders + weight + displacement + horsepower,
                     data = mod_df,
                     subset = train)
nb.fit
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##         0         1 
## 0.6102236 0.3897764 
## 
## Conditional probabilities:
##    cylinders
## Y       [,1]      [,2]
##   0 6.785340 1.4330662
##   1 4.139344 0.6207909
## 
##    weight
## Y       [,1]     [,2]
##   0 3630.592 681.6461
##   1 2276.852 382.7028
## 
##    displacement
## Y       [,1]     [,2]
##   0 274.4817 90.29308
##   1 111.8320 36.44659
## 
##    horsepower
## Y        [,1]     [,2]
##   0 130.97906 37.40377
##   1  78.51639 15.64283
nb.class <- predict(nb.fit, test)
table(nb.class, test.target)
##         test.target
## nb.class  0  1
##        0  5  8
##        1  0 66
1- mean(nb.class == test.target)
## [1] 0.1012658

We have a 10.13% error for the model using the naives Bayes classfier.

13h 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?

attach(mod_df)
## The following object is masked _by_ .GlobalEnv:
## 
##     mpg01
## The following objects are masked from Auto:
## 
##     acceleration, cylinders, displacement, horsepower, name, origin,
##     weight, year
#create training and test matrices and train-target array
training_set <- cbind(cylinders, weight, displacement, horsepower)[(1:(392*.8)),]
testing_set <- cbind(cylinders, weight, displacement, horsepower)[(392*.8):392,]
training_targets <- mpg01[train]

set.seed(1)

knn.pred <- knn(train = training_set, test = testing_set, cl = training_targets, k=4)
table(knn.pred, test.target)
##         test.target
## knn.pred  0  1
##        0  5 20
##        1  0 54
1 - (5 + 57)/79 #21.5% error rate k=1
## [1] 0.2151899
1 - (5 + 55)/79 #24.1% error rate k=2
## [1] 0.2405063
1 - (5 + 54)/79 #25.3% error rate k=3
## [1] 0.2531646
1 - (5 + 53)/79 #26.6% error rate k=4
## [1] 0.2658228

The error rates for k equals 1, 2, 3, 4 are as follow, 21.5%, 24.05%, 25.31%, and 26.58%.

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 finding

attach(Boston)

crim01 <- rep(0, length(crim))
crim01[crim > median(crim)] = 1
mod_df <- Boston
mod_df$crim01 <- crim01
#remove original mpg variable
mod_df <- subset(mod_df, select = -c(crim))

cor(mod_df)
##                  zn       indus         chas         nox          rm
## zn       1.00000000 -0.53382819 -0.042696719 -0.51660371  0.31199059
## indus   -0.53382819  1.00000000  0.062938027  0.76365145 -0.39167585
## chas    -0.04269672  0.06293803  1.000000000  0.09120281  0.09125123
## nox     -0.51660371  0.76365145  0.091202807  1.00000000 -0.30218819
## rm       0.31199059 -0.39167585  0.091251225 -0.30218819  1.00000000
## age     -0.56953734  0.64477851  0.086517774  0.73147010 -0.24026493
## dis      0.66440822 -0.70802699 -0.099175780 -0.76923011  0.20524621
## rad     -0.31194783  0.59512927 -0.007368241  0.61144056 -0.20984667
## tax     -0.31456332  0.72076018 -0.035586518  0.66802320 -0.29204783
## ptratio -0.39167855  0.38324756 -0.121515174  0.18893268 -0.35550149
## black    0.17552032 -0.35697654  0.048788485 -0.38005064  0.12806864
## lstat   -0.41299457  0.60379972 -0.053929298  0.59087892 -0.61380827
## medv     0.36044534 -0.48372516  0.175260177 -0.42732077  0.69535995
## crim01  -0.43615103  0.60326017  0.070096774  0.72323480 -0.15637178
##                 age         dis          rad         tax    ptratio       black
## zn      -0.56953734  0.66440822 -0.311947826 -0.31456332 -0.3916785  0.17552032
## indus    0.64477851 -0.70802699  0.595129275  0.72076018  0.3832476 -0.35697654
## chas     0.08651777 -0.09917578 -0.007368241 -0.03558652 -0.1215152  0.04878848
## nox      0.73147010 -0.76923011  0.611440563  0.66802320  0.1889327 -0.38005064
## rm      -0.24026493  0.20524621 -0.209846668 -0.29204783 -0.3555015  0.12806864
## age      1.00000000 -0.74788054  0.456022452  0.50645559  0.2615150 -0.27353398
## dis     -0.74788054  1.00000000 -0.494587930 -0.53443158 -0.2324705  0.29151167
## rad      0.45602245 -0.49458793  1.000000000  0.91022819  0.4647412 -0.44441282
## tax      0.50645559 -0.53443158  0.910228189  1.00000000  0.4608530 -0.44180801
## ptratio  0.26151501 -0.23247054  0.464741179  0.46085304  1.0000000 -0.17738330
## black   -0.27353398  0.29151167 -0.444412816 -0.44180801 -0.1773833  1.00000000
## lstat    0.60233853 -0.49699583  0.488676335  0.54399341  0.3740443 -0.36608690
## medv    -0.37695457  0.24992873 -0.381626231 -0.46853593 -0.5077867  0.33346082
## crim01   0.61393992 -0.61634164  0.619786249  0.60874128  0.2535684 -0.35121093
##              lstat       medv      crim01
## zn      -0.4129946  0.3604453 -0.43615103
## indus    0.6037997 -0.4837252  0.60326017
## chas    -0.0539293  0.1752602  0.07009677
## nox      0.5908789 -0.4273208  0.72323480
## rm      -0.6138083  0.6953599 -0.15637178
## age      0.6023385 -0.3769546  0.61393992
## dis     -0.4969958  0.2499287 -0.61634164
## rad      0.4886763 -0.3816262  0.61978625
## tax      0.5439934 -0.4685359  0.60874128
## ptratio  0.3740443 -0.5077867  0.25356836
## black   -0.3660869  0.3334608 -0.35121093
## lstat    1.0000000 -0.7376627  0.45326273
## medv    -0.7376627  1.0000000 -0.26301673
## crim01   0.4532627 -0.2630167  1.00000000
pairs(mod_df)

length(mod_df[,1])
## [1] 506

Nox, Chas, Age, Dis, Rad, Tax, Indus have a high correlation with crim01.

train <- (1:(506*.8))
test <- mod_df[(506*.8):506,]
test.target <- crim01[(506*.8):506]
attach(mod_df)
## The following object is masked _by_ .GlobalEnv:
## 
##     crim01
## The following objects are masked from Boston:
## 
##     age, black, chas, dis, indus, lstat, medv, nox, ptratio, rad, rm,
##     tax, zn
lr.fit <- glm(crim01 ~ nox + chas + age + dis + rad + tax + indus,
              data = mod_df,
              family = binomial,
              subset = train)
lr.prob <- predict(lr.fit,
                   test,
                   type = "response")
lr.pred <- rep(0, 102)
lr.pred[lr.prob > .5] <- 1

table(lr.pred, test.target)
##        test.target
## lr.pred  0  1
##       0  8  0
##       1  6 88
mean(lr.pred == test.target)
## [1] 0.9411765

With a logistic regression model, there is a 94.11% accuracy.

lda.fit <- lda(crim01 ~ nox + chas + age + dis + rad + tax + indus,
               data = mod_df,
               subset = train)
lda.pred <- predict(lda.fit,
                    test,
                    type = "response")

lda.class <- lda.pred$class

table(lda.class, test.target)
##          test.target
## lda.class  0  1
##         0  2  1
##         1 12 87
mean(lda.class == test.target)
## [1] 0.872549

The linear discrimant anaylsis yeilds a 87.25% accuracy.

nb.fit <- naiveBayes(crim01 ~ nox + chas + age + dis + rad + tax + indus,
                     data = mod_df,
                     subset = train)
nb.fit
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##         0         1 
## 0.5891089 0.4108911 
## 
## Conditional probabilities:
##    nox
## Y        [,1]       [,2]
##   0 0.4635324 0.04832517
##   1 0.6295120 0.11107163
## 
##    chas
## Y         [,1]      [,2]
##   0 0.05462185 0.2277195
##   1 0.13253012 0.3400921
## 
##    age
## Y       [,1]     [,2]
##   0 49.58824 25.31259
##   1 85.70301 19.19339
## 
##    dis
## Y       [,1]     [,2]
##   0 5.270933 2.013840
##   1 2.601809 1.254952
## 
##    rad
## Y        [,1]     [,2]
##   0  4.189076 1.625861
##   1 10.518072 8.705779
## 
##    tax
## Y       [,1]      [,2]
##   0 296.1261  66.36347
##   1 434.3253 156.92118
## 
##    indus
## Y        [,1]     [,2]
##   0  6.406639 4.715931
##   1 13.940723 6.225752
nb.class <- predict(nb.fit, test)
table(nb.class, test.target)
##         test.target
## nb.class  0  1
##        0  1  1
##        1 13 87
mean(nb.class == test.target)
## [1] 0.8627451

The naive Bayes classier yeilds a 86.27% accuracy.

training_set <- cbind.data.frame(nox, chas, age, dis, rad, tax, indus)[(1:(506*.8)),]
testing_set <- cbind.data.frame(nox, chas, age, dis, rad, tax, indus)[(506*.8):506,]
training_targets <- crim01[1:(506*.8)]

set.seed(1)

knn.pred <- knn(train = training_set, test = testing_set, cl = training_targets, k=12)
table(knn.pred, test.target)
##         test.target
## knn.pred  0  1
##        0  7  3
##        1  7 85

The accuracy rate for KNN Classifer is 90.19%.