library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.4.3
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
library(e1071)
## Warning: package 'e1071' was built under R version 4.4.3
library(class)

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.

data("Weekly")

a) Produce some numerical and graphical summaries of the Weekly data.

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[, -9])

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

Do there appear to be any patterns? Consistent increase in volume as time went on, presumably due to market growth

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.

lr_model <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, family = binomial)
summary(lr_model)
## 
## 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

Do any of the predictors appear to be statistically significant? If so, which ones? Yes – Lag2: p-value = 0.0296

c) Compute the confusion matrix and overall fraction of correct predictions.

lr_probs <- predict(lr_model, type = "response")
lr_pred <- ifelse(lr_probs > 0.5, "Up", "Down")
table(Predicted = lr_pred, Actual = Weekly$Direction)
##          Actual
## Predicted Down  Up
##      Down   54  48
##      Up    430 557
mean(lr_pred == Weekly$Direction)
## [1] 0.5610652

Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression. Overall logistic regression trends toward “Up” more often, thus generating a relatively high number of False Positives in this dataset (“Up” when “Down” ; 430 times). Regression accuracy: 0.5610652 or 56.1%

d) Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor.

train <- Weekly$Year <= 2008
test <- Weekly$Year > 2008
lr2 <- glm(Direction ~ Lag2, data = Weekly, subset = train, family = binomial)
lr2_probs <- predict(lr2, newdata = Weekly[test, ], type = "response")
lr2_pred <- ifelse(lr2_probs > 0.5, "Up", "Down")
table(Predicted = lr2_pred, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    9  5
##      Up     34 56
mean(lr2_pred == Weekly$Direction[test])
## [1] 0.625

Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010). Training model was accurate in predicting market direction 62.5% of the time.

e) Repeat (d) using LDA.

lda_model <- lda(Direction ~ Lag2, data = Weekly, subset = train)
lda_pred <- predict(lda_model, newdata = Weekly[test, ])
table(Predicted = lda_pred$class, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    9  5
##      Up     34 56
mean(lda_pred$class == Weekly$Direction[test])
## [1] 0.625

f) Repeat (d) using QDA.

qda_model <- qda(Direction ~ Lag2, data = Weekly, subset = train)
qda_pred <- predict(qda_model, newdata = Weekly[test, ])
table(Predicted = qda_pred$class, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    0  0
##      Up     43 61
mean(qda_pred$class == Weekly$Direction[test])
## [1] 0.5865385

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

x_train <- as.matrix(Weekly[train, "Lag2"])
x_test <- as.matrix(Weekly[test, "Lag2"])
y_train <- Weekly$Direction[train]
y_test <- Weekly$Direction[test]
knn_pred <- knn(train = x_train, test = x_test, cl = y_train, k = 1)
table(Predicted = knn_pred, Actual = y_test)
##          Actual
## Predicted Down Up
##      Down   21 29
##      Up     22 32
mean(knn_pred == y_test)
## [1] 0.5096154

h) Repeat (d) using naive Bayes.

nb_model <- naiveBayes(Direction ~ Lag2, data = Weekly, subset = train)
nb_pred <- predict(nb_model, newdata = Weekly[test, ])
table(Predicted = nb_pred, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    0  0
##      Up     43 61
mean(nb_pred == Weekly$Direction[test])
## [1] 0.5865385

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

13(e) – Logistic regression using LDA. Accuracy was the highest: 62.5%

  1. Experiment with different combinations of predictors, including possible transformations and interactions, for each of the methods.
lr3 <- glm(Direction ~ Lag1+Lag2, data = Weekly, subset = train, family = binomial)
lr3_probs <- predict(lr2, newdata = Weekly[test, ], type = "response")
lr3_pred <- ifelse(lr2_probs > 0.5, "Up", "Down")
table(Predicted = lr2_pred, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    9  5
##      Up     34 56
mean(lr2_pred == Weekly$Direction[test])
## [1] 0.625
lr4 <- glm(Direction ~ Lag1*Lag2, data = Weekly, subset = train, family = binomial)
lr4probs <- predict(lr2, newdata = Weekly[test, ], type = "response")
lr4_pred <- ifelse(lr2_probs > 0.5, "Up", "Down")
table(Predicted = lr2_pred, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    9  5
##      Up     34 56
mean(lr2_pred == Weekly$Direction[test])
## [1] 0.625
x_trainknnexp <- as.matrix(Weekly[train, c("Lag1","Lag2")])
x_testknnexp <- as.matrix(Weekly[test, c("Lag1","Lag2")])
y_trainknnexp <- Weekly$Direction[train]
y_testknnexp <- Weekly$Direction[test]
knn_predexp <- knn(train = x_trainknnexp, test = x_testknnexp, cl = y_trainknnexp, k = 1)
table(Predicted = knn_predexp, Actual = y_testknnexp)
##          Actual
## Predicted Down Up
##      Down   18 29
##      Up     25 32
mean(knn_predexp == y_testknnexp)
## [1] 0.4807692
lda_model <- lda(Direction ~ Lag1+Lag2, data = Weekly, subset = train)
lda_pred <- predict(lda_model, newdata = Weekly[test, ])
table(Predicted = lda_pred$class, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    7  8
##      Up     36 53
mean(lda_pred$class == Weekly$Direction[test])
## [1] 0.5769231
qda_model <- qda(Direction ~Lag1+ Lag2, data = Weekly, subset = train)
qda_pred <- predict(qda_model, newdata = Weekly[test, ])
table(Predicted = qda_pred$class, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    7 10
##      Up     36 51
mean(qda_pred$class == Weekly$Direction[test])
## [1] 0.5576923
nb_model <- naiveBayes(Direction ~ Lag1+Lag2, data = Weekly, subset = train)
nb_pred <- predict(nb_model, newdata = Weekly[test, ])
table(Predicted = nb_pred, Actual = Weekly$Direction[test])
##          Actual
## Predicted Down Up
##      Down    3  8
##      Up     40 53
mean(nb_pred == Weekly$Direction[test])
## [1] 0.5384615

Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Variables: Lag1 & Lag2 ; Method: Linear regression with Interaction & Linear regression using LDA; Confusion matrixes: - Linear regression using LDA: Actual Predicted Down Up Down 7 8 Up 36 53 - Linear regression w/ Interaction: Actual Predicted Down Up Down 7 8 Up 36 53

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.

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.

data("Auto")
Auto <- na.omit(Auto)
Auto$mpg01 <- ifelse(Auto$mpg > median(Auto$mpg), 1, 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.

boxplot(horsepower ~ mpg01, data = Auto)

boxplot(weight ~ mpg01, data = Auto)

boxplot(displacement ~ mpg01, data = Auto)

boxplot(acceleration ~ mpg01, data = Auto)

boxplot(cylinders ~ mpg01, data = Auto)

Describe your findings. Horsepower and weight are lower for vehicles with high mpg rating ; acceleration is slightly lower, but comparable, in vehicles with high mpg rating; Cylinders and displacement are significantly higher in vehicles with low mpg rating

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

set.seed(1)
train_auto <- sample(1:nrow(Auto), 0.7 * nrow(Auto))
auto_train <- Auto[train_auto, ]
auto_test  <- Auto[-train_auto, ]
  1. Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b).
lda_auto <- lda(mpg01 ~ horsepower + weight + cylinders + displacement, data = auto_train)
pred_lda <- predict(lda_auto, newdata = auto_test)
table(Predicted = pred_lda$class, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 50  3
##         1 11 54
mean(pred_lda$class == auto_test$mpg01)
## [1] 0.8813559

What is the test error of the model obtained? 88.14% accuracy

e) Perform QDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b).

qda_auto <- qda(mpg01 ~ horsepower + weight + cylinders + displacement, data = auto_train)
pred_qda <- predict(qda_auto, newdata = auto_test)
table(Predicted = pred_qda$class, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 52  5
##         1  9 52
mean(pred_qda$class == auto_test$mpg01)
## [1] 0.8813559

What is the test error of the model obtained? 88.14% accuracy

f) Perform logistic regression on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b).

log_auto <- glm(mpg01 ~ horsepower + weight + cylinders + displacement, data = auto_train, family = binomial)
log_probs <- predict(log_auto, newdata = auto_test, type = "response")
log_pred <- ifelse(log_probs > 0.5, 1, 0)
table(Predicted = log_pred, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 53  3
##         1  8 54
mean(log_pred == auto_test$mpg01)
## [1] 0.9067797

What is the test error of the model obtained? 90.68% accuracy

g) Perform naive Bayes on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b).

nb_auto <- naiveBayes(mpg01 ~ horsepower + weight + cylinders + displacement, data = auto_train)
nb_pred <- predict(nb_auto, newdata = auto_test)
table(Predicted = nb_pred, Actual = auto_test$mpg01)
##          Actual
## Predicted  0  1
##         0 52  4
##         1  9 53
mean(nb_pred == auto_test$mpg01)
## [1] 0.8898305

What is the test error of the model obtained? 89.98% accuracy

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

X_train <- scale(auto_train[, c("horsepower", "weight", "cylinders", "displacement")])
X_test <- scale(auto_test[, c("horsepower", "weight", "cylinders", "displacement")])
y_train <- auto_train$mpg01
y_test <- auto_test$mpg01

What test errors do you obtain?

for (k in c(1, 3, 5, 10))
  {set.seed(1)
  knn_pred <- knn(train = X_train, test = X_test, cl = y_train, k = k)
  cat("K =", k, "Accuracy:", mean(knn_pred == y_test), "\n")}
## K = 1 Accuracy: 0.8559322 
## K = 3 Accuracy: 0.8559322 
## K = 5 Accuracy: 0.8644068 
## K = 10 Accuracy: 0.8644068

Which value of K seems to perform the best on this data set? 3

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.

data("Boston")
Boston$crim01 <- ifelse(Boston$crim > median(Boston$crim), 1, 0)
set.seed(1)
n <- nrow(Boston)
train_indices <- sample(1:n, size = round(0.7 * n))
boston_train <- Boston[train_indices, ]
boston_test  <- Boston[-train_indices, ]
predictors <- c("nox", "rad", "dis", "lstat", "tax")

Logistic Regression

log_fit <- glm(crim01 ~ nox + rad + dis + lstat + tax, data = boston_train, family = binomial)
log_probs <- predict(log_fit, newdata = boston_test, type = "response")
log_pred <- ifelse(log_probs > 0.5, 1, 0)
table(Predicted = log_pred, Actual = boston_test$crim01)
##          Actual
## Predicted  0  1
##         0 57 13
##         1 16 66
mean(log_pred == boston_test$crim01)
## [1] 0.8092105

LDA

lda_fit <- lda(crim01 ~ nox + rad + dis + lstat + tax, data = boston_train)
lda_pred <- predict(lda_fit, newdata = boston_test)
table(Predicted = lda_pred$class, Actual = boston_test$crim01)
##          Actual
## Predicted  0  1
##         0 69 19
##         1  4 60
mean(lda_pred$class == boston_test$crim01)
## [1] 0.8486842

Naive Bayes

nb_fit <- naiveBayes(crim01 ~ nox + rad + dis + lstat + tax, data = boston_train)
nb_pred <- predict(nb_fit, newdata = boston_test)
table(Predicted = nb_pred, Actual = boston_test$crim01)
##          Actual
## Predicted  0  1
##         0 67 19
##         1  6 60
mean(nb_pred == boston_test$crim01)
## [1] 0.8355263

KNN

X_train <- as.matrix(boston_train[, predictors])
X_test  <- as.matrix(boston_test[, predictors])
y_train <- boston_train$crim01
y_test  <- boston_test$crim01
for (k in c(1, 3, 5, 10)) 
  {set.seed(1)
  knn_pred <- knn(train = X_train, test = X_test, cl = y_train, k = k)
  acc <- mean(knn_pred == y_test)
  cat("K =", k, "\u2192 Accuracy:", round(acc, 4), "\n")}
## K = 1 → Accuracy: 0.9408 
## K = 3 → Accuracy: 0.9013 
## K = 5 → Accuracy: 0.9079 
## K = 10 → Accuracy: 0.8947
best_k <- 1
knn_pred_best <- knn(train = X_train, test = X_test, cl = y_train, k = best_k)
table(Predicted = knn_pred_best, Actual = y_test)
##          Actual
## Predicted  0  1
##         0 65  1
##         1  8 78
mean(knn_pred_best == y_test)
## [1] 0.9407895

Describe your findings. Radial highway access and nitrogen oxides tend to be higher in high-crime areas; lower status population percentage and property tax rate are significantly higher in high-crime areas; distance to employment centers are generally lower in high-crime areas