This question should be answered using the Weekly data set, which is part of the ISLR
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.
Produce some numerical and graphical summaries of the Weekly
data. Do there appear to be any patterns?
Year
and Volume
appear to have a strong relationship with a positive correlation of 0.84. Based on the scatterplot below, the number of shares traded has significantly grown over time. The rest of the variables have very weak correlations with coefficients close to zero, indicating there are no other relationships among the variables in the data set.
library(GGally)
ggpairs(Weekly, ggplot2::aes(color = Direction),
upper = list(combo = wrap("box_no_facet", alpha=0.5), continuous = wrap("points", alpha=0.5)),
diag = list(discrete= wrap("barDiag", alpha=0.7), continuous = wrap("densityDiag", alpha=0.5)),
lower = list(combo = wrap("box_no_facet", alpha=0.5),continuous = wrap("cor", size=4)))
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?
Lag 2
has a significant positive association with Direction
(p-value = 0.03).
glm.fit <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,
data = Weekly, family = binomial)
summary(glm.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
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.
Our logistic regression model has an accuracy of 56.1%. The sensitivity is quite high at 92.1%, which is the percentage of correct predictions that the stock market is up. However, the specificity of the model is much lower, which is the percentage of correct predictions that the stock market is down, at 11.2%.
glm.prob <- predict(glm.fit, type = "response")
glm.pred <- ifelse(glm.prob > 0.5, 1, 0)
Weekly$Direction01 <- ifelse(Weekly$Direction == "Up", 1, 0)
caret::confusionMatrix(as_factor(glm.pred), as_factor(Weekly$Direction01), positive = '1')
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 54 48
## 1 430 557
##
## Accuracy : 0.5611
## 95% CI : (0.531, 0.5908)
## No Information Rate : 0.5556
## P-Value [Acc > NIR] : 0.369
##
## Kappa : 0.035
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.9207
## Specificity : 0.1116
## Pos Pred Value : 0.5643
## Neg Pred Value : 0.5294
## Prevalence : 0.5556
## Detection Rate : 0.5115
## Detection Prevalence : 0.9063
## Balanced Accuracy : 0.5161
##
## 'Positive' Class : 1
##
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).## [1] 985 10
## [1] 104 10
glm.fit <- glm(Direction ~ Lag2, data = Weekly.train, family = binomial)
glm.probs <- predict(glm.fit, Weekly.test, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Up", "Down")
direction.test <- Weekly.test$Direction
table(glm.pred, direction.test)
## direction.test
## glm.pred Down Up
## Down 9 5
## Up 34 56
## [1] 0.625
lda.fit <- lda(Direction ~ Lag2, data = Weekly.train)
lda.pred <- predict(lda.fit, Weekly.test)
table(lda.pred$class, direction.test)
## direction.test
## Down Up
## Down 9 5
## Up 34 56
## [1] 0.625
qda.fit <- qda(Direction ~ Lag2, data = Weekly.train)
qda.class <- predict(qda.fit, Weekly.test)$class
table(qda.class, direction.test)
## direction.test
## qda.class Down Up
## Down 0 0
## Up 43 61
## [1] 0.5865385
## direction.test
## knn.pred Down Up
## Down 21 30
## Up 22 31
## [1] 0.5
Which of these methods appears to provide the best results on this data?
Logistic regression and LDA give us the best results with 62.5% accuracy.
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.
# Logistic regression with interaction
glm.fit <- glm(Direction ~ Lag2:Volume, data = Weekly.train, family = binomial)
glm.probs <- predict(glm.fit, Weekly.test, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, "Up", "Down")
table(glm.pred, direction.test)
## direction.test
## glm.pred Down Up
## Down 9 6
## Up 34 55
## [1] 0.6153846
# LDA with interactions
lda.fit <- lda(Direction ~ Lag2:Volume + Lag2:Lag3, data = Weekly.train)
lda.class <- predict(lda.fit, Weekly.test)$class
table(lda.class, direction.test)
## direction.test
## lda.class Down Up
## Down 10 6
## Up 33 55
## [1] 0.625
# QDA with transformations
qda.fit <- qda(Direction ~ sqrt(abs(Lag1)) + log(abs(Lag2)), data = Weekly.train)
qda.class <- predict(qda.fit, Weekly.test)$class
table(qda.class, direction.test)
## direction.test
## qda.class Down Up
## Down 1 0
## Up 42 61
## [1] 0.5961538
## direction.test
## knn.pred Down Up
## Down 16 20
## Up 27 41
## [1] 0.5480769
## direction.test
## knn.pred Down Up
## Down 16 20
## Up 27 41
## [1] 0.5480769
## direction.test
## knn.pred Down Up
## Down 17 20
## Up 26 41
## [1] 0.5576923
## direction.test
## knn.pred Down Up
## Down 19 23
## Up 24 38
## [1] 0.5480769
After trying different combinations of predictors, the LDA model with Lag2
interactions between Volume
and Lag3
achieved the highest accuracy of 62.5%, which is the same as the original LDA and logistic regression models.
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.
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.Auto <- Auto %>%
mutate(mpg01 = as_factor(ifelse(mpg > median(mpg), 1, 0)))
head(Auto[,c(1,ncol(Auto))])
## mpg mpg01
## 1 18 0
## 2 15 0
## 3 18 0
## 4 16 0
## 5 17 0
## 6 15 0
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.
The variables most associated with mpg01
(correlations above 0.6) are cylinders
, displacement
, horsepower
, weight
, and mpg
itself.
Auto %>%
select(-name) %>%
ggpairs(ggplot2::aes(color = mpg01),
diag = list(continuous = wrap("densityDiag", alpha=0.5)),
lower = list(continuous = wrap("points", alpha=0.5)))
set.seed(1)
trainInd <- sample(1:nrow(Auto), 0.75*nrow(Auto))
Auto.train <- Auto[trainInd, ]
Auto.test <- Auto[-trainInd, ]
mpg01.test <- Auto.test$mpg01
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 + horsepower + weight, data = Auto.train)
lda.pred <- predict(lda.fit, Auto.test)
mean(lda.pred$class != mpg01.test)
## [1] 0.1326531
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 = Auto.train)
qda.pred <- predict(qda.fit, Auto.test)
mean(qda.pred$class != mpg01.test)
## [1] 0.122449
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 = Auto.train, family = binomial)
glm.probs <- predict(glm.fit, Auto.test, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, 1, 0)
mean(glm.pred != mpg01.test)
## [1] 0.1020408
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?
The KNN model with 4 nearest neighbors has the lowest test error of 10.2%, which is the same error rate as the logistic model.
## [1] 0.122449
## [1] 0.1020408
## [1] 0.1326531
## [1] 0.1530612
## [1] 0.1428571
Using the Boston
data set, fit classification models in order to predict whether a given suburb has a crime rate above or below the median. Explore logistic regression, LDA, and KNN models using various subsets of the predictors. Describe your findings.
Boston <- Boston %>%
mutate(crime01 = ifelse(crim > median(crim), 1, 0))
head(Boston[,c(1,ncol(Boston))])
## crim crime01
## 1 0.00632 0
## 2 0.02731 0
## 3 0.02729 0
## 4 0.03237 0
## 5 0.06905 0
## 6 0.02985 0
library(ggcorrplot)
ggcorrplot(cor(Boston), type = "upper", lab=TRUE, hc.order = TRUE,
colors = rev(colorspace::diverge_hsv(n=3)))
set.seed(2)
trainInd <- sample(1:nrow(Boston), 0.8*nrow(Boston))
Boston.train <- Boston[trainInd, ]
Boston.test <- Boston[-trainInd, ]
crime01.test <- Boston.test$crime01
##
## Call:
## glm(formula = crime01 ~ . - crim, family = binomial, data = Boston.train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.9239 -0.1979 -0.0061 0.0020 3.2468
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -31.951406 6.736023 -4.743 2.10e-06 ***
## zn -0.060678 0.033100 -1.833 0.0668 .
## indus -0.040889 0.048136 -0.849 0.3956
## chas 0.560825 0.819833 0.684 0.4939
## nox 42.436265 7.707026 5.506 3.67e-08 ***
## rm -0.237023 0.794074 -0.298 0.7653
## age 0.015697 0.013222 1.187 0.2351
## dis 0.551900 0.227557 2.425 0.0153 *
## rad 0.657003 0.167022 3.934 8.37e-05 ***
## tax -0.005635 0.002821 -1.998 0.0457 *
## ptratio 0.318066 0.133227 2.387 0.0170 *
## black -0.009705 0.006065 -1.600 0.1095
## lstat 0.068844 0.053456 1.288 0.1978
## medv 0.143262 0.072217 1.984 0.0473 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 558.64 on 403 degrees of freedom
## Residual deviance: 169.55 on 390 degrees of freedom
## AIC: 197.55
##
## Number of Fisher Scoring iterations: 9
glm.probs <- predict(glm.fit, Boston.test, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, 1, 0)
mean(glm.pred == crime01.test)
## [1] 0.9117647
# Logistic regression using variables with correlations above 0.6
glm.fit <- glm(crime01 ~ rad + tax + age + indus + nox + dis, data = Boston.train, family = binomial)
glm.probs <- predict(glm.fit, Boston.test, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, 1, 0)
mean(glm.pred == crime01.test)
## [1] 0.8137255
# LDA full model
lda.fit <- lda(crime01 ~ . -crim, data = Boston.train)
lda.pred <- predict(lda.fit, Boston.test)
mean(lda.pred$class == crime01.test)
## [1] 0.7941176
# LDA with correlated variables
lda.fit <- lda(crime01 ~ rad + tax + age + indus + nox + dis, data = Boston.train)
lda.pred <- predict(lda.fit, Boston.test)
mean(lda.pred$class == crime01.test)
## [1] 0.7843137
# LDA using significant variables from logistic model
lda.fit <- lda(crime01 ~ nox + dis + rad + tax + ptratio + medv, data = Boston.train)
lda.pred <- predict(lda.fit, Boston.test)
mean(lda.pred$class == crime01.test)
## [1] 0.7647059
# QDA full model
qda.fit <- qda(crime01 ~ . -crim, data = Boston.train)
qda.pred <- predict(qda.fit, Boston.test)
mean(qda.pred$class == crime01.test)
## [1] 0.8627451
# QDA with correlated variables
qda.fit <- qda(crime01 ~ rad + tax + age + indus + nox + dis, data = Boston.train)
qda.pred <- predict(qda.fit, Boston.test)
mean(qda.pred$class == crime01.test)
## [1] 0.8333333
# QDA using significant variables
qda.fit <- qda(crime01 ~ nox + dis + rad + tax + ptratio + medv, data = Boston.train)
qda.pred <- predict(qda.fit, Boston.test)
mean(qda.pred$class == crime01.test)
## [1] 0.8235294
# KNN using significant variables
train <- Boston.train[c("nox", "dis", "rad", "tax", "ptratio", "medv")]
test <- Boston.test[c("nox", "dis", "rad", "tax", "ptratio", "medv")]
cl <- Boston.train$crime01
## [1] 0.9509804
## [1] 0.9705882
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 38 2
## 1 1 61
##
## Accuracy : 0.9706
## 95% CI : (0.9164, 0.9939)
## No Information Rate : 0.6176
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.938
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 0.9683
## Specificity : 0.9744
## Pos Pred Value : 0.9839
## Neg Pred Value : 0.9500
## Prevalence : 0.6176
## Detection Rate : 0.5980
## Detection Prevalence : 0.6078
## Balanced Accuracy : 0.9713
##
## 'Positive' Class : 1
##
## [1] 0.9313725
## [1] 0.9411765
## [1] 0.8921569
The KNN classifier had the best performance on the Boston
data set out of all the models. The KNN with 3 nearest neighbors achieved the highest accuracy in predicting whether a suburb has a crime rate above the median at 97.1%, with 96.8% sensitivity and 97.4% specificity.