Weekly data set, which is part of the ISLR package. This data is similar in nature to theSmarket 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.10A: Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
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)
corrplot(cor(Weekly[,-9]), method="square")
Comments: Based on the pairs and correlational plots, there aren’t really any patterns or significant relationship, other than Year and Volume.
10B: 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.week <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = Weekly, family = binomial)
summary (glm.week)
##
## 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
Comments: The only variable that seems statistically significant (p < 0.05) is Lag2. Other variables are greater than the cutoff point of 0.05, which means we fail to reject null hypothesis
10C: 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.
week.prob <- predict(glm.week, type = 'response')
week.pred <- rep("Down", 1089)
week.pred[week.prob > 0.5] = "Up"
table(week.pred, Weekly$Direction)
##
## week.pred Down Up
## Down 54 48
## Up 430 557
Comments: Based on the table above, we can see that while our prediction model correctly predicted the weekly Up trends well (TP = 557/(48+557) = 92.07%), it poorly predicted the weekly Down trend (TN = 54/(54+430) = 11.15%) Hence, this is not an ideal model.
10D: 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[Weekly$Year<2009,]
test <- Weekly[Weekly$Year>2008,]
glm.lag <- glm(Direction ~ Lag2, data = train, family = "binomial")
test.prob <- predict(glm.lag, type="response", newdata=test)
test.dir = Weekly$Direction[Weekly$Year>2008]
test.pred = rep("Down", 104)
test.pred[test.prob>0.5] = "Up"
table(test.pred, test.dir)
## test.dir
## test.pred Down Up
## Down 9 5
## Up 34 56
Comment: With this model, it correctly predicted weekly Up trends with 91.81% accuracy and weekly Down trends with 79.07% accuracy, so this isn’t really a bad model
10E: Repeat (d) using LDA
lda.fit <- lda(Direction ~ Lag2, data = train)
lda.pred <- predict(lda.fit, newdata = test, type = "response")
lda.class <- lda.pred$class
table(lda.class, test$Direction)
##
## lda.class Down Up
## Down 9 5
## Up 34 56
Comment: The LDA model created has more or less similar rate values as the logistic regression model in part (d)
10F: Repeat (d) using QDA
qda.fit <- qda(Direction ~ Lag2, data = train)
qda.pred <- predict(qda.fit, newdata = test, type = "response")
qda.class <- qda.pred$class
table(qda.class, test$Direction)
##
## qda.class Down Up
## Down 0 0
## Up 43 61
Comment: The QDA model only predicted our weekly Up trend. This is not good at all because we’re not only trying to predict weekly Up trends, but also its Down trends – it basically classifies all data as Up.
10G: Repeat (d) using KNN with K = 1
set.seed(9)
train.X <- cbind(train$Lag2)
test.X <- cbind(test$Lag2)
train.Y <- cbind(train$Direction)
pred.knn <- knn(train.X, test.X, train.Y, k=1)
table(pred.knn, test$Direction)
##
## pred.knn Down Up
## 1 21 29
## 2 22 32
Comment: The KNN with K = 1 produced an accuracy rate of 52.45% – equal to random chance
10H: Which of these methods appears to provide the best results on this data?
Answer: The best method that provides the best results on this data seems to be Logistic Regression and LDA since they have the highest accuracy out of all models (91.81% accuracy for Up trends, 79.07% accuracy for Down trends)
Auto data set.11A: 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.
set.seed(1)
mpg01 = rep(0,nrow(Auto))
mpg01[Auto$mpg>median(Auto$mpg)]=1
Auto = data.frame(Auto, mpg01)
11B: 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.
pairs(Auto)
cor(Auto[,-9])
## mpg cylinders displacement horsepower weight
## mpg 1.0000000 -0.7776175 -0.8051269 -0.7784268 -0.8322442
## cylinders -0.7776175 1.0000000 0.9508233 0.8429834 0.8975273
## displacement -0.8051269 0.9508233 1.0000000 0.8972570 0.9329944
## horsepower -0.7784268 0.8429834 0.8972570 1.0000000 0.8645377
## weight -0.8322442 0.8975273 0.9329944 0.8645377 1.0000000
## acceleration 0.4233285 -0.5046834 -0.5438005 -0.6891955 -0.4168392
## year 0.5805410 -0.3456474 -0.3698552 -0.4163615 -0.3091199
## origin 0.5652088 -0.5689316 -0.6145351 -0.4551715 -0.5850054
## mpg01 0.8369392 -0.7591939 -0.7534766 -0.6670526 -0.7577566
## acceleration year origin mpg01
## mpg 0.4233285 0.5805410 0.5652088 0.8369392
## cylinders -0.5046834 -0.3456474 -0.5689316 -0.7591939
## displacement -0.5438005 -0.3698552 -0.6145351 -0.7534766
## horsepower -0.6891955 -0.4163615 -0.4551715 -0.6670526
## weight -0.4168392 -0.3091199 -0.5850054 -0.7577566
## acceleration 1.0000000 0.2903161 0.2127458 0.3468215
## year 0.2903161 1.0000000 0.1815277 0.4299042
## origin 0.2127458 0.1815277 1.0000000 0.5136984
## mpg01 0.3468215 0.4299042 0.5136984 1.0000000
Comments: From these findings, we can see that mpg01 seems to have an inverse relationship with cylinders, displacement, horsepower, and weight. acceleration and year are positively correlated as this indicates that newer cars have faster acceleration and are fuel efficient.
11C: Split the data into a training set and a test set
#50/50
train.OBS <- sample(1:nrow(Auto),.5*nrow(Auto),replace=FALSE)
Auto.train <- Auto[train.OBS,]
Auto.test <- Auto[-train.OBS,]
mpg01.test <- Auto.test$mpg01
11D: 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_model <- lda(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto, subset = train.OBS)
lda_pred <- predict(lda_model, Auto.test)
mean(lda_pred$class != mpg01.test)
## [1] 0.127551
Comment: The test error rate obtained is 12.75%
11E: 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_model <- qda(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto, subset = train.OBS)
qda_pred <- predict(qda_model, Auto.test)
mean(qda_pred$class != mpg01.test)
## [1] 0.1173469
Comment: The test error rate obtained is 11.73%
11F: 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_fit = glm(mpg01 ~ cylinders + weight + displacement + horsepower, data = Auto, family = binomial, subset = train.OBS)
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.122449
Comment: The test error rate obtained is 12.24%
11G: 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?
library(class)
train.X = cbind(Auto$cylinders, Auto$weight, Auto$displacement, Auto$horsepower)[train.OBS, ]
test.X = cbind(Auto$cylinders, Auto$weight, Auto$displacement, Auto$horsepower)[-train.OBS, ]
train.mpg01 = mpg01[train.OBS]
#K = 1
knn.pred <- knn(train.X, test.X, train.mpg01, k = 1)
mean(knn.pred != mpg01.test)
## [1] 0.1785714
#K = 5
knn.pred <- knn(train.X, test.X, train.mpg01, k = 5)
mean(knn.pred != mpg01.test)
## [1] 0.127551
#K = 9
knn.pred <- knn(train.X, test.X, train.mpg01, k = 9)
mean(knn.pred != mpg01.test)
## [1] 0.122449
Comment: The K value that seems to perform best on this dataset is K = 9, as it yields the lowest error rate of 12.24%
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.Step 1: Creating a binary variable, crim01, that contains 1 if crim contains a value above its media, and a 0 if crim contains a value below its median
attach(Boston)
crime01 <- rep(0, length(crim))
crime01[crim > median(crim)] <- 1
Boston= data.frame(Boston,crime01)
Step 2: Explore the data graphically to investigate association between crim01 and other features
pairs(Boston)
corrplot(cor(Boston), method = "square")
Comment: From the correlation plot above, we can see that indus, nox, age, dis, rad, and tax have strong relationships with mpg01
Step 3: Splitting dataset
train <- 1:(dim(Boston)[1]/2)
test <- (dim(Boston)[1]/2 + 1):dim(Boston)[1]
Boston.train <- Boston[train, ]
Boston.test <- Boston[test, ]
crime01.test <- crime01[test]
Step 4: Performing Logistic Regression
set.seed(1)
Boston.fit <- glm(crime01~ indus + nox + age + dis + rad + tax, data=Boston.train, family=binomial)
Boston.probs <- predict(Boston.fit, Boston.test, type = "response")
Boston.pred <- rep(0, length(Boston.probs))
Boston.pred[Boston.probs > 0.5] <- 1
table(Boston.pred, crime01.test)
## crime01.test
## Boston.pred 0 1
## 0 75 8
## 1 15 155
mean(Boston.pred != crime01.test)
## [1] 0.09090909
summary(Boston.fit)
##
## Call:
## glm(formula = crime01 ~ indus + nox + age + dis + rad + tax,
## family = binomial, data = Boston.train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.97810 -0.21406 -0.03454 0.47107 3.04502
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -42.214032 7.617440 -5.542 2.99e-08 ***
## indus -0.213126 0.073236 -2.910 0.00361 **
## nox 80.868029 16.066473 5.033 4.82e-07 ***
## age 0.003397 0.012032 0.282 0.77772
## dis 0.307145 0.190502 1.612 0.10690
## rad 0.847236 0.183767 4.610 4.02e-06 ***
## tax -0.013760 0.004956 -2.777 0.00549 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 329.37 on 252 degrees of freedom
## Residual deviance: 144.44 on 246 degrees of freedom
## AIC: 158.44
##
## Number of Fisher Scoring iterations: 8
Comment: Test error rate is 9.09%
Step 5: Performing LDA
Boston.lda <- lda(crime01~ indus + nox + age + dis + rad + tax, data = Boston.train)
Boston.lda.pred <- predict(Boston.lda, Boston.test)
mean(Boston.lda.pred$class != crime01.test)
## [1] 0.1067194
Comment: Test error rate is 10.67%
Step 6: Performing KNN
library(class)
train.K <- cbind(indus,nox,age,dis,rad,tax)[train,]
test.K <- cbind(indus,nox,age,dis,rad,tax)[test,]
#K = 1
Bosknn.pred <- knn(train.K, test.K, crime01.test, k=1)
table(Bosknn.pred,crime01.test)
## crime01.test
## Bosknn.pred 0 1
## 0 31 155
## 1 59 8
mean(Bosknn.pred !=crime01.test)
## [1] 0.8458498
#K = 20
Bosknn.pred <- knn(train.K, test.K, crime01.test, k=20)
table(Bosknn.pred,crime01.test)
## crime01.test
## Bosknn.pred 0 1
## 0 38 18
## 1 52 145
mean(Bosknn.pred !=crime01.test)
## [1] 0.2766798
#K = 50
Bosknn.pred <- knn(train.K, test.K, crime01.test, k=50)
table(Bosknn.pred,crime01.test)
## crime01.test
## Bosknn.pred 0 1
## 0 38 14
## 1 52 149
mean(Bosknn.pred !=crime01.test)
## [1] 0.2608696
#K = 70
Bosknn.pred <- knn(train.K, test.K, crime01.test, k=70)
table(Bosknn.pred,crime01.test)
## crime01.test
## Bosknn.pred 0 1
## 0 33 12
## 1 57 151
mean(Bosknn.pred !=crime01.test)
## [1] 0.2727273
Comment: After runnning all three models, Logistic Regression seems to be the most effective out of all three as it has the lowest error rate (9.09%) When looking at the summary of the Logistic Regression model, only indux, rad, tax, and noz are statistically significant. The KNN model (K=1) seems to have the highest error rate of 85.58%, making it the least effective model. As we increase the K value, the error rate drops but not significantly.