Exercise 10

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.

library(ISLR)
## Warning: package 'ISLR' was built under R version 3.6.3
library(knitr)
attach(Weekly)

pairs(Weekly)

cor_tbl_10 <- kable(cor(Weekly[,-9]))
cor_tbl_10
Year Lag1 Lag2 Lag3 Lag4 Lag5 Volume Today
Year 1.0000000 -0.0322893 -0.0333900 -0.0300065 -0.0311279 -0.0305191 0.8419416 -0.0324599
Lag1 -0.0322893 1.0000000 -0.0748531 0.0586357 -0.0712739 -0.0081831 -0.0649513 -0.0750318
Lag2 -0.0333900 -0.0748531 1.0000000 -0.0757209 0.0583815 -0.0724995 -0.0855131 0.0591667
Lag3 -0.0300065 0.0586357 -0.0757209 1.0000000 -0.0753959 0.0606572 -0.0692877 -0.0712436
Lag4 -0.0311279 -0.0712739 0.0583815 -0.0753959 1.0000000 -0.0756750 -0.0610746 -0.0078259
Lag5 -0.0305191 -0.0081831 -0.0724995 0.0606572 -0.0756750 1.0000000 -0.0585174 0.0110127
Volume 0.8419416 -0.0649513 -0.0855131 -0.0692877 -0.0610746 -0.0585174 1.0000000 -0.0330778
Today -0.0324599 -0.0750318 0.0591667 -0.0712436 -0.0078259 0.0110127 -0.0330778 1.0000000

Inspecting the pair-wise plots it looks like there aren’t any clear relationships between any two variable except for Year and Volume and maybe even Today and Direction. The plots suggest and as time goes on Volume will increase, and that if a market was up on a given week then the percentage return for that week (Today) will tend to be higher.
The correlation table confirms that there is strong relationship between Year and Volume (correlation coefficient of ~0.84).

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

There is one statistically significant predictor (assuming a significance level of 0.05), and that is Lag2 with a p-value of 0.0296.

log_10_probs <- predict(log_10_fits, type = 'response')
log_10_pred <- rep("Down", 1089)
#We will consider any probabilities greater than 0.5 as "Up"
log_10_pred[log_10_probs>0.5] = "Up"
table(log_10_pred, Direction)
##            Direction
## log_10_pred Down  Up
##        Down   54  48
##        Up    430 557

The confusion matrix is telling us that we had 54 correct predictions for when the market had a negative return for that week and 557 correct predictions for when the market had a positive return for that week. Note that we also had some incorrect predictions. The mis-classification rate of this model is \((48+430)/(54+48+430+557) = 43.9\%\).

#First we need to define training data set.
train_10 <- (Year< 2008)
Weekly.train <- Weekly[train_10,]
Weekly.test <- Weekly[!train_10,]

log_10_fits_2 <- glm(Direction~Lag2, data = Weekly.train, family = binomial)
log_10_probs_2 <- predict(log_10_fits_2, Weekly.test, type = 'response')
log_10_pred_2 <- rep('Down', 156)
log_10_pred_2[log_10_probs_2>0.5] = "Up"
table(log_10_pred_2, Weekly.test$Direction)
##              
## log_10_pred_2 Down Up
##          Down    7  5
##          Up     65 79
#Accuracy rate:
(7 + 79)/156
## [1] 0.5512821
library(MASS)
lda_10_fits <- lda(Direction~Lag2, data = Weekly, subset = train_10)
lda_10_prob <- predict(lda_10_fits, Weekly.test)
lda_10_class <- lda_10_prob$class
table(lda_10_class, Weekly.test$Direction)
##             
## lda_10_class Down Up
##         Down    6  5
##         Up     66 79
#LDA accuracy rate:
(6+79)/156
## [1] 0.5448718
qda_10_fits <- qda(Direction~Lag2, data = Weekly, subset = train_10)
qda_10_prob <- predict(qda_10_fits, Weekly.test)
qda_10_class <- qda_10_prob$class
table(qda_10_class, Weekly.test$Direction)
##             
## qda_10_class Down Up
##         Down    0  0
##         Up     72 84
#QDA accuracy rate:
(0+84)/156
## [1] 0.5384615
library(class)

train.x_10 <- matrix(Lag2[train_10])
test.x_10 <- matrix(Lag2[!train_10])
train.direction_10 <- Direction[train_10]
set.seed(1)
knn_pred_10 <- knn(train.x_10, test.x_10, train.direction_10, k=1)
table(knn_pred_10, Weekly.test$Direction)
##            
## knn_pred_10 Down Up
##        Down   32 38
##        Up     40 46
#KNN accuracy rate:
(32+46)/156
## [1] 0.5

The logistic model seems to provide the best results with an accuracy rate of 55.13%.

#Different Logistic models
#Include Lag1 and the interaction between Lag1 and Lag2
log_10_fits_3 <- glm(Direction~Lag1 + Lag2 + Lag1:Lag2, data = Weekly.train, family = binomial)
log_10_probs_3 <- predict(log_10_fits_3, Weekly.test, type = 'response')
log_10_pred_3 <- rep('Down', 156)
log_10_pred_3[log_10_probs_3>0.5] = "Up"
table(log_10_pred_3, Weekly.test$Direction)
##              
## log_10_pred_3 Down Up
##          Down   10 11
##          Up     62 73
(10 + 73)/156
## [1] 0.5320513
#Include Lag1 and Lag2 and square them
log_10_fits_4 <- glm(Direction~Lag1**2+Lag2**2, data = Weekly.train, family = binomial)
log_10_probs_4 <- predict(log_10_fits_4, Weekly.test, type = 'response')
log_10_pred_4 <- rep('Down', 156)
log_10_pred_4[log_10_probs_4>0.5] = "Up"
table(log_10_pred_4, Weekly.test$Direction)
##              
## log_10_pred_4 Down Up
##          Down    8  8
##          Up     64 76
(8 + 76)/156
## [1] 0.5384615
#Different LDA/QDA models:
#Include Lag1 thru Lag5
lda_10_fits_2 <- lda(Direction~Lag1+Lag2+Lag3+Lag4+Lag5, data = Weekly, subset = train_10)
lda_10_prob_2 <- predict(lda_10_fits_2, Weekly.test)
lda_10_class_2 <- lda_10_prob_2$class
table(lda_10_class_2, Weekly.test$Direction)
##               
## lda_10_class_2 Down Up
##           Down   14 14
##           Up     58 70
(14 + 70)/156
## [1] 0.5384615
#Include Lag1, Lag2, and Lag3
qda_10_fits_2 <- qda(Direction~Lag1+Lag2+Lag3, data = Weekly, subset = train_10)
qda_10_prob_2 <- predict(qda_10_fits_2, Weekly.test)
qda_10_class_2 <- qda_10_prob_2$class
table(qda_10_class_2, Weekly.test$Direction)
##               
## qda_10_class_2 Down Up
##           Down    8 12
##           Up     64 72
(8+72)/156
## [1] 0.5128205
#Different KNN models
#K = 3
set.seed(1)
knn_pred_10_2 <- knn(train.x_10, test.x_10, train.direction_10, k=3)
table(knn_pred_10_2, Weekly.test$Direction)
##              
## knn_pred_10_2 Down Up
##          Down   25 28
##          Up     47 56
(24 + 56)/156
## [1] 0.5128205
#K = 5
set.seed(1)
knn_pred_10_3 <- knn(train.x_10, test.x_10, train.direction_10, k=5)
table(knn_pred_10_3, Weekly.test$Direction)
##              
## knn_pred_10_3 Down Up
##          Down   24 29
##          Up     48 55
(24 + 55)/156
## [1] 0.5064103
detach(Weekly)

Based on these models, the models that yielded the best results was the second logistic model where the Lag1 and Lag2 variables were squared, and the LDA model where Lag1 through Lag5 were the variables. The accuracy for both of these models was 53.85%.

Exercise 11

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 <- rep(0, 392)
mpg01[Auto$mpg > median(Auto$mpg)] = 1
mpg01 <- as.factor(mpg01)
Auto_2 <- data.frame(Auto, mpg01)
attach(Auto_2)
## The following object is masked _by_ .GlobalEnv:
## 
##     mpg01
pairs(Auto_2)

par(mfrow=c(1,2))
plot(mpg01, horsepower, main = "Horsepower by MPG Class", sub ="(0 for Low MPG and 1 for High MPG)", xlab = "MPG Class", ylab = "Horsepower")
plot(mpg01, weight, main = "Weight by MPG Class", xlab = "MPG Class", ylab = "Weight (lbs.)")

Based on the two-way scatter plots, it looks like Horsepower and Weight may be correlated to the type of MPG class (mpg01). This is confirmed to be the case by the two box plots shown. An MPG class of 1 tends to have lower powerclass and a lower weight whereas an MPG class of 0 tends to have a higher horsepower and weight.

#I will do a 70/20 split on my training vs test data set.
#To randomly pick my training observations I will generate 392 "coin flips" that have a probability of 0.7 to return a 1.
#A 1 indicates my observation will be a training obervation and 0 is a test observation.
#To do this, a binomial distribution will be used with a probability set at 0.7.
set.seed(1)
train_11 <- rbinom(392, 1, 0.7)
Auto_2 <- cbind(Auto_2, train_11)
Auto.train <- Auto_2[train_11 == 1,]
Auto.test <- Auto_2[train_11 == 0,]
lda_11_fits <- lda(mpg01~horsepower + weight, data = Auto.train)
lda_11_preds <- predict(lda_11_fits, Auto.test, type = "response")
lda_11_class <- lda_11_preds$class 
table(lda_11_preds$class, Auto.test$mpg01)
##    
##      0  1
##   0 44  2
##   1 15 51
#Error rate:
(2 + 15)/112
## [1] 0.1517857
qda_11_fits <- qda(mpg01~horsepower + weight, data = Auto.train)
qda_11_preds <- predict(qda_11_fits, Auto.test, type = "response")
qda_11_class <- qda_11_preds$class 
table(qda_11_preds$class, Auto.test$mpg01)
##    
##      0  1
##   0 46  6
##   1 13 47
#Error rate:
(6 + 13)/112
## [1] 0.1696429
log_11_fits <- glm(mpg01~horsepower + weight, data = Auto.train, family = binomial)
log_11_probs <- predict(log_11_fits, Auto.test, type = "response")
log_11_preds <- rep(0, 112)
log_11_preds[log_11_probs>0.5] = 1
table(log_11_preds, Auto.test$mpg01)
##             
## log_11_preds  0  1
##            0 49  6
##            1 10 47
#Error rate:
(6 +10)/112
## [1] 0.1428571
train.x_11 <- cbind(Auto.train$horsepower, Auto.train$weight)
test.x_11 <- cbind(Auto.test$horsepower, Auto.test$weight)
set.seed(1)
knn_pred_11 <- knn(train.x_11, test.x_11, Auto.train$mpg01, k=1)
table(knn_pred_11, Auto.test$mpg01)
##            
## knn_pred_11  0  1
##           0 50  7
##           1  9 46
#Error rate:
(7 + 9)/112
## [1] 0.1428571
knn_pred_11_2 <- knn(train.x_11, test.x_11, Auto.train$mpg01, k=5)
table(knn_pred_11_2, Auto.test$mpg01)
##              
## knn_pred_11_2  0  1
##             0 50  9
##             1  9 44
#Error rate:
(9 + 9)/112
## [1] 0.1607143
knn_pred_11_3 <- knn(train.x_11, test.x_11, Auto.train$mpg01, k=20)
table(knn_pred_11_3, Auto.test$mpg01)
##              
## knn_pred_11_3  0  1
##             0 50  8
##             1  9 45
#Error rate:
(8 + 9)/112
## [1] 0.1517857
detach(Auto_2)

Based on these anlyses, the k level set at 1 yields the lowest error rate out of the KNN models tested.

Exercise 13

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.

attach(Boston)
median_crime = median(crim)
#We will create crim_lvl variable that takes on two values: "0" or "1".
#"0" if crime rate below median and "1" if above median.
crim_lvl <- rep(0, 506)
crim_lvl[crim > median_crime] = 1
crim_lvl <- as.factor(crim_lvl)
Boston_2 <- data.frame(Boston, crim_lvl)
detach(Boston)

pairs(Boston_2)

Looking at the pair-wise correlation plots, it looks like the variables nox, age, dis, medv may have some sort of correlation with our crime rate. Therefore these may make good predictors for our crim_lvl variable (crime level high or low, high if crime rate above median and low otherwise).

First we will run a logistic regression model to identify which of our predictors are significant, we will then evaluate how effective our model is at predicing if the crime rate will be above or below the median.

#We need to create our train and test data sets. We will use the same approach as followed in exercise 11 with the binomial random number picking method.
set.seed(1)
train_13 <- rbinom(506, 1, 0.7)
Boston_2 <- cbind(Boston_2, train_13)
Boston.train <- Boston_2[train_13 == 1,]
Boston.test <- Boston_2[train_13 == 0,]

#We will start by fitting a logistic model.
attach(Boston.train)
## The following objects are masked _by_ .GlobalEnv:
## 
##     crim_lvl, train_13
log_13_fits <- glm(crim_lvl~nox + age + dis + medv, data = Boston.train, family = binomial)
summary(log_13_fits)
## 
## Call:
## glm(formula = crim_lvl ~ nox + age + dis + medv, family = binomial, 
##     data = Boston.train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -2.17404  -0.35742   0.00278   0.26418   2.53635  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -24.900404   4.019591  -6.195 5.84e-10 ***
## nox          38.426015   5.859800   6.558 5.47e-11 ***
## age           0.016253   0.009966   1.631   0.1029    
## dis           0.309361   0.164026   1.886   0.0593 .  
## medv          0.087237   0.028230   3.090   0.0020 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 499.02  on 359  degrees of freedom
## Residual deviance: 210.55  on 355  degrees of freedom
## AIC: 220.55
## 
## Number of Fisher Scoring iterations: 7
#Looking at the fitted model, age is not a significant predictor, so we will remove it from the model. 
log_13_fits <- glm(crim_lvl~nox + dis + medv, data = Boston.train, family = binomial)
summary(log_13_fits)
## 
## Call:
## glm(formula = crim_lvl ~ nox + dis + medv, family = binomial, 
##     data = Boston.train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -2.19958  -0.39388   0.00252   0.26563   2.48475  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -23.94414    3.89175  -6.153 7.63e-10 ***
## nox          39.78032    5.77733   6.886 5.75e-12 ***
## dis           0.23393    0.15697   1.490  0.13615    
## medv          0.07713    0.02678   2.880  0.00398 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 499.02  on 359  degrees of freedom
## Residual deviance: 213.25  on 356  degrees of freedom
## AIC: 221.25
## 
## Number of Fisher Scoring iterations: 7
#dis has now become another un-significant predictor after the removal of age. So we will remove it until only significant predictors are left.
log_13_fits <- glm(crim_lvl~nox  + medv, data = Boston.train, family = binomial)
summary(log_13_fits)
## 
## Call:
## glm(formula = crim_lvl ~ nox + medv, family = binomial, data = Boston.train)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -2.17657  -0.38729   0.00523   0.30375   2.65695  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -19.74864    2.42833  -8.133  4.2e-16 ***
## nox          33.97633    3.88025   8.756  < 2e-16 ***
## medv          0.06605    0.02524   2.617  0.00887 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 499.02  on 359  degrees of freedom
## Residual deviance: 215.41  on 357  degrees of freedom
## AIC: 221.41
## 
## Number of Fisher Scoring iterations: 6
#Now we have our final set of predictors.
detach(Boston.train)

log_13_prob <- predict(log_13_fits, Boston.test, type = 'response')
log_13_preds <- rep(0, 146)
log_13_preds[log_13_prob > 0.5] = 1

dat <- matrix(data=table(log_13_preds, Boston.test$crim_lvl), nrow=2, ncol=2, 
              dimnames=list(c("Below median", "Above median"), c("Below", "Above")))
names(dimnames(dat)) <- c("predicted", "observed")
print(dat)
##               observed
## predicted      Below Above
##   Below median    63    16
##   Above median    12    55
#Error rate:
(16+12)/146
## [1] 0.1917808

The logistic model selected considered nox and medv as the predictors. The other predictors were taken out as they were not statistically significant predictors. The model states that as the nox variable increases (nitrogen oxides concentration), our predicted probability of above-median-crime-rate for that neighborhood increases. The model also states that as the median value of owner-occupied homes increases then the predicted probability for a high crime-rate also increases, however the effect of this variable on the probability is significant less than that of the nox variable.
The final error rate of this model with a threshold of 50% was 19.2%.

We will now run an LDA analysis using our original set of predictors (nox, age, dis, and medv).

lda_13_fits <- lda(crim_lvl~nox + age+ dis+medv, data = Boston_2, subset= (train_13==1))
#Our LDA model
lda_13_fits
## Call:
## lda(crim_lvl ~ nox + age + dis + medv, data = Boston_2, subset = (train_13 == 
##     1))
## 
## Prior probabilities of groups:
##         0         1 
## 0.4944444 0.5055556 
## 
## Group means:
##         nox      age      dis     medv
## 0 0.4690051 51.33371 5.241056 24.95618
## 1 0.6401758 86.26044 2.498684 20.19670
## 
## Coefficients of linear discriminants:
##              LD1
## nox   9.32383649
## age   0.01342745
## dis  -0.08315746
## medv  0.01499271
lda_13_preds <- predict(lda_13_fits, Boston.test)
lda_13_class <- lda_13_preds$class

dat <- matrix(data=table(lda_13_class, Boston.test$crim_lvl), nrow=2, ncol=2, 
              dimnames=list(c("Below median", "Above median"), c("Below", "Above")))
names(dimnames(dat)) <- c("predicted", "observed")
print(dat)
##               observed
## predicted      Below Above
##   Below median    62    14
##   Above median    13    57
#Error rate:
(14 + 13)/146
## [1] 0.1849315

The LDA model states that the nox, age, and medv variables have a positive correlation with the probability of a high crime rate (above median). The dis variable has a negative correlation with the predicted probablity. Using the LDA model, the error rate is slightly lower than that of the logistic model with the rate at 18.5%.

Our final model will be a K Nearest Neighbors model. These models will be ran with varying levels of k. The variables of interest in this model will be variables over which a city or town government may have some influence. The predictors will be nox, tax, and pratio.

train.x_13 <- cbind(Boston.train$nox, Boston.train$tax, Boston.train$pratio)
test.x_13 <- cbind(Boston.test$nox, Boston.test$tax, Boston.test$pratio)
set.seed(1)
knn_pred_13 <- knn(train.x_13, test.x_13, Boston.train$crim_lvl, k=3)
table(knn_pred_13, Boston.test$crim_lvl)
##            
## knn_pred_13  0  1
##           0 71  5
##           1  4 66
#Error rate:
(4 + 5)/146
## [1] 0.06164384
knn_pred_13_2 <- knn(train.x_13, test.x_13, Boston.train$crim_lvl, k=5)
table(knn_pred_13_2, Boston.test$crim_lvl)
##              
## knn_pred_13_2  0  1
##             0 69  5
##             1  6 66
#Error rate:
(5 + 6)/146
## [1] 0.07534247

We ran to KNN models, one with a k of 3 and one with a k of 5. The error rates were 6.2% and 7.5% respectively.This model outperforms the Logistic Regression and LDA models developed in the examples above. The best model is the KNN model with a k of 3. However, the difficulty with the KNN approach is that it doesn’t tell us which predictors are important and how they can affect the probability of our outcome. What we can take away from this model is that if we want to lower the crime rate of a community, we should look at what low-crime communities are doing. Based on our variables selected, we should look at that low-crime communities are doing in terms of air pollution, tax rates/tax structures, and school funding.