library(ISLR2)
library(MASS)
library(e1071)
library(corrplot)
library(class)

Applied

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.


a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?

head(Weekly)
##   Year   Lag1   Lag2   Lag3   Lag4   Lag5    Volume  Today Direction
## 1 1990  0.816  1.572 -3.936 -0.229 -3.484 0.1549760 -0.270      Down
## 2 1990 -0.270  0.816  1.572 -3.936 -0.229 0.1485740 -2.576      Down
## 3 1990 -2.576 -0.270  0.816  1.572 -3.936 0.1598375  3.514        Up
## 4 1990  3.514 -2.576 -0.270  0.816  1.572 0.1616300  0.712        Up
## 5 1990  0.712  3.514 -2.576 -0.270  0.816 0.1537280  1.178        Up
## 6 1990  1.178  0.712  3.514 -2.576 -0.270 0.1544440 -1.372      Down
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)

corr <- cor(Weekly[ , -9])
corrplot(corr, method = "ellipse")


  • According to the pairs and correlation plots, only Volume and Year appear to have any relationship. There appears to be a strong positive relationship between the two. This might indicate that as the years go on there is an increase in the total number of shares traded. That may not mean anything in terms of predicting Direction. Other than that there doesn’t appear to be any noticeable relationships between the variables. This could make predicting Direction difficult.


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?

log_fit <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, 
               family = "binomial")

summary(log_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


  • Only the variable Lag2 appears to be statistically significant at the 0.05 level with a p-value of 0.0296. All other variables do not appear to be statistically significant.


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.

log_fit_prob <- predict(log_fit, type = "response")
log_fit_pred <- rep("Down", 1089)
log_fit_pred[log_fit_prob > 0.5] = "Up"

table(log_fit_pred, Weekly$Direction)
##             
## log_fit_pred Down  Up
##         Down   54  48
##         Up    430 557
mean(log_fit_pred == Weekly$Direction)
## [1] 0.5610652


  • The off-diagonal elements of the confusion matrix indicate predictions that were made correctly by the logistic regression model, while the diagonals represent incorrect predictions. This models has a 56.1% accuracy rate.
  • The problem with this is that the model was trained and tested on the same 1089 observations. The training error rate of 43.9% is almost certainly overly optimistic, since the model will perform at least slightly worse on a test data set that was held out from the initial training.


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)
weekly_0910 <- Weekly[!train, ]
direction_0910 <- Weekly$Direction[!train]
dim(weekly_0910)
## [1] 104   9
log_fit2 <- glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = train)
summary(log_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
log_fit_prob2 <- predict(log_fit2, weekly_0910, type = "response")
log_fit_pred2 <- rep("Down", 104)
log_fit_pred2[log_fit_prob2 > 0.5] <- "Up"

table(log_fit_pred2, direction_0910)
##              direction_0910
## log_fit_pred2 Down Up
##          Down    9  5
##          Up     34 56
mean(log_fit_pred2 == direction_0910)
## [1] 0.625


  • The logistic regression model with Lag2 as the only predictor has a test accuracy of 62.5%.


e) Repeat d) using LDA.

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
pred_lda <- predict(lda_fit, weekly_0910)
table(pred_lda$class, direction_0910)
##       direction_0910
##        Down Up
##   Down    9  5
##   Up     34 56
mean(pred_lda$class == direction_0910)
## [1] 0.625


  • The linear discriminant analysis model with Lag2 as the only predictor has a test accuracy of 62.5%.


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
pred_qda <- predict(qda_fit, weekly_0910)
table(pred_qda$class, direction_0910)
##       direction_0910
##        Down Up
##   Down    0  0
##   Up     43 61
mean(pred_qda$class == direction_0910)
## [1] 0.5865385


  • The quadratic discriminant analysis model with Lag2 as the only predictor has a test accuracy of 58.65%. The model predicted “Up” every time for the test data set.


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

train_X <- data.frame(Weekly[train, ]$Lag2)
test_X <- data.frame(Weekly[!train, ]$Lag2)
train_Direction <- Weekly[train, ]$Direction
set.seed(1)

knn_pred <- knn(train_X, test_X, train_Direction, k=1)
table(knn_pred, direction_0910)
##         direction_0910
## knn_pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn_pred == direction_0910)
## [1] 0.5


  • The K nearest neighbor model with k = 1 and with Lag2 as the only predictor has a test accuracy of 50%.


h) Repeat d) using naive Bayes.

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_pred <- predict(nb_fit, weekly_0910)
table(nb_pred, direction_0910)
##        direction_0910
## nb_pred Down Up
##    Down    0  0
##    Up     43 61
mean(nb_pred == direction_0910)
## [1] 0.5865385


  • The naive Bayes model with Lag2 as the only predictor has a test accuracy of 58.65%. The model predicted “Up” every time for the test data set just like the QDA model.


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

Model Test Accuracy
Logistic Regression 62.5%
LDA 62.5%
QDA 58.65%
KNN with k = 1 50%
Naive Bayes 58.65%


  • The methods that appear to provide the best results on this data are the logistic regression and linear discriminant analysis models.


j) Experiment with different combinations of predictors, including possible transformations and iterations, for each of the methods. Report the variables, method, 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 with the interaction between Lag1 and Lag2 as the predictor:

log_fit3 <- glm(Direction ~ Lag1:Lag2, data = Weekly, family = binomial, subset = train)
log_fit_prob3 <- predict(log_fit3, weekly_0910, type = "response")

log_fit_pred3 <- rep("Down", 104)
log_fit_pred3[log_fit_prob3 > 0.5] = "Up"
table(log_fit_pred3, direction_0910)
##              direction_0910
## log_fit_pred3 Down Up
##          Down    1  1
##          Up     42 60
mean(log_fit_pred3 == direction_0910)
## [1] 0.5865385


LDA with the interaction of Lag2 and Lag3 as the predictor:

lda_fit2 <- lda(Direction ~ Lag2:Lag3, data = Weekly, subset = train)
pred_lda2 <- predict(lda_fit2, weekly_0910)
table(pred_lda2$class, direction_0910)
##       direction_0910
##        Down Up
##   Down    0  0
##   Up     43 61
mean(pred_lda2$class == direction_0910)
## [1] 0.5865385


QDA with Lag3 raised to the third power as the predictor:

qda_fit2 <- qda(Direction ~ I(Lag2**3), data = Weekly, subset = train)
pred_qda2 <- predict(qda_fit2, weekly_0910)
table(pred_qda2$class, direction_0910)
##       direction_0910
##        Down Up
##   Down    3  4
##   Up     40 57
mean(pred_qda2$class == direction_0910)
## [1] 0.5769231


KNN with k = 5:

knn_pred2 <- knn(train_X, test_X, train_Direction, k = 5)
table(knn_pred2, direction_0910)
##          direction_0910
## knn_pred2 Down Up
##      Down   15 20
##      Up     28 41
mean(knn_pred2 == direction_0910)
## [1] 0.5384615


KNN with k = 10:

knn_pred3 <- knn(train_X, test_X, train_Direction, k = 10)
table(knn_pred3, direction_0910)
##          direction_0910
## knn_pred3 Down Up
##      Down   17 19
##      Up     26 42
mean(knn_pred3 == direction_0910)
## [1] 0.5673077


  • The methods that worked the best were the logistic regression model with the interaction term of Lag1 and Lag2 and the LDA model with the interaction term of Lag2 and Lag3. The test accuracy for both models is 58.65%. This is slightly less accurate than the logistic regression and LDA models with just Lag2 as the only predictor. The various interactions, transformations, and values for k do not seem to improve the test accuracy of the base models.


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


a) Create a binary variable, mpg01, that contains a 1 if mpg 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 that 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.

Auto1 <- Auto
attach(Auto1)
mpg01 <- ifelse(mpg > median(mpg), 1, 0)
Auto1 <- data.frame(Auto1, mpg01)


b) Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be a useful tools to answer this question. Describe your findings.

par(mfrow = c(2, 3))
plot(factor(mpg01), cylinders, ylab = "Cylinders", xlab = "mpg01")
plot(factor(mpg01), displacement, ylab = "Displacement", xlab = "mpg01")
plot(factor(mpg01), horsepower, ylab = "Horsepower", xlab = "mpg01")
plot(factor(mpg01), weight, ylab = "Weight", xlab = "mpg01")
plot(factor(mpg01), acceleration, ylab = "Acceleration", xlab = "mpg01")
plot(factor(mpg01), year, ylab = "Manufacture year", xlab = "mpg01")


  • Based on the above boxplots, it appears that cars with more engine cylinders, larger engine displacement, more horsepower, and are heavier are more likely to have a miles per gallon rating below the median. The differences between the below-median and above-median groups are pretty stark.
  • It appear cars with higher acceleration and later manufacture years are more likely to have a miles per gallon rating above the median. The differences between the below-median and above-median groups are not nearly as wide.


par(mfrow = c(3, 2))
plot(cylinders, mpg01, xlab = "Cylinders", ylab = "mpg01")
plot(displacement, mpg01, xlab = "Displacement", ylab = "mpg01" )
plot(horsepower, mpg01, xlab = "Horsepower", ylab = "mpg01")
plot(weight, mpg01, xlab = "Weight", ylab = "mpg01")
plot(acceleration, mpg01, xlab = "Acceleration", ylab = "mpg01")
plot(year, mpg01, xlab = "Year", ylab = "mpg01")


  • According to the scatterplots, there appears to be some noticeable separation of mpg01 in the predictor variables Cylinders, Displacement, Horsepower, and Weight. This could mean that those variables could be useful predictors.


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

set.seed(1)
idx <- sample(1:nrow(Auto1), 0.8 * nrow(Auto1))
train_auto <- Auto1[idx, -9]
test_auto <- Auto1[-idx, -9]


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?

auto_lda <- lda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto1, 
                subset = idx)
auto_lda
## Call:
## lda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto1, 
##     subset = idx)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4920128 0.5079872 
## 
## Group means:
##   cylinders displacement horsepower   weight
## 0  6.753247     269.6558   128.0844 3598.026
## 1  4.207547     117.5723    79.8239 2350.283
## 
## Coefficients of linear discriminants:
##                        LD1
## cylinders    -0.3683695573
## displacement -0.0034034169
## horsepower    0.0043232816
## weight       -0.0009434883
pred_lda <- predict(auto_lda, test_auto)
table(pred_lda$class, test_auto$mpg01)
##    
##      0  1
##   0 35  0
##   1  7 37
mean(pred_lda$class != test_auto$mpg01)
## [1] 0.08860759


  • The test error rate is 8.86%.


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?

auto_qda <- qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto1, 
                subset = idx)
auto_qda
## Call:
## qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto1, 
##     subset = idx)
## 
## Prior probabilities of groups:
##         0         1 
## 0.4920128 0.5079872 
## 
## Group means:
##   cylinders displacement horsepower   weight
## 0  6.753247     269.6558   128.0844 3598.026
## 1  4.207547     117.5723    79.8239 2350.283
pred_qda <- predict(auto_qda, test_auto)
table(pred_qda$class, test_auto$mpg01)
##    
##      0  1
##   0 37  2
##   1  5 35
mean(pred_qda$class != test_auto$mpg01)
## [1] 0.08860759


  • The test error rate is 8.86%.


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_glm <- glm(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto1,
                family = binomial, subset = idx)
summary(auto_glm)
## 
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower + 
##     weight, family = binomial, data = Auto1, subset = idx)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.4150  -0.2266   0.1209   0.4166   3.2331  
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  11.5534753  1.8949939   6.097 1.08e-09 ***
## cylinders     0.0518590  0.3680655   0.141  0.88795    
## displacement -0.0111621  0.0085732  -1.302  0.19293    
## horsepower   -0.0380148  0.0155083  -2.451  0.01424 *  
## weight       -0.0021874  0.0007507  -2.914  0.00357 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 433.83  on 312  degrees of freedom
## Residual deviance: 175.13  on 308  degrees of freedom
## AIC: 185.13
## 
## Number of Fisher Scoring iterations: 7
auto_prob <- predict(auto_glm, test_auto, type = "response")
glm_pred <- rep(0, length(auto_prob))
glm_pred[auto_prob > 0.5] <- 1
table(glm_pred, test_auto$mpg01)
##         
## glm_pred  0  1
##        0 38  1
##        1  4 36
mean(glm_pred != test_auto$mpg01)
## [1] 0.06329114


  • The test error rate is 6.33%.


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?

nB_auto <- naiveBayes(mpg01 ~ cylinders + displacement + horsepower + weight, data = Auto1,
                      subset = idx)
nB_auto
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##         0         1 
## 0.4920128 0.5079872 
## 
## Conditional probabilities:
##    cylinders
## Y       [,1]      [,2]
##   0 6.753247 1.4294370
##   1 4.207547 0.7297951
## 
##    displacement
## Y       [,1]     [,2]
##   0 269.6558 85.82353
##   1 117.5723 40.76848
## 
##    horsepower
## Y       [,1]     [,2]
##   0 128.0844 35.44949
##   1  79.8239 16.41647
## 
##    weight
## Y       [,1]     [,2]
##   0 3598.026 668.4909
##   1 2350.283 401.2710
nB_pred <- predict(nB_auto, test_auto)
table(nB_pred, test_auto$mpg01)
##        
## nB_pred  0  1
##       0 37  1
##       1  5 36
mean(nB_pred != test_auto$mpg01)
## [1] 0.07594937


  • The test error rate is 7.59%.


h) Perform KNN on the training data, with several values of K, 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? Which value of K seems to perform the best on this data set?

y_train <- train_auto$mpg01
x_train <- train_auto[ , c(2:5)]

y_test <- test_auto$mpg01
x_test <- test_auto[ , c(2:5)]

K = 1

set.seed(1)

knn_pred <- knn(x_train, x_test, y_train, k = 1)
table(knn_pred, y_test)
##         y_test
## knn_pred  0  1
##        0 36  4
##        1  6 33
mean(knn_pred != y_test)
## [1] 0.1265823


  • The test error rate is 12.66%.


K = 3

knn_pred2 <- knn(x_train, x_test, y_train, k = 3)
table(knn_pred2, y_test)
##          y_test
## knn_pred2  0  1
##         0 38  4
##         1  4 33
mean(knn_pred2 != y_test)
## [1] 0.1012658


  • The test error rate is 10.13%.


K = 10

knn_pred3 <- knn(x_train, x_test, y_train, k = 10)
table(knn_pred3, y_test)
##          y_test
## knn_pred3  0  1
##         0 36  4
##         1  6 33
mean(knn_pred3 != y_test)
## [1] 0.1265823


  • The test error rate is 12.66%.


K = 100

knn_pred4 <- knn(x_train, x_test, y_train, k = 100)
table(knn_pred4, y_test)
##          y_test
## knn_pred4  0  1
##         0 35  3
##         1  7 34
mean(knn_pred4 != y_test)
## [1] 0.1265823


  • The test error rate is 12.66%.

  • The model with K = 3 appears to perform the best on this data.


16. Using the Boston data set, fit classification models in order to predict whether a given census tract has a crime rate above of below the median. Explore logistic regression, LDA, naive Bayes, and KNN models using various subsets of predictors. Describe your findings.

Boston1 <- Boston
attach(Boston1)
crim01 <- ifelse(crim > median(crim), 1, 0)
Boston1 <- data.frame(Boston1, crim01)


Train/Test split

set.seed(1)
idx2 <- sample(1:nrow(Boston1), 0.8 * nrow(Boston1))
train_boston <- Boston1[idx2, ]
test_boston <- Boston1[-idx2, ]


Logistic Regression

bos_glm <- glm(crim01 ~ . -crim, data = Boston1, family = binomial, subset = idx2)
summary(bos_glm)
## 
## Call:
## glm(formula = crim01 ~ . - crim, family = binomial, data = Boston1, 
##     subset = idx2)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0320  -0.1436  -0.0001   0.0016   3.6189  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -42.886750   7.627711  -5.622 1.88e-08 ***
## zn           -0.106512   0.042954  -2.480 0.013149 *  
## indus        -0.064955   0.051562  -1.260 0.207759    
## chas          0.473349   0.786069   0.602 0.547059    
## nox          56.659757   9.246096   6.128 8.90e-10 ***
## rm           -0.116177   0.846737  -0.137 0.890868    
## age           0.021587   0.013568   1.591 0.111610    
## dis           1.068641   0.278562   3.836 0.000125 ***
## rad           0.696528   0.175753   3.963 7.40e-05 ***
## tax          -0.007585   0.003075  -2.466 0.013646 *  
## ptratio       0.362327   0.148310   2.443 0.014564 *  
## black        -0.010208   0.005643  -1.809 0.070462 .  
## lstat         0.078033   0.055794   1.399 0.161939    
## medv          0.165209   0.080364   2.056 0.039806 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 560.06  on 403  degrees of freedom
## Residual deviance: 159.83  on 390  degrees of freedom
## AIC: 187.83
## 
## Number of Fisher Scoring iterations: 9
bos_prob <- predict(bos_glm, test_boston, type = "response")
bospred_glm <- rep(0, length(bos_prob))
bospred_glm[bos_prob > 0.5] <- 1
table(bospred_glm, test_boston$crim01)
##            
## bospred_glm  0  1
##           0 43  5
##           1  8 46
mean(bospred_glm != test_boston$crim01)
## [1] 0.127451


Logistic Regression with significant predictors

bos_glm2 <- glm(crim01 ~ zn + nox + dis + rad + tax + ptratio + medv, data = Boston1, 
                family = binomial, subset = idx2)
summary(bos_glm2)
## 
## Call:
## glm(formula = crim01 ~ zn + nox + dis + rad + tax + ptratio + 
##     medv, family = binomial, data = Boston1, subset = idx2)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.2450  -0.1983  -0.0004   0.0022   3.3258  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -38.719704   6.147925  -6.298 3.01e-10 ***
## zn           -0.092672   0.036109  -2.566  0.01027 *  
## nox          51.492732   7.695414   6.691 2.21e-11 ***
## dis           0.770301   0.237990   3.237  0.00121 ** 
## rad           0.738695   0.155941   4.737 2.17e-06 ***
## tax          -0.008533   0.002742  -3.112  0.00186 ** 
## ptratio       0.302910   0.124092   2.441  0.01465 *  
## medv          0.085076   0.033196   2.563  0.01038 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 560.06  on 403  degrees of freedom
## Residual deviance: 173.51  on 396  degrees of freedom
## AIC: 189.51
## 
## Number of Fisher Scoring iterations: 9
bos_prob2 <- predict(bos_glm2, test_boston, type = "response")
bospred_glm2 <- rep(0, length(bos_prob))
bospred_glm2[bos_prob2 > 0.5] <- 1
table(bospred_glm2, test_boston$crim01)
##             
## bospred_glm2  0  1
##            0 44  6
##            1  7 45
mean(bospred_glm2 != test_boston$crim01)
## [1] 0.127451


LDA

bos_lda <- lda(crim01 ~ zn + nox + dis + rad + tax + ptratio + medv, data = Boston1,
               subset = idx2)
bos_lda
## Call:
## lda(crim01 ~ zn + nox + dis + rad + tax + ptratio + medv, data = Boston1, 
##     subset = idx2)
## 
## Prior probabilities of groups:
##   0   1 
## 0.5 0.5 
## 
## Group means:
##          zn       nox      dis       rad      tax  ptratio     medv
## 0 21.631188 0.4704243 5.036025  4.148515 309.4109 17.89307 25.28960
## 1  1.108911 0.6356634 2.532918 15.099010 513.8812 19.11931 20.43119
## 
## Coefficients of linear discriminants:
##                  LD1
## zn      -0.007200388
## nox      9.759752703
## dis     -0.005351261
## rad      0.082365854
## tax     -0.001156148
## ptratio  0.074340151
## medv     0.027899465
bospred_lda <- predict(bos_lda, test_boston)
table(bospred_lda$class, test_boston$crim01)
##    
##      0  1
##   0 50 14
##   1  1 37
mean(bospred_lda$class != test_boston$crim01)
## [1] 0.1470588


QDA

bos_qda <- qda(crim01 ~ zn + nox + dis + rad + tax + ptratio + medv, data = Boston1,
               subset = idx2)
bos_qda
## Call:
## qda(crim01 ~ zn + nox + dis + rad + tax + ptratio + medv, data = Boston1, 
##     subset = idx2)
## 
## Prior probabilities of groups:
##   0   1 
## 0.5 0.5 
## 
## Group means:
##          zn       nox      dis       rad      tax  ptratio     medv
## 0 21.631188 0.4704243 5.036025  4.148515 309.4109 17.89307 25.28960
## 1  1.108911 0.6356634 2.532918 15.099010 513.8812 19.11931 20.43119
bospred_qda <- predict(bos_qda, test_boston)
table(bospred_qda$class, test_boston$crim01)
##    
##      0  1
##   0 45  4
##   1  6 47
mean(bospred_qda$class != test_boston$crim01)
## [1] 0.09803922


Naive Bayes

nB_bos <- naiveBayes(crim01 ~ zn + nox + dis + rad + tax + ptratio + medv, data = Boston1,
                     subset = idx2)
nB_bos
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##   0   1 
## 0.5 0.5 
## 
## Conditional probabilities:
##    zn
## Y        [,1]      [,2]
##   0 21.631188 29.185014
##   1  1.108911  4.635792
## 
##    nox
## Y        [,1]       [,2]
##   0 0.4704243 0.05641035
##   1 0.6356634 0.09880639
## 
##    dis
## Y       [,1]     [,2]
##   0 5.036025 2.105805
##   1 2.532918 1.122580
## 
##    rad
## Y        [,1]     [,2]
##   0  4.148515 1.674427
##   1 15.099010 9.521387
## 
##    tax
## Y       [,1]      [,2]
##   0 309.4109  92.92116
##   1 513.8812 167.20743
## 
##    ptratio
## Y       [,1]     [,2]
##   0 17.89307 1.818466
##   1 19.11931 2.283441
## 
##    medv
## Y       [,1]      [,2]
##   0 25.28960  7.420105
##   1 20.43119 10.676765
nB_bospred <- predict(nB_bos, test_boston)
table(nB_bospred, test_boston$crim01)
##           
## nB_bospred  0  1
##          0 45 15
##          1  6 36
mean(nB_bospred != test_boston$crim01)
## [1] 0.2058824


KNN with K = 5

knn_train <- cbind(zn, nox, dis, rad, tax, ptratio, medv)[idx2, ]
knn_test <- cbind(zn, nox, dis, rad, tax, ptratio, medv)[-idx2, ]

train_crim01 <- train_boston$crim01
test_crim01 <- test_boston$crim01
set.seed(1)

bos_knn <- knn(knn_train, knn_test, train_crim01, k = 5)
table(bos_knn, test_crim01)
##        test_crim01
## bos_knn  0  1
##       0 45  3
##       1  6 48
mean(bos_knn != test_crim01)
## [1] 0.08823529


KNN with K = 10

bos_knn2 <- knn(knn_train, knn_test, train_crim01, k = 10)
table(bos_knn2, test_crim01)
##         test_crim01
## bos_knn2  0  1
##        0 44  4
##        1  7 47
mean(bos_knn2 != test_crim01)
## [1] 0.1078431

KNN with K = 3

bos_knn3 <- knn(knn_train, knn_test, train_crim01, k = 3)
table(bos_knn3, test_crim01)
##         test_crim01
## bos_knn3  0  1
##        0 49  3
##        1  2 48
mean(bos_knn3 != test_crim01)
## [1] 0.04901961


Results

Model Test Accuracy Error Rate
Logistic Regression with all predictors 12.75%
Logistic Regression with significant predictors 12.75%
LDA 14.71%
QDA 9.80%
Naive Bayes 20.59%
KNN with k = 3 4.90%
KNN with k = 5 8.82%
KNN with k = 10 10.78%


  • After running various classification models on the Boston data set to try and predict whether the crime rate will be above or below the median crime rate, we see that both logistic regression models perform almost identically. The second model only had the predictors that were statistically significant at the 0.05 level. Since the performance was so similar I went with those predictors for the preceding models.

  • The KNN models appear to perform the best on this data. The two best models overall were the KNN with k = 3 and k = 5, while the model with k = 10 was right behind the QDA model in terms of test error rate.

  • The models that performed the worst were the naive Bayes and the LDA models, with both logistic regression models not faring too much better.