Chapter 4

Question 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)
library(class)
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
library(e1071)
  1. 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)

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

The only notable correlation is between Year and Volume with the lag variables and today’s return are all very close to 0.

  1. 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)
## 
## 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 predictor that appears to be statistically significant is Lag2 with 0.0296 as the p-value

  1. 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_probs <- predict(log_fit, type = "response")

log_pred <- rep("Down", length(log_probs))
log_pred[log_probs > 0.5] <- "Up"

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

Checking the matrix reveals the model predicts “Up” the vast majority of the time. The overall training accuracy is roughly 56.1%

  1. 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_idx <- (Weekly$Year <= 2008)
weekly_train <- Weekly[train_idx, ]
weekly_test  <- Weekly[!train_idx, ]

log_fit_sub <- glm(Direction ~ Lag2, data = weekly_train, family = binomial)

log_probs_sub <- predict(log_fit_sub, weekly_test, type = "response")
log_pred_sub  <- rep("Down", length(log_probs_sub))
log_pred_sub[log_probs_sub > 0.5] <- "Up"

table(Predicted = log_pred_sub, Actual = weekly_test$Direction)
##          Actual
## Predicted Down Up
##      Down    9  5
##      Up     34 56
mean(log_pred_sub == weekly_test$Direction)
## [1] 0.625

The test accuracy using just Lag2 climbs to approximately 62.5%

  1. Repeat (d) using LDA.
lda_fit <- lda(Direction ~ Lag2, data = weekly_train)
lda_pred <- predict(lda_fit, weekly_test)

table(Predicted = lda_pred$class, Actual = weekly_test$Direction)
##          Actual
## Predicted Down Up
##      Down    9  5
##      Up     34 56
mean(lda_pred$class == weekly_test$Direction)
## [1] 0.625

The test accuracy matches the logistic regression model exactly.

  1. Repeat (d) using QDA.
qda_fit <- qda(Direction ~ Lag2, data = weekly_train)
qda_pred <- predict(qda_fit, weekly_test)

table(Predicted = qda_pred$class, Actual = weekly_test$Direction)
##          Actual
## Predicted Down Up
##      Down    0  0
##      Up     43 61
mean(qda_pred$class == weekly_test$Direction)
## [1] 0.5865385

The test accuracy is roughly 58.7%. The QDA predicts “Up” for every single week in the test set. Because the test set contains more “Up” weeks than “Down”, it achieves 58.7% by default choice, failing to capture any true downward variations.

  1. Repeat (d) using KNN with K =1.
train_X <- as.matrix(weekly_train$Lag2)
test_X  <- as.matrix(weekly_test$Lag2)
train_Y <- weekly_train$Direction

knn_pred <- knn(train_X, test_X, train_Y, k = 1)

table(Predicted = knn_pred, Actual = weekly_test$Direction)
##          Actual
## Predicted Down Up
##      Down   21 29
##      Up     22 32
mean(knn_pred == weekly_test$Direction)
## [1] 0.5096154

K=1 yields a test accuracy of 50% this indicates that a single nearest neighbor is too flexible and fits too much noise in the return data

  1. Repeat (d) using naive Bayes.
nb_fit <- naiveBayes(Direction ~ Lag2, data = weekly_train)
nb_pred <- predict(nb_fit, weekly_test)

table(Predicted = nb_pred, Actual = weekly_test$Direction)
##          Actual
## Predicted Down Up
##      Down    0  0
##      Up     43 61
mean(nb_pred == weekly_test$Direction)
## [1] 0.5865385

Results mirror QDA with 58.7%

  1. Which of these methods appears to provide the best results on this data?

Comparing test accuracy, Logistic Regression and LDA tied for the highest test accuracy at 62.5%.

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

  1. 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.
median_mpg <- median(Auto$mpg)

mpg01 <- ifelse(Auto$mpg > median_mpg, 1, 0)
Auto_df <- data.frame(Auto, mpg01)
  1. 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))
boxplot(cylinders ~ mpg01, data = Auto_df, main = "Cylinders")
boxplot(displacement ~ mpg01, data = Auto_df, main = "Displacement")
boxplot(horsepower ~ mpg01, data = Auto_df, main = "Horsepower")
boxplot(weight ~ mpg01, data = Auto_df, main = "Weight")
boxplot(acceleration ~ mpg01, data = Auto_df, main = "Acceleration")
boxplot(year ~ mpg01, data = Auto_df, main = "Model Year")

Strong separation in the medians exists for weight, horsepower, and displacement, and cylinders.

  1. Split the data into a training set and a test set.
sample_size <- floor(0.70 * nrow(Auto_df))
set.seed(1)
train_idx <- sample(seq_len(nrow(Auto_df)), size = sample_size)

auto_train <- Auto_df[train_idx, ]
auto_test  <- Auto_df[-train_idx, ]
  1. 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_auto <- lda(mpg01 ~ weight + horsepower + displacement + cylinders, data = auto_train)
lda_auto_pred <- predict(lda_auto, auto_test)

table(Predicted = lda_auto_pred$class, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 50  3
##         1 11 54
mean(lda_auto_pred$class != auto_test$mpg01)
## [1] 0.1186441
  1. 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_auto <- qda(mpg01 ~ weight + horsepower + displacement + cylinders, data = auto_train)
qda_auto_pred <- predict(qda_auto, auto_test)

table(Predicted = qda_auto_pred$class, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 52  5
##         1  9 52
mean(qda_auto_pred$class != auto_test$mpg01)
## [1] 0.1186441
  1. 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?
log_auto <- glm(mpg01 ~ weight + horsepower + displacement + cylinders, 
                data = auto_train, 
                family = binomial)
log_auto_probs <- predict(log_auto, auto_test, type = "response")
log_auto_pred  <- ifelse(log_auto_probs > 0.5, 1, 0)

table(Predicted = log_auto_pred, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 53  3
##         1  8 54
mean(log_auto_pred != auto_test$mpg01)
## [1] 0.09322034
  1. 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 ~ weight + horsepower + displacement + cylinders, data = auto_train)
nb_auto_pred <- predict(nb_auto, auto_test)

table(Predicted = nb_auto_pred, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 52  4
##         1  9 53
mean(nb_auto_pred != auto_test$mpg01)
## [1] 0.1101695
  1. 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?
train_X_auto <- scale(auto_train[, c("weight", "horsepower", "displacement", "cylinders")])
test_X_auto  <- scale(auto_test[, c("weight", "horsepower", "displacement", "cylinders")])
train_Y_auto <- auto_train$mpg01

for (kv in c(1, 5, 10, 20, 50)) {
  set.seed(1)
  knn_auto_pred <- knn(train_X_auto, test_X_auto, train_Y_auto, k = kv)
  error_rate <- mean(knn_auto_pred != auto_test$mpg01)
  cat(stringr::str_interp("K = ${kv} | Test Error Rate: ${round(error_rate, 4)}\n"))
}
## K = 1 | Test Error Rate: 0.1441
## K = 5 | Test Error Rate: 0.1356
## K = 10 | Test Error Rate: 0.1356
## K = 20 | Test Error Rate: 0.1102
## K = 50 | Test Error Rate: 0.1102

For this data split, KNN with K=20 and K=50 performed optimally among the neighborhood models, yielding a test error rate of 11.02%.

Question 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

median_crim <- median(Boston$crim)

crim01 <- ifelse(Boston$crim > median_crim, 1, 0)
Boston_df <- data.frame(Boston, crim01)
cor(Boston)[, "crim"]
##        crim          zn       indus        chas         nox          rm 
##  1.00000000 -0.20046922  0.40658341 -0.05589158  0.42097171 -0.21924670 
##         age         dis         rad         tax     ptratio       black 
##  0.35273425 -0.37967009  0.62550515  0.58276431  0.28994558 -0.38506394 
##       lstat        medv 
##  0.45562148 -0.38830461
set.seed(123)
train_idx <- sample(1:nrow(Boston_df), 0.7 * nrow(Boston_df))

train_set <- Boston_df[train_idx, ]
test_set  <- Boston_df[-train_idx, ]
actual_labels <- test_set$crim01

Logistic Regression

log_fit <- glm(crim01 ~ nox + rad + tax + dis, data = train_set, family = binomial)
log_probs <- predict(log_fit, test_set, type = "response")
log_pred <- ifelse(log_probs > 0.5, 1, 0)

table(Predicted = log_pred, Actual = actual_labels)
##          Actual
## Predicted  0  1
##         0 69 10
##         1  6 67
mean(log_pred != actual_labels)
## [1] 0.1052632

LDA

lda_fit <- lda(crim01 ~ nox + rad + tax + dis, data = train_set)
lda_pred <- predict(lda_fit, test_set)$class

table(Predicted = lda_pred, Actual = actual_labels)
##          Actual
## Predicted  0  1
##         0 70 15
##         1  5 62
mean(lda_pred != actual_labels)
## [1] 0.1315789

QDA

qda_fit <- qda(crim01 ~ nox + rad + tax + dis, data = train_set)
qda_pred <- predict(qda_fit, test_set)$class

table(Predicted = qda_pred, Actual = actual_labels)
##          Actual
## Predicted  0  1
##         0 71 21
##         1  4 56
mean(qda_pred != actual_labels)
## [1] 0.1644737

KNN

predictors <- c("nox", "rad", "tax", "dis")
scaled_X <- scale(Boston_df[, predictors])

train_X <- scaled_X[train_idx, ]
test_X  <- scaled_X[-train_idx, ]
train_Y <- train_set$crim01

for (kv in c(1, 3, 5, 10, 20)) {
  set.seed(123)
  knn_pred <- knn(train_X, test_X, train_Y, k = kv)
  cat(sprintf("K = %2d | Test Error Rate: %.2f%%\n", kv, mean(knn_pred != actual_labels) * 100))
}
## K =  1 | Test Error Rate: 4.61%
## K =  3 | Test Error Rate: 5.26%
## K =  5 | Test Error Rate: 5.92%
## K = 10 | Test Error Rate: 4.61%
## K = 20 | Test Error Rate: 4.61%

KNN with K=1, K=10 and K=20 performed optimally on the test set, achieving the lowest overall test error rate of 4.61%. The non-parametric model comfortably outperformed the parametric alternatives as Logistic Regression at 10.5%, suggesting that the true decision boundary separating high-crime census tracts based on industrial features (nox, rad, tax, dis) is highly non-linear