library(ISLR2)
data(Weekly)
pairs(Weekly[, 1:8])Assignment #3
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?
Volume increases over time. No strong patterns in lag variables.
(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?
fit <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,
data = Weekly, family = binomial)
summary(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
Only Lag2 is 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.
probs <- predict(fit, type = "response")
pred <- ifelse(probs > 0.5, "Up", "Down")
table(pred, Weekly$Direction)
pred Down Up
Down 54 48
Up 430 557
mean(pred == Weekly$Direction)[1] 0.5610652
Accuracy is 56.1%. Model predicts “Up” well and misses “Down”.
(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)
fit2 <- glm(Direction ~ Lag2, data = Weekly, subset = train, family = binomial)
test_probs <- predict(fit2, Weekly[!train, ], type = "response")
test_pred <- ifelse(test_probs > 0.5, "Up", "Down")
table(test_pred, Weekly$Direction[!train])
test_pred Down Up
Down 9 5
Up 34 56
mean(test_pred == Weekly$Direction[!train])[1] 0.625
Accuracy is 62.5%. Slightly better, but still misses “Down”.
(e) Repeat (d) using LDA.
library(MASS)Warning: package 'MASS' was built under R version 4.4.3
Attaching package: 'MASS'
The following object is masked from 'package:ISLR2':
Boston
lda_fit <- lda(Direction ~ Lag2, data = Weekly, subset = train)
lda_pred <- predict(lda_fit, Weekly[!train, ])$class
table(lda_pred, Weekly$Direction[!train])
lda_pred Down Up
Down 9 5
Up 34 56
mean(lda_pred == Weekly$Direction[!train])[1] 0.625
Accuracy is 62.5%. Same result as logistic regression, still misses “Down”.
(f) Repeat (d) using QDA.
qda_fit <- qda(Direction ~ Lag2, data = Weekly, subset = train)
qda_pred <- predict(qda_fit, Weekly[!train, ])$class
table(qda_pred, Weekly$Direction[!train])
qda_pred Down Up
Down 0 0
Up 43 61
mean(qda_pred == Weekly$Direction[!train])[1] 0.5865385
Accuracy is 58.7%. Model predicts only “Up” and misses all “Down”.
(g) Repeat (d) using KNN with K = 1.
library(class)
train_X <- as.matrix(Weekly$Lag2[train])
test_X <- as.matrix(Weekly$Lag2[!train])
train_Y <- Weekly$Direction[train]
set.seed(1)
knn_pred <- knn(train_X, test_X, train_Y, k = 1)
table(knn_pred, Weekly$Direction[!train])
knn_pred Down Up
Down 21 30
Up 22 31
mean(knn_pred == Weekly$Direction[!train])[1] 0.5
Accuracy is 50%. Model performs no better than random guessing.
(h) Repeat (d) using naive Bayes.
library(e1071)Warning: package 'e1071' was built under R version 4.4.3
nb_fit <- naiveBayes(Direction ~ Lag2, data = Weekly, subset = train)
nb_pred <- predict(nb_fit, Weekly[!train, ])
table(nb_pred, Weekly$Direction[!train])
nb_pred Down Up
Down 0 0
Up 43 61
mean(nb_pred == Weekly$Direction[!train])[1] 0.5865385
Accuracy is 58.7%. Same as QDA. Predicts only “Up” and misses all “Down”.
(i) Which of these methods appears to provide the best results on this data?
Logistic regression and LDA perform best with 62.5% accuracy. Both predict “Up” well, but struggle with “Down”.
(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.
set.seed(1)
knn_pred20 <- knn(train_X, test_X, train_Y, k = 20)
table(knn_pred20, Weekly$Direction[!train])
knn_pred20 Down Up
Down 21 21
Up 22 40
mean(knn_pred20 == Weekly$Direction[!train])[1] 0.5865385
KNN with K = 20 gives 58.7% accuracy. Slight improvement over K = 1, but still weak on “Down”.
qda_poly <- qda(Direction ~ I(Lag2^2), data = Weekly, subset = train)
qda_poly_pred <- predict(qda_poly, Weekly[!train, ])$class
table(qda_poly_pred, Weekly$Direction[!train])
qda_poly_pred Down Up
Down 4 6
Up 39 55
mean(qda_poly_pred == Weekly$Direction[!train])[1] 0.5673077
QDA with Lag2 squared also gives 58.7% accuracy. Same result, no improvement.
lda_inter <- lda(Direction ~ Lag2:Lag3, data = Weekly, subset = train)
lda_inter_pred <- predict(lda_inter, Weekly[!train, ])$class
table(lda_inter_pred, Weekly$Direction[!train])
lda_inter_pred Down Up
Down 0 0
Up 43 61
mean(lda_inter_pred == Weekly$Direction[!train])[1] 0.5865385
LDA with Lag2:Lag3 interaction gives 58.7% accuracy. Lower than basic LDA.
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 fnd it helpful to use the data.frame() function to create a single data set containing both mpg01 and the other Auto variables.
library(ISLR2)
data(Auto)
mpg01 <- ifelse(Auto$mpg > median(Auto$mpg), 1, 0)
auto_data <- data.frame(Auto, 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? Scatter plots and box plots may be useful tools to answer this question. Describe your findings.
pairs(auto_data[, 1:8])boxplot(cylinders ~ mpg01, data = auto_data)boxplot(displacement ~ mpg01, data = auto_data)boxplot(horsepower ~ mpg01, data = auto_data)boxplot(weight ~ mpg01, data = auto_data)boxplot(acceleration ~ mpg01, data = auto_data)boxplot(year ~ mpg01, data = auto_data)cor(auto_data[, 1:8]) mpg cylinders displacement horsepower weight
mpg 1.0000000 -0.7776175 -0.8051269 -0.7784268 -0.8322442
cylinders -0.7776175 1.0000000 0.9508233 0.8429834 0.8975273
displacement -0.8051269 0.9508233 1.0000000 0.8972570 0.9329944
horsepower -0.7784268 0.8429834 0.8972570 1.0000000 0.8645377
weight -0.8322442 0.8975273 0.9329944 0.8645377 1.0000000
acceleration 0.4233285 -0.5046834 -0.5438005 -0.6891955 -0.4168392
year 0.5805410 -0.3456474 -0.3698552 -0.4163615 -0.3091199
origin 0.5652088 -0.5689316 -0.6145351 -0.4551715 -0.5850054
acceleration year origin
mpg 0.4233285 0.5805410 0.5652088
cylinders -0.5046834 -0.3456474 -0.5689316
displacement -0.5438005 -0.3698552 -0.6145351
horsepower -0.6891955 -0.4163615 -0.4551715
weight -0.4168392 -0.3091199 -0.5850054
acceleration 1.0000000 0.2903161 0.2127458
year 0.2903161 1.0000000 0.1815277
origin 0.2127458 0.1815277 1.0000000
Cylinders, displacement, horsepower, and weight show clear separation with mpg01.
(c) Split the data into a training set and a test set.
set.seed(1)
train_idx <- sample(1:nrow(auto_data), 0.8 * nrow(auto_data))
train_data <- auto_data[train_idx, ]
test_data <- auto_data[-train_idx, ](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?
library(MASS)
lda_fit <- lda(mpg01 ~ cylinders + displacement + weight, data = train_data)
lda_pred <- predict(lda_fit, test_data)$class
table(lda_pred, test_data$mpg01)
lda_pred 0 1
0 35 0
1 7 37
mean(lda_pred == test_data$mpg01)[1] 0.9113924
Accuracy is high. Predictors separate mpg01 well.
(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?
qda_fit <- qda(mpg01 ~ cylinders + displacement + horsepower + weight, data = train_data)
qda_pred <- predict(qda_fit, test_data)$class
table(qda_pred, test_data$mpg01)
qda_pred 0 1
0 37 2
1 5 35
mean(qda_pred == test_data$mpg01)[1] 0.9113924
QDA performs slightly better than LDA.
(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?
glm_fit <- glm(mpg01 ~ cylinders + displacement + horsepower + weight,
data = train_data, family = binomial)
glm_probs <- predict(glm_fit, test_data, type = "response")
glm_pred <- ifelse(glm_probs > 0.5, 1, 0)
table(glm_pred, test_data$mpg01)
glm_pred 0 1
0 38 1
1 4 36
mean(glm_pred == test_data$mpg01)[1] 0.9367089
Logistic regression performs similarly to LDA.
(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)
nb_fit <- naiveBayes(mpg01 ~ cylinders + displacement + horsepower + weight, data = train_data)
nb_pred <- predict(nb_fit, test_data)
table(nb_pred, test_data$mpg01)
nb_pred 0 1
0 37 1
1 5 36
mean(nb_pred == test_data$mpg01)[1] 0.9240506
Naive Bayes performs slightly worse than LDA and logistic regression.
(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)
train_X <- scale(train_data[, c("cylinders", "displacement", "horsepower", "weight")])
test_X <- scale(test_data[, c("cylinders", "displacement", "horsepower", "weight")])
train_Y <- train_data$mpg01
set.seed(1)
knn_pred1 <- knn(train_X, test_X, train_Y, k = 1)
knn_pred10 <- knn(train_X, test_X, train_Y, k = 10)
knn_pred20 <- knn(train_X, test_X, train_Y, k = 20)
mean(knn_pred1 == test_data$mpg01)[1] 0.8860759
mean(knn_pred10 == test_data$mpg01)[1] 0.8987342
mean(knn_pred20 == test_data$mpg01)[1] 0.9240506
K = 20 performs best. K = 1 over fits, K = 10 slightly under performs.
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.
library(ISLR2)
library(MASS)
library(e1071)
library(class)
data(Boston)
crim01 <- ifelse(Boston$crim > median(Boston$crim), 1, 0)
boston_data <- data.frame(Boston, crim01)
set.seed(1)
train_idx <- sample(1:nrow(boston_data), 0.8 * nrow(boston_data))
train_data <- boston_data[train_idx, ]
test_data <- boston_data[-train_idx, ]
# Logistic Regression
glm_fit <- glm(crim01 ~ nox + dis + rad + tax + lstat, data = train_data, family = binomial)
glm_pred <- ifelse(predict(glm_fit, test_data, type = "response") > 0.5, 1, 0)
glm_acc <- mean(glm_pred == test_data$crim01)
cat("Logistic Regression Accuracy:", glm_acc, "\n")Logistic Regression Accuracy: 0.8039216
# LDA
lda_fit <- lda(crim01 ~ nox + dis + rad + tax + lstat, data = train_data)
lda_pred <- predict(lda_fit, test_data)$class
lda_acc <- mean(lda_pred == test_data$crim01)
cat("LDA Accuracy:", lda_acc, "\n")LDA Accuracy: 0.8627451
# Naive Bayes
nb_fit <- naiveBayes(crim01 ~ nox + dis + rad + tax + lstat, data = train_data)
nb_pred <- predict(nb_fit, test_data)
nb_acc <- mean(nb_pred == test_data$crim01)
cat("Naive Bayes Accuracy:", nb_acc, "\n")Naive Bayes Accuracy: 0.8627451
# KNN
train_X <- scale(train_data[, c("nox", "dis", "rad", "tax", "lstat")])
test_X <- scale(test_data[, c("nox", "dis", "rad", "tax", "lstat")])
train_Y <- train_data$crim01
set.seed(1)
for (k in c(1, 10, 20)) {
knn_pred <- knn(train_X, test_X, train_Y, k = k)
knn_acc <- mean(knn_pred == test_data$crim01)
cat("KNN Accuracy (k =", k, "):", knn_acc, "\n")
}KNN Accuracy (k = 1 ): 0.9215686
KNN Accuracy (k = 10 ): 0.9019608
KNN Accuracy (k = 20 ): 0.9215686
Used crim01 as binary target (1 if crime rate above median). Predictors: nox, dis, rad, tax, lstat.
KNN (k = 20) performed best. All models predicted well. No major difference between LDA and Naive Bayes.