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?
data(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
##
##
##
##
pairs(Weekly[, -9])
# Graphical summaries
par(mfrow = c(2, 2))
# Plot Volume over time
plot(Weekly$Year, Weekly$Volume, type = "l", xlab = "Year", ylab = "Volume", main = "Volume Over Time")
# Boxplot of Lag1 by Direction
boxplot(Lag1 ~ Direction, data = Weekly, main = "Lag1 vs Direction", xlab = "Direction", ylab = "Lag1")
# Boxplot of Volume by Direction
boxplot(Volume ~ Direction, data = Weekly, main = "Volume vs Direction", xlab = "Direction", ylab = "Volume")
# Histogram of Today’s returns
hist(Weekly$Today, breaks = 30, main = "Histogram of Today’s Returns", xlab = "Today")
The most notable pattern is the increasing trend in Volume over the
years, which might suggest a relationship with market growth or
volatility.
There are no clear patterns in Lag1, Lag2, Lag3, Lag4, or Lag5 that
strongly differentiate “Up” from “Down” weeks based on the
boxplots.
The symmetry in Today’s returns suggests no strong directional bias, but
the heavy tails indicate potential for extreme movements.
(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_full <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, family = binomial)
summary(fit_full)
##
## 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
Yes and Lag2 is the only statistically significant predictor in the model. It has a p-value of 0.0296, which is less than the conventional significance level of 0.05. This suggests that Lag2 is significantly associated with the Direction variable. All other predictors (Lag1, Lag3, Lag4, Lag5, and Volume) have p-values greater than 0.05 and are not 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.
probs <- predict(fit_full, type = "response")
preds <- ifelse(probs > 0.5, "Up", "Down")
table(Predicted = preds, Actual = Weekly$Direction)
## Actual
## Predicted Down Up
## Down 54 48
## Up 430 557
mean(preds == Weekly$Direction)
## [1] 0.5610652
The confusion matrix shows that the logistic regression model predicts “Up” much more often than “Down,” resulting in many false negatives. It correctly classifies 557 “Up” weeks but only 54 “Down” weeks, while misclassifying 430 actual “Down” weeks as “Up.” This indicates the model is biased toward predicting “Up” and performs poorly at identifying “Down” weeks.
(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[Weekly$Year <= 2008, ]
test <- Weekly[Weekly$Year > 2008, ]
glm_fit2 <- glm(Direction ~ Lag2, data = train, family = binomial)
glm_probs2 <- predict(glm_fit2, newdata = test, type = "response")
glm_pred2 <- ifelse(glm_probs2 > 0.5, "Up", "Down")
table(glm_pred2, test$Direction)
##
## glm_pred2 Down Up
## Down 9 5
## Up 34 56
mean(glm_pred2 == test$Direction)
## [1] 0.625
(e) Repeat (d) using LDA.
lda_fit <- lda(Direction ~ Lag2, data = train)
lda_pred <- predict(lda_fit, newdata = test)$class
table(lda_pred, test$Direction)
##
## lda_pred Down Up
## Down 9 5
## Up 34 56
mean(lda_pred == test$Direction)
## [1] 0.625
(f) Repeat (d) using QDA.
qda_fit <- qda(Direction ~ Lag2, data = train)
qda_pred <- predict(qda_fit, newdata = test)$class
table(qda_pred, test$Direction)
##
## qda_pred Down Up
## Down 0 0
## Up 43 61
mean(qda_pred == test$Direction)
## [1] 0.5865385
(g) Repeat (d) using KNN with K = 1.
train_X <- as.matrix(train$Lag2)
test_X <- as.matrix(test$Lag2)
train_y <- train$Direction
knn_pred <- knn(train_X, test_X, train_y, k = 1)
table(knn_pred, test$Direction)
##
## knn_pred Down Up
## Down 21 30
## Up 22 31
mean(knn_pred == test$Direction)
## [1] 0.5
(h) Repeat (d) using naive Bayes.
nb_fit <- naiveBayes(Direction ~ Lag2, data = train)
nb_pred <- predict(nb_fit, newdata = test)
table(nb_pred, test$Direction)
##
## nb_pred Down Up
## Down 0 0
## Up 43 61
mean(nb_pred == test$Direction)
## [1] 0.5865385
(i) Which of these methods appears to provide the best
results on this data?
Logistic Regression and LDA provide the best results, both achieving an
accuracy of 0.625 on the test data.
(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.
# Example: Logistic regression with Lag1, Lag2, and interaction
glm_fit_exp <- glm(Direction ~ Lag1 + Lag2 + Lag1:Lag2, data = train, family = binomial)
glm_probs_exp <- predict(glm_fit_exp, newdata = test, type = "response")
glm_pred_exp <- ifelse(glm_probs_exp > 0.5, "Up", "Down")
table(glm_pred_exp, test$Direction)
##
## glm_pred_exp Down Up
## Down 7 8
## Up 36 53
mean(glm_pred_exp == test$Direction)
## [1] 0.5769231
# Example: KNN with Lag1, Lag2, and different K
train_X2 <- as.matrix(train[, c("Lag1", "Lag2")])
test_X2 <- as.matrix(test[, c("Lag1", "Lag2")])
knn_pred2 <- knn(train_X2, test_X2, train_y, k = 5)
table(knn_pred2, test$Direction)
##
## knn_pred2 Down Up
## Down 22 32
## Up 21 29
mean(knn_pred2 == test$Direction)
## [1] 0.4903846
The best results on the held-out data (2009–2010) were achieved with Logistic Regression using Lag2 alone (from part d), yielding an accuracy of 0.625 and a confusion matrix of 9 true “Down,” 56 true “Up,” 5 false “Down” as “Up,” and 34 false “Up” as “Down.” Additional experiments, such as Logistic Regression with Lag1 + Lag2 + Lag1:Lag2 (accuracy 0.5769231) and KNN with K=5 and Lag1 + Lag2 (accuracy 0.4903846), did not improve performance, indicating that Lag2 remains the most effective predictor for this dataset. Varying K values for KNN (e.g., K=5) and including multiple predictors or interactions generally reduced accuracy, suggesting overfitting or noise in the additional variables.
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)
median_mpg <- median(Auto$mpg)
Auto$mpg01 <- ifelse(Auto$mpg > median_mpg, 1, 0)
head(Auto)
## mpg cylinders displacement horsepower weight acceleration year origin
## 1 18 8 307 130 3504 12.0 70 1
## 2 15 8 350 165 3693 11.5 70 1
## 3 18 8 318 150 3436 11.0 70 1
## 4 16 8 304 150 3433 12.0 70 1
## 5 17 8 302 140 3449 10.5 70 1
## 6 15 8 429 198 4341 10.0 70 1
## name mpg01
## 1 chevrolet chevelle malibu 0
## 2 buick skylark 320 0
## 3 plymouth satellite 0
## 4 amc rebel sst 0
## 5 ford torino 0
## 6 ford galaxie 500 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. Describe your findings.
par(mfrow = c(2, 3))
boxplot(horsepower ~ mpg01, data = Auto, main = "Horsepower vs mpg01")
boxplot(weight ~ mpg01, data = Auto, main = "Weight vs mpg01")
boxplot(displacement ~ mpg01, data = Auto, main = "Displacement vs mpg01")
boxplot(cylinders ~ mpg01, data = Auto, main = "Cylinders vs mpg01")
boxplot(acceleration ~ mpg01, data = Auto, main = "Acceleration vs mpg01")
The boxplots show that Horsepower, Weight, and Displacement exhibit
clear separation between mpg01 = 0 and mpg01 = 1, with lower values
associated with higher mpg (1), making them the most useful predictors.
Cylinders also shows some differentiation, though less pronounced, while
Acceleration has overlapping distributions with minimal separation,
suggesting it is less predictive. These findings indicate that
engine-related features (Horsepower, Weight, Displacement) are most
likely to effectively predict mpg01.
(c) Split the data into a training set and a test set.
set.seed(123)
train_indices <- sample(1:nrow(Auto), 0.7 * nrow(Auto))
train <- Auto[train_indices, ]
test <- Auto[-train_indices, ]
(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?
lda_fit <- lda(mpg01 ~ horsepower + weight + displacement, data = train)
lda_pred <- predict(lda_fit, newdata = test)$class
lda_error <- mean(lda_pred != test$mpg01)
lda_error
## [1] 0.1186441
(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 ~ horsepower + weight + displacement, data = train)
qda_pred <- predict(qda_fit, newdata = test)$class
qda_error <- mean(qda_pred != test$mpg01)
qda_error
## [1] 0.1016949
(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 ~ horsepower + weight + displacement, data = train, family = binomial)
glm_probs <- predict(glm_fit, newdata = test, type = "response")
glm_pred <- ifelse(glm_probs > 0.5, 1, 0)
glm_error <- mean(glm_pred != test$mpg01)
glm_error
## [1] 0.1101695
(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_fit <- naiveBayes(mpg01 ~ horsepower + weight + displacement, data = train)
nb_pred <- predict(nb_fit, newdata = test)
nb_error <- mean(nb_pred != test$mpg01)
nb_error
## [1] 0.1101695
The Naive Bayes model was fitted using horsepower, weight, and displacement as predictors, achieving a test error of 0.1101695 on the held-out test set. Interestingly, this exact error matches the test error obtained from the Logistic Regression model (also 0.1101695), possibly due to the linear separability of the data or the specific train-test split aligning the models’ predictions.
(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?
train_X <- as.matrix(train[, c("horsepower", "weight", "displacement")])
test_X <- as.matrix(test[, c("horsepower", "weight", "displacement")])
train_y <- train$mpg01
k_values <- c(1, 3, 5, 7, 10)
knn_errors <- sapply(k_values, function(k) {
knn_pred <- knn(train_X, test_X, train_y, k = k)
mean(knn_pred != test$mpg01)
})
knn_errors
## [1] 0.1694915 0.1271186 0.1101695 0.1016949 0.1101695
The lowest test error of 0.1016949.
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.
# data exploration
data(Boston)
median_crim <- median(Boston$crim)
Boston$crim01 <- ifelse(Boston$crim > median_crim, 1, 0)
pairs(Boston[, c("crim01", "rm", "lstat", "nox", "age")])
# split data
set.seed(123)
train_indices <- sample(1:nrow(Boston), 0.7 * nrow(Boston))
train <- Boston[train_indices, ]
test <- Boston[-train_indices, ]
# model fitting and evaluation
# Logistic Regression
glm_fit <- glm(crim01 ~ lstat + rm + nox, data = train, family = binomial)
glm_probs <- predict(glm_fit, newdata = test, type = "response")
glm_pred <- ifelse(glm_probs > 0.5, 1, 0)
glm_error <- mean(glm_pred != test$crim01)
glm_error
## [1] 0.1447368
# LDA
lda_fit <- lda(crim01 ~ lstat + rm + nox, data = train)
lda_pred <- predict(lda_fit, newdata = test)$class
lda_error <- mean(lda_pred != test$crim01)
lda_error
## [1] 0.1644737
# Naive Bayes
nb_fit <- naiveBayes(crim01 ~ lstat + rm + nox, data = train)
nb_pred <- predict(nb_fit, newdata = test)
nb_error <- mean(nb_pred != test$crim01)
nb_error
## [1] 0.1513158
# KNN (K=3, 5, 7)
train_X <- as.matrix(train[, c("lstat", "rm", "nox")])
test_X <- as.matrix(test[, c("lstat", "rm", "nox")])
train_y <- train$crim01
knn_errors <- sapply(c(3, 5, 7), function(k) {
knn_pred <- knn(train_X, test_X, train_y, k = k)
mean(knn_pred != test$crim01)
})
knn_errors
## [1] 0.2960526 0.3026316 0.3026316
The scatterplot matrix reveals that lstat (lower status population) and nox (nitric oxides) show the strongest associations with crim01, with higher lstat and nox values linked to higher crime rates (1), while rm (average rooms) shows some separation, and age has minimal differentiation. Logistic Regression with lstat, rm, and nox achieved the lowest test error of 0.1447368, indicating the best performance among the models tested. LDA and Naive Bayes had higher test errors (0.1644737 and 0.1513158, respectively), suggesting less effective class separation, while KNN with \(K = 3, 5, 7\) performed poorly (errors around 0.296–0.303), likely due to the dataset’s complexity or inappropriate \(K\) values, highlighting Logistic Regression as the most effective method for this task.