Problem 13

(a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?

library(ISLR2)
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:ISLR2':
## 
##     Boston
library(class)
library(e1071)

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

(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?

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

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

glm_probs <- predict(glm_full, type = "response")
glm_pred <- rep("Down", nrow(Weekly))
glm_pred[glm_probs > 0.5] <- "Up"
table(glm_pred, Weekly$Direction)
##         
## glm_pred Down  Up
##     Down   54  48
##     Up    430 557
mean(glm_pred == Weekly$Direction)
## [1] 0.5610652

(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 >= 1990 & Weekly$Year <= 2008 
Weekly_test <- Weekly[!train, ]

glm_lag2 <- glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = train)
glm_lag2_probs <- predict(glm_lag2, Weekly_test, type = "response")
glm_lag2_pred <- rep("Down", nrow(Weekly_test))
glm_lag2_pred[glm_lag2_probs > 0.5] <- "Up"

table(glm_lag2_pred, Weekly_test$Direction)
##              
## glm_lag2_pred Down Up
##          Down    9  5
##          Up     34 56
mean(glm_lag2_pred == Weekly_test$Direction)
## [1] 0.625

(e) Repeat (d) using LDA.

lda_fit <- lda(Direction ~ Lag2, data = Weekly, subset = train)
lda_pred <- predict(lda_fit, Weekly_test)

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

(f) Repeat (d) using QDA.

qda_fit <- qda(Direction ~ Lag2, data = Weekly, subset = train)
qda_pred <- predict(qda_fit, Weekly_test)

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

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

train_X <- as.matrix(Weekly$Lag2[train])
test_X  <- as.matrix(Weekly$Lag2[!train])
train_Y <- Weekly$Direction[train]

set.seed(42)
knn_pred <- knn(train_X, test_X, train_Y, k = 1)

table(knn_pred, Weekly_test$Direction)
##         
## knn_pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn_pred == Weekly_test$Direction)
## [1] 0.5

(h) Repeat (d) using naive Bayes.

nb_fit  <- naiveBayes(Direction ~ Lag2, data = Weekly, subset = train)
nb_pred <- predict(nb_fit, Weekly_test)

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

(i) Which of these methods appears to provide the best results on this 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.

# Logistic regression with transformed Lag2
glm_tran <- glm(Direction ~ Lag2 + I(Lag2^2), data = Weekly, family = binomial, subset = train)
glm_tran_probs <- predict(glm_tran, Weekly_test, type = "response")
glm_tran_pred <- rep("Down", nrow(Weekly_test))
glm_tran_pred[glm_tran_probs > 0.5] <- "Up"
table(glm_tran_pred, Weekly_test$Direction)
##              
## glm_tran_pred Down Up
##          Down    8  4
##          Up     35 57
mean(glm_tran_pred == Weekly_test$Direction)
## [1] 0.625
# LDA with Lag2 Lag1 Interactions
lda_inter <- lda(Direction ~ Lag1 + Lag2 + Lag1:Lag2, data = Weekly, subset = train)
lda_inter <- predict(lda_inter, Weekly_test)
table(lda_inter$class, Weekly_test$Direction)
##       
##        Down Up
##   Down    7  8
##   Up     36 53
mean(lda_inter$class == Weekly_test$Direction)
## [1] 0.5769231

Problem 14

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

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

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

set.seed(42)
n <- nrow(Auto)
train_idx  <- sample(1:n, size = floor(0.65 * n))
auto_train <- Auto[train_idx, ]
auto_test  <- Auto[-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?

lda_auto <- lda(mpg01 ~ cylinders + displacement + horsepower + weight,
                data = auto_train)
lda_auto_pred <- predict(lda_auto, auto_test)

table(lda_auto_pred$class, auto_test$mpg01)
##    
##      0  1
##   0 52  6
##   1  8 72
mean(lda_auto_pred$class != auto_test$mpg01)
## [1] 0.1014493

(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_auto <- qda(mpg01 ~ cylinders + displacement + horsepower + weight,
                data = auto_train)
qda_auto_pred <- predict(qda_auto, auto_test)

table(qda_auto_pred$class, auto_test$mpg01)
##    
##      0  1
##   0 53  7
##   1  7 71
mean(qda_auto_pred$class != auto_test$mpg01)
## [1] 0.1014493

(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_auto <- glm(mpg01 ~ cylinders + displacement + horsepower + weight,
                data = auto_train, family = binomial)
glm_auto_probs <- predict(glm_auto, auto_test, type = "response")
glm_auto_pred  <- ifelse(glm_auto_probs > 0.5, 1, 0)

table(glm_auto_pred, auto_test$mpg01)
##              
## glm_auto_pred  0  1
##             0 54  6
##             1  6 72
mean(glm_auto_pred != auto_test$mpg01)
## [1] 0.08695652

(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_auto <- naiveBayes(mpg01 ~ cylinders + displacement + horsepower + weight,
                      data = auto_train)
nb_auto_pred <- predict(nb_auto, auto_test)

table(nb_auto_pred, auto_test$mpg01)
##             
## nb_auto_pred  0  1
##            0 51  6
##            1  9 72
mean(nb_auto_pred != auto_test$mpg01)
## [1] 0.1086957

(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?

knn_trainX <- scale(auto_train[,c("cylinders","displacement","horsepower","weight")])
knn_testX <- scale(auto_test[,c("cylinders","displacement","horsepower","weight")])
knn_trainY <- auto_train$mpg01

knn_pred <- knn(knn_trainX, knn_testX, knn_trainY, k=5)
table(knn_pred, auto_test$mpg01)
##         
## knn_pred  0  1
##        0 52  5
##        1  8 73
mean(knn_pred == auto_test$mpg01)
## [1] 0.9057971
knn.pred <- knn(knn_trainX, knn_testX, knn_trainY, k=10)
table(knn_pred, auto_test$mpg01)
##         
## knn_pred  0  1
##        0 52  5
##        1  8 73
mean(knn_pred == auto_test$mpg01)
## [1] 0.9057971
knn.pred <- knn(knn_trainX, knn_testX, knn_trainY, k=1)
table(knn_pred, auto_test$mpg01)
##         
## knn_pred  0  1
##        0 52  5
##        1  8 73
mean(knn_pred == auto_test$mpg01)
## [1] 0.9057971

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

# Create binary response variable
Boston$crim01 <- ifelse(Boston$crim > median(Boston$crim), 1, 0)
Boston$crim01 <- as.factor(Boston$crim01)

cor(Boston[, -which(names(Boston) == "crim01")])
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
##                  rm         age         dis          rad         tax    ptratio
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431  0.2899456
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332 -0.3916785
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018  0.3832476
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652 -0.1215152
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320  0.1889327
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783 -0.3555015
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559  0.2615150
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158 -0.2324705
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819  0.4647412
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000  0.4608530
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304  1.0000000
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801 -0.1773833
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341  0.3740443
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593 -0.5077867
##               black      lstat       medv
## crim    -0.38506394  0.4556215 -0.3883046
## zn       0.17552032 -0.4129946  0.3604453
## indus   -0.35697654  0.6037997 -0.4837252
## chas     0.04878848 -0.0539293  0.1752602
## nox     -0.38005064  0.5908789 -0.4273208
## rm       0.12806864 -0.6138083  0.6953599
## age     -0.27353398  0.6023385 -0.3769546
## dis      0.29151167 -0.4969958  0.2499287
## rad     -0.44441282  0.4886763 -0.3816262
## tax     -0.44180801  0.5439934 -0.4685359
## ptratio -0.17738330  0.3740443 -0.5077867
## black    1.00000000 -0.3660869  0.3334608
## lstat   -0.36608690  1.0000000 -0.7376627
## medv     0.33346082 -0.7376627  1.0000000
# Train/test split
set.seed(42)
n_bos <- nrow(Boston)
bos_train_idx <- sample(1:n_bos, size = floor(0.65 * n_bos))
bos_train <- Boston[bos_train_idx, ]
bos_test  <- Boston[-bos_train_idx, ]
# Logistic Regression
glm_bos <- glm(crim01 ~ nox + rad + age + dis + indus + tax, data = bos_train, family = binomial)
glm_bos_probs <- predict(glm_bos, bos_test, type = "response")
glm_bos_pred  <- ifelse(glm_bos_probs > 0.5, 1, 0)
table(glm_bos_pred, bos_test$crim01)
##             
## glm_bos_pred  0  1
##            0 81 12
##            1  8 77
mean(glm_bos_pred != bos_test$crim01)
## [1] 0.1123596
# LDA
lda_bos <- lda(crim01 ~ nox + rad + age + dis + indus + tax, data = bos_train)
lda_bos_pred <- predict(lda_bos, bos_test)
table(lda_bos_pred$class, bos_test$crim01)
##    
##      0  1
##   0 87 20
##   1  2 69
mean(lda_bos_pred$class != bos_test$crim01)
## [1] 0.1235955
# Naive Bayes
nb_bos <- naiveBayes(crim01 ~ nox + rad + age + dis + indus + tax, data = bos_train)
nb_bos_pred <- predict(nb_bos, bos_test)
table(nb_bos_pred, bos_test$crim01)
##            
## nb_bos_pred  0  1
##           0 84 21
##           1  5 68
mean(nb_bos_pred != bos_test$crim01)
## [1] 0.1460674
train_bos_knn <- scale(bos_train[,c("nox", "rad", "age", "dis", "indus", "tax")])
test_bos_knn <- scale(bos_test[,c("nox", "rad", "age", "dis", "indus", "tax")])
train_bos_y <- bos_train$crim01

knn_bos <- knn(train_bos_knn, test_bos_knn, train_bos_y, k=15)
table(knn_bos, bos_test$crim01)
##        
## knn_bos  0  1
##       0 79  4
##       1 10 85
mean(knn_bos == bos_test$crim01)
## [1] 0.9213483
knn_bos <- knn(train_bos_knn, test_bos_knn, train_bos_y, k=10)
table(knn_bos, bos_test$crim01)
##        
## knn_bos  0  1
##       0 81  4
##       1  8 85
mean(knn_bos == bos_test$crim01)
## [1] 0.9325843
knn_bos <- knn(train_bos_knn, test_bos_knn, train_bos_y, k=1)
table(knn_bos, bos_test$crim01)
##        
## knn_bos  0  1
##       0 83  4
##       1  6 85
mean(knn_bos == bos_test$crim01)
## [1] 0.9438202