4.7 EXERCISE: 10 (Applied)

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.

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

correlations=cor(Weekly[, -9]); corrplot(correlations, method="circle")

corr_data = Weekly[, -9]
pairs(Weekly[, -9])

corr_results <- cor(corr_data, use = "complete.obs")
kable(round(corr_results, 2),)
Year Lag1 Lag2 Lag3 Lag4 Lag5 Volume Today
Year 1.00 -0.03 -0.03 -0.03 -0.03 -0.03 0.84 -0.03
Lag1 -0.03 1.00 -0.07 0.06 -0.07 -0.01 -0.06 -0.08
Lag2 -0.03 -0.07 1.00 -0.08 0.06 -0.07 -0.09 0.06
Lag3 -0.03 0.06 -0.08 1.00 -0.08 0.06 -0.07 -0.07
Lag4 -0.03 -0.07 0.06 -0.08 1.00 -0.08 -0.06 -0.01
Lag5 -0.03 -0.01 -0.07 0.06 -0.08 1.00 -0.06 0.01
Volume 0.84 -0.06 -0.09 -0.07 -0.06 -0.06 1.00 -0.03
Today -0.03 -0.08 0.06 -0.07 -0.01 0.01 -0.03 1.00

(10.a) Answer: A pattern is seen between correlation Year and Volume confirmed by their 0.84 correlation.

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

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

(10.b) Answer: Lag 2 appears to be statistically significant

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

Weekly_glm_preds = predict(Weekly_glm_fit, type = "response")

Weekly_glm_yhats = ifelse(Weekly_glm_preds >= .5, "Up","Down")

confusionMatrix(as.factor(Weekly$Direction), as.factor(Weekly_glm_yhats), positive = 'Up')
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down  Up
##       Down   54 430
##       Up     48 557
##                                          
##                Accuracy : 0.5611         
##                  95% CI : (0.531, 0.5908)
##     No Information Rate : 0.9063         
##     P-Value [Acc > NIR] : 1              
##                                          
##                   Kappa : 0.035          
##                                          
##  Mcnemar's Test P-Value : <2e-16         
##                                          
##             Sensitivity : 0.5643         
##             Specificity : 0.5294         
##          Pos Pred Value : 0.9207         
##          Neg Pred Value : 0.1116         
##              Prevalence : 0.9063         
##          Detection Rate : 0.5115         
##    Detection Prevalence : 0.5556         
##       Balanced Accuracy : 0.5469         
##                                          
##        'Positive' Class : Up             
## 

(10.c) Answer: The overall fraction of correct predictions is: (54+557)/(54+557+48+430) = 56.1%. Weeks the market goes up the model is right 557/(430+557) = 56.4% and wrong 48/(557+48)= 43.6% Weeks the market goes down the model is right 54/(54+48) = 52.9% and wrong 48/(54+48)= 47.1%

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

#data does not go below 1990
lessthan_2009 = (Weekly$Year < 2009)
Weekly_greaterthan_2009 = Weekly[!lessthan_2009, ]

lessthan_2009_glm_fit = glm(Direction ~ Lag2, 
                            data = Weekly, family = binomial, subset = lessthan_2009)

lessthan_2009_probs = predict(lessthan_2009_glm_fit, Weekly_greaterthan_2009, type = "response")
lessthan_2009_pred = rep("Down", length(lessthan_2009_probs))
lessthan_2009_pred[lessthan_2009_probs > 0.5] = "Up"
Direction_greaterthan_2009 = Weekly$Direction[!lessthan_2009]
table(lessthan_2009_pred, Direction_greaterthan_2009)
##                   Direction_greaterthan_2009
## lessthan_2009_pred Down Up
##               Down    9  5
##               Up     34 56
mean(lessthan_2009_pred == Direction_greaterthan_2009)
## [1] 0.625

(10.d) Answer: The fraction of correct predictions for the held out data (9+56)/(9+56+34+5)= 62.5%

(10.e) Repeat (10.d) using LDA

lda.fit = lda(Direction ~ Lag2, data = Weekly, subset = lessthan_2009)
lda.pred = predict(lda.fit, Weekly_greaterthan_2009)
table(lda.pred$class, Direction_greaterthan_2009)
##       Direction_greaterthan_2009
##        Down Up
##   Down    9  5
##   Up     34 56
mean(lda.pred$class == Direction_greaterthan_2009)
## [1] 0.625

(10.e) Answer: The fraction of correct predictions for the held out data (9+56)/(9+56+34+5)= 62.5%

(10.f) Repeat (10.d) using QDA.

qda.fit = qda(Direction ~ Lag2, data = Weekly, subset = lessthan_2009)
qda.class = predict(qda.fit, Weekly_greaterthan_2009)$class
table(qda.class, Direction_greaterthan_2009)
##          Direction_greaterthan_2009
## qda.class Down Up
##      Down    0  0
##      Up     43 61
mean(qda.class == Direction_greaterthan_2009)
## [1] 0.5865385

(10.f) Answer: The fraction of correct predictions for the held out data (0+61)/(43+61)= 58.6%

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

lessthan_2009.X = as.matrix(Weekly$Lag2[lessthan_2009])
test.X = as.matrix(Weekly$Lag2[!lessthan_2009])
lessthan_2009.Direction = Weekly$Direction[lessthan_2009]
set.seed(1)
knn.pred = knn(lessthan_2009.X, test.X, lessthan_2009.Direction, k = 1)
table(knn.pred, Direction_greaterthan_2009)
##         Direction_greaterthan_2009
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred == Direction_greaterthan_2009)
## [1] 0.5

(10.g) Answer: The fraction of correct predictions for the held out data (21+31)/(21+31+30+22)=50%

(10.h) Which of these methods appears to provide the best results on this data?

(10.h) Answer: The methods that appear to provide the best results on this data are logistic regression and LDA.

(10.i) 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.

(10.i) Logistic regression with Lag2:Lag1

glm.fit = glm(Direction ~ Lag2:Lag1, 
              data = Weekly, family = binomial, subset = lessthan_2009)
glm.probs = predict(glm.fit, Weekly_greaterthan_2009, type = "response")
glm.pred = rep("Down", length(glm.probs))
glm.pred[glm.probs > 0.5] = "Up"
Direction_greaterthan_2009 = Weekly$Direction[!lessthan_2009]
table(glm.pred, Direction_greaterthan_2009)
##         Direction_greaterthan_2009
## glm.pred Down Up
##     Down    1  1
##     Up     42 60
mean(glm.pred == Direction_greaterthan_2009)
## [1] 0.5865385

(10.i) LDA with Lag2 interaction with Lag1

lda.fit = lda(Direction ~ Lag2:Lag1, data = Weekly, subset = lessthan_2009)
lda.pred = predict(lda.fit, Weekly_greaterthan_2009)

mean(lda.pred$class == Direction_greaterthan_2009)
## [1] 0.5769231

(10.i) QDA with sqrt(abs(Lag2))

qda.fit = qda(Direction ~ Lag2 + sqrt(abs(Lag2)), data = Weekly, subset = lessthan_2009)
qda.class = predict(qda.fit, Weekly_greaterthan_2009)$class
table(qda.class, Direction_greaterthan_2009)
##          Direction_greaterthan_2009
## qda.class Down Up
##      Down   12 13
##      Up     31 48
mean(qda.class == Direction_greaterthan_2009)
## [1] 0.5769231

(10.i) KNN k =10

knn.pred = knn(lessthan_2009.X, test.X, lessthan_2009.Direction, k = 10)
table(knn.pred, Direction_greaterthan_2009)
##         Direction_greaterthan_2009
## knn.pred Down Up
##     Down   17 18
##     Up     26 43
mean(knn.pred == Direction_greaterthan_2009)
## [1] 0.5769231

(10.i) KNN k =100

knn.pred = knn(lessthan_2009.X, test.X, lessthan_2009.Direction, k = 100)
table(knn.pred, Direction_greaterthan_2009)
##         Direction_greaterthan_2009
## knn.pred Down Up
##     Down    9 12
##     Up     34 49
mean(knn.pred == Direction_greaterthan_2009)
## [1] 0.5576923

(10.i) Answer: The LDA and logistic regression from (10.g) retain the best test error rate.

4.7 EXERCISE: 11 (Applied)

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.

summary(Auto)

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

attach(Auto)
more_than_mpg_median = rep(0, length(mpg))
more_than_mpg_median[mpg > median(mpg)] = 1
Auto = data.frame(Auto, more_than_mpg_median)

(11.b) Explore the data graphically in order to investigate the association between more_than_mpg_median and the other features. Which of the other features seem most likely to be useful in predicting more_than_mpg_median? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.

correlations=cor(Auto[, -9]); corrplot(correlations, method="circle")

corr_data = Auto[, -9]
corr_results <- cor(corr_data, use = "complete.obs"); 
kable(round(corr_results, 2),)
mpg cylinders displacement horsepower weight acceleration year origin more_than_mpg_median
mpg 1.00 -0.78 -0.81 -0.78 -0.83 0.42 0.58 0.57 0.84
cylinders -0.78 1.00 0.95 0.84 0.90 -0.50 -0.35 -0.57 -0.76
displacement -0.81 0.95 1.00 0.90 0.93 -0.54 -0.37 -0.61 -0.75
horsepower -0.78 0.84 0.90 1.00 0.86 -0.69 -0.42 -0.46 -0.67
weight -0.83 0.90 0.93 0.86 1.00 -0.42 -0.31 -0.59 -0.76
acceleration 0.42 -0.50 -0.54 -0.69 -0.42 1.00 0.29 0.21 0.35
year 0.58 -0.35 -0.37 -0.42 -0.31 0.29 1.00 0.18 0.43
origin 0.57 -0.57 -0.61 -0.46 -0.59 0.21 0.18 1.00 0.51
more_than_mpg_median 0.84 -0.76 -0.75 -0.67 -0.76 0.35 0.43 0.51 1.00

(11.b) Answer: The newly created binary variable, more_than_mpg_median, has a negative correlation with cylinders, weight, displacement, horsepower. and perfect pos cor with mpg

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

train = (year%%2 == 0)  # if the year is even
test = !train
Auto.train = Auto[train, ]
Auto.test = Auto[test, ]
more_than_mpg_median.test = more_than_mpg_median[test]

(11.d) Perform LDA on the training data in order to predict more_than_mpg_median using the variables that seemed most associated with more_than_mpg_median in (b). What is the test error of the model obtained?

lda.fit = lda(more_than_mpg_median ~ cylinders + weight + displacement + horsepower, data = Auto, 
    subset = train)
lda.pred = predict(lda.fit, Auto.test)
mean(lda.pred$class != more_than_mpg_median.test)
## [1] 0.1263736

(11.d) Answer: 12.6% test error rate.

(11.e) Perform QDA on the training_indexesing data in order to predict more_than_mpg_median using the variables that seemed most associated with more_than_mpg_median in (b). What is the test error of the model obtained?

qda.fit = qda(more_than_mpg_median ~ cylinders + weight + displacement + horsepower, data = Auto, subset = train)
qda.pred = predict(qda.fit, Auto.test)
mean(qda.pred$class != more_than_mpg_median.test)
## [1] 0.1318681

(11.e) Answer: 13.2% test error rate.

(11.f) Perform logistic regression on the training_indexesing data in order to predict more_than_mpg_median using the variables that seemed most associated with more_than_mpg_median in (b). What is the test error of the model obtained?

glm.fit = glm(more_than_mpg_median ~ cylinders + weight + displacement + horsepower, data = Auto, 
    family = binomial, subset = train)
glm.probs = predict(glm.fit, Auto.test, type = "response")
glm.pred = rep(0, length(glm.probs))
glm.pred[glm.probs > 0.5] = 1
mean(glm.pred != more_than_mpg_median.test)
## [1] 0.1208791

(11.f) Answer: 12.1% test error rate.

(11.g) Perform KNN on the training_indexesing data, with several values of K, in order to predict more_than_mpg_median. Use only the variables that seemed most associated with more_than_mpg_median in (b). What test errors do you obtain? Which value of K seems to perform the best on this data set?

train.X = cbind(cylinders, weight, displacement, horsepower)[train, ]
test.X = cbind(cylinders, weight, displacement, horsepower)[test, ]
train.more_than_mpg_median = more_than_mpg_median[train]
set.seed(1)
# KNN(k=1)
knn.pred = knn(train.X, test.X, train.more_than_mpg_median, k = 1)
mean(knn.pred != more_than_mpg_median.test)
## [1] 0.1538462

(11.g) KNN(k=10)

knn.pred = knn(train.X, test.X, train.more_than_mpg_median, k = 10)
mean(knn.pred != more_than_mpg_median.test)
## [1] 0.1648352

(11.g) KNN(k=100)

knn.pred = knn(train.X, test.X, train.more_than_mpg_median, k = 100)
mean(knn.pred != more_than_mpg_median.test)
## [1] 0.1428571

(11.g) Answer: The test errors I obtain are:
15.4% for K=1 16.5% for K=10
14.3% for k=10
The value of K that seems to perform the best on this data set is 100.

4.7 EXERCISE: 13 (Applied)

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

summary(Boston)
attach(Boston)
crime = rep(0, length(crim))
crime[crim > median(crim)] = 1
Boston = data.frame(Boston, crime)

train = 1:(dim(Boston)[1]/2)
test = (dim(Boston)[1]/2 + 1):dim(Boston)[1]
Boston.train = Boston[train, ]
Boston.test = Boston[test, ]
crime.test = crime[test]

(13.0) logistic regression model 1

glm.fit = glm(crime ~ . - crime - crim, data = Boston, family = binomial, subset = train)

glm.probs = predict(glm.fit, Boston.test, type = "response")
glm.pred = rep(0, length(glm.probs))
glm.pred[glm.probs > 0.5] = 1
mean(glm.pred != crime.test)
## [1] 0.1818182

(13.0) Answer: My first logistic regression model test error rate is 18.2%.

(13.0) logistic regression model 2

glm.fit = glm(crime ~ . - crime - crim - chas - tax, data = Boston, family = binomial, 
    subset = train)

glm.probs = predict(glm.fit, Boston.test, type = "response")
glm.pred = rep(0, length(glm.probs))
glm.pred[glm.probs > 0.5] = 1
mean(glm.pred != crime.test)
## [1] 0.1857708

(13.0) Answer: My second logistic regression model test error rate is 18.6%.

(13.0 LDA 1)

lda.fit = lda(crime ~ . - crime - crim, data = Boston, subset = train)
lda.pred = predict(lda.fit, Boston.test)
mean(lda.pred$class != crime.test)
## [1] 0.1343874

(13.0) Answer: My first LDA model test error rate is 13.4%

(13.0 LDA 2)

lda.fit = lda(crime ~ . - crime - crim - chas - tax, data = Boston, subset = train)
lda.pred = predict(lda.fit, Boston.test)
mean(lda.pred$class != crime.test)
## [1] 0.1225296

(13.0) Answer: My second LDA model test error rate is 12.3%

(13.0 LDA 3)

lda.fit = lda(crime ~ . - crime - crim - chas - tax - lstat - indus - age, data = Boston, subset = train)
lda.pred = predict(lda.fit, Boston.test)
mean(lda.pred$class != crime.test)
## [1] 0.1185771

(13.0) Answer: My third LDA model test error rate is 11.9%

(13.0) KNN

train.X = cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black, lstat, medv)[train, ]
test.X = cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black,  lstat, medv)[test, ]

train.crime = crime[train]

(13.0) KNN(k=1)

knn.pred = knn(train.X, test.X, train.crime, k = 1)
mean(knn.pred != crime.test)
## [1] 0.458498

(13.) Answer: My KNN(k=1) model test error rate is 45.8%

(13.0) KNN(k=10)

knn.pred = knn(train.X, test.X, train.crime, k = 10)
mean(knn.pred != crime.test)
## [1] 0.1106719

(13.) Answer: My KNN(k=10) model test error rate is 11.5%

(13.0) KNN(k=100)

knn.pred = knn(train.X, test.X, train.crime, k = 100)
mean(knn.pred != crime.test)
## [1] 0.4901186

(13.) Answer: My KNN(k=100) model test error rate is 49.0%

(13.0) KNN(k=10) with subset of variables

train.X = cbind(zn, nox, rm, dis, rad, ptratio, black, medv)[train, ]
test.X = cbind(zn, nox, rm, dis, rad, ptratio, black, medv)[test, ]
knn.pred = knn(train.X, test.X, train.crime, k = 10)
mean(knn.pred != crime.test)
## [1] 0.2687747

(13.) Answer: My KNN(k=10) with subset of variables model test error rate is 28.5%