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.
(a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
Yes, the trend seems to be that the volume increases as time goes on.
attach(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)
plot(Weekly$Volume)
(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?
Yes, the predictor Lag2, p-value = 0.0296, is statistically significant at alpha = 0.05.
glm.fit = glm(Direction ~ . - Year - Today, data = Weekly, family = "binomial")
summary(glm.fit)
##
## Call:
## glm(formula = Direction ~ . - Year - Today, 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
(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.
According to the confusion matrix table, the model correctly predicted 54 down out of 484 down and correctly predicted 557 up out of 605 up. The logistic model did better in predicting up in comparison to predicting down, with correctly predicting up by 92% (557/605) and only correctly predicted down by 11% (54/484). Overall, the model correctly predicted 56.12% (611/1089) of the outcome.
glm.probs = predict(glm.fit, type = "response")
glm.pred = rep("Down", 1089)
glm.pred[glm.probs > 0.5] = "Up"
table(glm.pred, Weekly$Direction)
##
## glm.pred Down Up
## Down 54 48
## Up 430 557
(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).
According to the confusion matrix table of the Logistic Regression using Lag2 as the predictor, the model correctly predicted 9 down out of 43 down and correctly predicted 56 up out of 61 up. The logistic model did better in predicting up in comparison to predicting down, with correctly predicting up by 92% (56/61) and only correctly predicted down by 21% (9/34). Overall, the model correctly predicted 62.5% of the outcome.
#creck the year variable
#table(Year)
#create a vector for train set
train <-(Year<2009)
#create dataset with years above 2009
Weekly.2009 <- Weekly[!train,]
Direction.2009 <- Direction[!train]
#see dimension of original dataset and the new created subset
dim(Weekly)
## [1] 1089 9
dim(Weekly.2009)
## [1] 104 9
#fit a logistic regression using train set
glm.fit2 <- glm(Direction ~ Lag2 , data= Weekly, subset = train, family = binomial)
glm.probs <- predict(glm.fit2, Weekly.2009, type = "response")
glm.pred <- rep("Down", 104)
glm.pred[glm.probs>0.5] = "Up"
#confusion matrix
table(glm.pred, Direction.2009)
## Direction.2009
## glm.pred Down Up
## Down 9 5
## Up 34 56
#check correct classification
mean(glm.pred==Direction.2009)
## [1] 0.625
(e) Repeat (d) using LDA.
LDA resulted to the same accuracy, specificity, and sensitivity as the Logistic Regression above.
#fit an LDA with train set
lda.fit <- lda(Direction ~ Lag2, data = Weekly, subset = train)
lda.fit
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2
## Down -0.03568254
## Up 0.26036581
##
## Coefficients of linear discriminants:
## LD1
## Lag2 0.4414162
#plot(lda.fit)
#fit with test set
lda.pred=predict(lda.fit, Weekly.2009)
names(lda.pred)
## [1] "class" "posterior" "x"
lda.class=lda.pred$class
table(lda.class, Direction.2009)
## Direction.2009
## lda.class Down Up
## Down 9 5
## Up 34 56
#check correct classifications
mean(lda.class==Direction.2009)
## [1] 0.625
(f) Repeat (d) using QDA.
According to the confusion matrix table of the Quadratic Discriminant Analysis using Lag2 as the predictor, the model correctly predicted 0 down out of 43 down and correctly predicted 61 up out of 61 up. The Quadratic Discriminant Analysis model did better in predicting up in comparison to predicting down, with correctly predicting up by 100% (61/61) and did not correctly predicted any down’s. Overall, the model correctly predicted 58.65% of the outcome.
#fit a QDA with train set
qda.fit <- qda(Direction ~ Lag2, data = Weekly, subset = train)
qda.fit
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2
## Down -0.03568254
## Up 0.26036581
#plot(qda.fit)
#fit with test set
qda.pred=predict(qda.fit, Weekly.2009)
names(qda.pred)
## [1] "class" "posterior"
qda.class=qda.pred$class
table(qda.class, Direction.2009)
## Direction.2009
## qda.class Down Up
## Down 0 0
## Up 43 61
#check correct classifications
mean(qda.class==Direction.2009)
## [1] 0.5865385
(g) Repeat (d) using KNN with K = 1.
According to the confusion matrix table of the K-Nearest Neighbors using Lag2 as the predictor, the model correctly predicted 21 down out of 43 down and correctly predicted 31 up out of 61 up. Overall, the model correctly predicted 50% (52/104) of the outcome.
train.X=as.matrix(Lag2[train])
test.X=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
knn.pred=knn(train.X,test.X,train.Direction,k=1)
table(knn.pred,Direction.2009)
## Direction.2009
## knn.pred Down Up
## Down 21 30
## Up 22 31
(h) Which of these methods appears to provide the best results on this data?
Logistic and LDA did better in regards of accuracy in comparison to QDA and KNN, QDA did better in predicting if the market will go up, and KNN did not do as well as the others in accuracy, specificity, or sensitivity.
(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.
According to the models with predictor Lag2 and interactions between Lag2 and Lag5, there is a slight improvement in accuracy in the Logistic Regression and LDA with the accuracy of 63.46% in comparison to the initial model accuracy of 62.5% and increased the number of correctly predicted up by 1. The QDA model decreased in accuracy from 58.65% to 50.96%. The KNN model with KNN classifier of 20 increased in accuracy from 50% to 58.65%, the number of correctly predicted up increased from 31 to 40.
#fit a logistic regression using train set
glm.fit2 <- glm(Direction ~ Lag2:Lag5+ Lag2 , data= Weekly, subset = train, family = binomial)
glm.probs <- predict(glm.fit2, Weekly.2009, type = "response")
glm.pred <- rep("Down", 104)
glm.pred[glm.probs>0.5] = "Up"
#confusion matrix
table(glm.pred, Direction.2009)
## Direction.2009
## glm.pred Down Up
## Down 9 4
## Up 34 57
#check correct classification
mean(glm.pred==Direction.2009)
## [1] 0.6346154
#fit an LDA with train set
lda.fit <- lda(Direction ~ Lag2:Lag5+ Lag2, data = Weekly, subset = train)
lda.fit
## Call:
## lda(Direction ~ Lag2:Lag5 + Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2 Lag2:Lag5
## Down -0.03568254 -0.3132494
## Up 0.26036581 -0.3497535
##
## Coefficients of linear discriminants:
## LD1
## Lag2 0.44645312
## Lag2:Lag5 0.01369782
#plot(lda.fit)
#fit with test set
lda.pred=predict(lda.fit, Weekly.2009)
names(lda.pred)
## [1] "class" "posterior" "x"
lda.class=lda.pred$class
table(lda.class, Direction.2009)
## Direction.2009
## lda.class Down Up
## Down 9 4
## Up 34 57
#check correct classifications
mean(lda.class==Direction.2009)
## [1] 0.6346154
#fit a QDA with train set
qda.fit <- qda(Direction ~ Lag2:Lag5 + Lag2, data = Weekly, subset = train)
qda.fit
## Call:
## qda(Direction ~ Lag2:Lag5 + Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2 Lag2:Lag5
## Down -0.03568254 -0.3132494
## Up 0.26036581 -0.3497535
#plot(qda.fit)
#fit with test set
qda.pred=predict(qda.fit, Weekly.2009)
names(qda.pred)
## [1] "class" "posterior"
qda.class=qda.pred$class
table(qda.class, Direction.2009)
## Direction.2009
## qda.class Down Up
## Down 5 13
## Up 38 48
#check correct classifications
mean(qda.class==Direction.2009)
## [1] 0.5096154
train.X=as.matrix(Lag2[train])
test.X=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
knn.pred=knn(train.X,test.X,train.Direction,k=20)
table(knn.pred,Direction.2009)
## Direction.2009
## knn.pred Down Up
## Down 21 21
## Up 22 40
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.
(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)
mpg01 <- rep(0, length(mpg))
mpg01[mpg > median(mpg)] <- 1
Auto <- data.frame(Auto, mpg01)
#median(mpg)
(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.
According to the boxplots below, as cylinders increases then the mpg decreases, as displacements increases then mpg decreases, as `horsepower increases then mpg decreases, as weight increases then mpg decreases, as acceleration decreases then mpg increases, and older cars are less fuel efficient.
#Boxplots of all numeric variables
par(mar=c(2,2,2,2))
par(mfrow=c(2,3))
boxplot(cylinders ~ mpg01, data = Auto, main = "Cylinders vs mpg01", col="#FF9999")
boxplot(displacement ~ mpg01, data = Auto, main = "Displacement vs mpg01", col="#FF9999")
boxplot(horsepower ~ mpg01, data = Auto, main = "Horsepower vs mpg01", col="#FF9999")
boxplot(weight ~ mpg01, data = Auto, main = "Weight vs mpg01", col="#FF9999")
boxplot(acceleration ~ mpg01, data = Auto, main = "Acceleration vs mpg01", col="#FF9999")
boxplot(year ~ mpg01, data = Auto, main = "Year vs mpg01", col="#FF9999")
(c) Split the data into a training set and a test set.
train <- (year %% 2 == 0)
test <- !train
Auto.train <- Auto[train,]
Auto.test <- Auto[test,]
mpg01.test <- mpg01[test]
(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?
The test error of the model is 12.64%
lda.fit <- lda(mpg01 ~ cylinders + weight + displacement + horsepower,
data = Auto, subset = train)
lda.pred <- predict(lda.fit, Auto.test)
mean(lda.pred$class != mpg01.test)
## [1] 0.1263736
(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?
The test error of the model is 13.19%
qda.fit <- qda(mpg01 ~ cylinders + weight + displacement + horsepower,
data = Auto, subset = train)
qda.pred = predict(qda.fit, Auto.test)
mean(qda.pred$class != mpg01.test)
## [1] 0.1318681
(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?
The test error of the model is 12.09%
glm.fit = glm(mpg01 ~ 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 != mpg01.test)
## [1] 0.1208791
(g) 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 test error of the model for k=1 is 15.38%, k=5 is 14.84%, and k=25 is 14.28. The k number of 25 performed slightly the best.
train.X <- cbind(cylinders, weight, displacement, horsepower)[train,]
test.X <- cbind(cylinders, weight, displacement, horsepower)[test,]
train.mpg01 <- mpg01[train]
set.seed(1)
# KNN (k=1)
knn.pred <- knn(train.X, test.X, train.mpg01, k = 1)
mean(knn.pred != mpg01.test)
## [1] 0.1538462
# KNN (k=5)
knn.pred <- knn(train.X, test.X, train.mpg01, k = 5)
mean(knn.pred != mpg01.test)
## [1] 0.1483516
# KNN (k=10)
knn.pred <- knn(train.X, test.X, train.mpg01, k = 25)
mean(knn.pred != mpg01.test)
## [1] 0.1428571
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)
#create new column
crim01 <- rep(0, length(crim))
crim01[crim > median(crim)] <- 1
Boston <- data.frame(Boston, crim01)
# median(crim) = 0.25651
#create test and train set
train = 1:(length(crim) / 2)
test = (length(crim) / 2 + 1):length(crim)
Boston.train = Boston[train, ]
Boston.test = Boston[test, ]
crim01.test = crim01[test]
According to the results of the logistic regression below, the model accuracy is 81.82%, it correctly predicted 68 0 (below the median crime rate) out of 90, and correctly predicted 139 1 (above the median crime rate) out of 163.
#fit a logistic regresion
glm.fit <- glm(crim01 ~ . - 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
#confusion matrix
table(glm.pred, crim01.test)
## crim01.test
## glm.pred 0 1
## 0 68 24
## 1 22 139
#check correct classification
mean(glm.pred==crim01.test)
## [1] 0.8181818
According to the results of the LDA model below, the model accuracy is 86.56%, it correctly predicted 80 0 (below the median crime rate) out of 90, and correctly predicted 139 1 (above the median crime rate) out of 163.
#fit an LDA model
lda.fit <- lda(crim01 ~ . - crim, data = Boston, subset = train)
lda.pred <- predict(lda.fit, Boston.test)
table(lda.pred$class, crim01.test)
## crim01.test
## 0 1
## 0 80 24
## 1 10 139
mean(lda.pred$class == crim01.test)
## [1] 0.8656126
According to the results of the KNN model below, the model accuracy is 88.93%, it correctly predicted 83 0 (below the median crime rate) out of 90, and correctly predicted 142 1 (above the median crime rate) out of 163.
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.crim01 <- crim01[train]
set.seed(1)
knn.pred <- knn(train.X, test.X, train.crim01, k = 10)
table(knn.pred, crim01.test)
## crim01.test
## knn.pred 0 1
## 0 83 21
## 1 7 142