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)
library(corrplot)
## corrplot 0.92 loaded
(a) 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)
Well, I do not see much correlation between the variables, except for ‘year’ and ‘volume’. Trying corrplot to cross verify.
corrplot(cor(Weekly[,-9]), method="square")
The corrplot shows that ‘Volume’ and ‘year’ are correlated.
(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?
attach(Weekly)
glm.fit=glm(Direction ~ Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data = Weekly,family=binomial)
summary(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
glm.probs=predict(glm.fit, type='response')
glm.pred=rep("Down", length(glm.probs))
glm.pred[glm.probs>0.5]="Up"
table(glm.pred, Direction)
## Direction
## glm.pred Down Up
## Down 54 48
## Up 430 557
‘Lag2’ is significantly associated with ‘Direction’. The p-value is 0.0296, which is lower than 0.5. The other variables fail to reject the NULL hypothesis.
(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.
The percentage of correct prediction is (54+557)/(54+48+430+557) = 0.5610. i.e., the model predicted up and down trends correctly 56% of the time.
(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).
#Creating a vector index
attach(Weekly)
## The following objects are masked from Weekly (pos = 3):
##
## Direction, Lag1, Lag2, Lag3, Lag4, Lag5, Today, Volume, Year
#creaing train dataset
train=(Year<2009)
#Creating a test dataset
Weekly.0910= Weekly[!train,]
glm.fits=glm(Direction~Lag2, data=Weekly, subset=train, family=binomial)
Direction.0910=Direction[!train]
glm.probs=predict(glm.fits, Weekly.0910, type='response')
glm.pred=rep('Down', 104)
glm.pred[glm.probs>0.5]='Up'
table(glm.pred,Direction.0910)
## Direction.0910
## glm.pred Down Up
## Down 9 5
## Up 34 56
#How many times did logistic regression predict right
mean(glm.pred==Direction.0910)
## [1] 0.625
After splitting the whole data into training and test data, the model correctly predicted 62.5% of the time. This model is better than the previous one, where the whole dataset was used.
(e) Repeat (d) using LDA.
library(MASS)
lda.fits<-lda(Direction~Lag2, data=Weekly, subset=train)
lda.fits
## 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.fits)
lda.pred=predict(lda.fits,Weekly.0910)
lda.class=lda.pred$class
table(lda.class,Direction.0910)
## Direction.0910
## lda.class Down Up
## Down 9 5
## Up 34 56
mean(lda.class==Direction.0910)
## [1] 0.625
The Linear Discriminant analysis yielded the similar results as in logistic regression.
(f) Repeat (d) using QDA.
qda.fits<-qda(Direction~Lag2, data=Weekly, subset=train)
qda.fits
## 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
#Create class
qda.class=predict(qda.fits,Weekly.0910)$class
table(qda.class,Direction.0910)
## Direction.0910
## qda.class Down Up
## Down 0 0
## Up 43 61
mean(qda.class == Direction.0910)
## [1] 0.5865385
The quadratic discriminant analysis model accuracy is only 58.65%, which is lower than the last two models.
(g) Repeat (d) using KNN with K = 1.
library(class)
train.X=as.matrix(Lag2[train])
test.X=as.matrix(Lag2[!train])
train.Direction=Direction[train]
#dim(train.X)
#dim(test.X)
#length(train.Direction)
#Set the seed to ensure the reproducibility of the results
set.seed(1)
knn.pred=knn(train.X,test.X,train.Direction,k=1)
table(knn.pred,Direction.0910)
## Direction.0910
## knn.pred Down Up
## Down 21 30
## Up 22 31
mean(knn.pred==Direction.0910)
## [1] 0.5
The KNN model resulted in classifying model with an accuracy of only 50%.
(h) Which of these methods appears to provide the best results on this data?
The logistic regression and LDA provide the best results. Both the models have accuracy of 62.5%.
(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.
An interaction term of Lag2 and Lag4 is added to the model.
attach(Weekly)
## The following objects are masked from Weekly (pos = 5):
##
## Direction, Lag1, Lag2, Lag3, Lag4, Lag5, Today, Volume, Year
## The following objects are masked from Weekly (pos = 6):
##
## Direction, Lag1, Lag2, Lag3, Lag4, Lag5, Today, Volume, Year
Weekly.fit1<-glm(Direction ~ Lag2:Lag4 + Lag2, data=Weekly,family=binomial, subset=train)
Weekly.prob1= predict(Weekly.fit1, Weekly.0910, type = "response")
Weekly.pred1 = rep("Down", length(Weekly.prob1))
Weekly.pred1[Weekly.prob1 > 0.5] = "Up"
Direction.0910 = Direction[!train]
table(Weekly.pred1, Direction.0910)
## Direction.0910
## Weekly.pred1 Down Up
## Down 3 4
## Up 40 57
The logistic regression predicted correctly, (57+3)/(57+3+40+4) = 57.69% of the time.
LDA
library(MASS)
lda.fiti = lda(Direction~Lag2:Lag4+Lag2, data=Weekly, subset=train)
lda.fiti
## Call:
## lda(Direction ~ Lag2:Lag4 + Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2 Lag2:Lag4
## Down -0.03568254 0.78824608
## Up 0.26036581 0.04407141
##
## Coefficients of linear discriminants:
## LD1
## Lag2 0.3442725
## Lag2:Lag4 -0.0608715
#plot(lda.fits)
lda.pred=predict(lda.fiti,Weekly.0910)
lda.class=lda.pred$class
table(lda.class,Direction.0910)
## Direction.0910
## lda.class Down Up
## Down 3 3
## Up 40 58
mean(lda.class==Direction.0910)
## [1] 0.5865385
LDA predicted 58.65% of the time.
QDA
qda.fits<-qda(Direction~Lag2 + Lag4:Lag2, data=Weekly, subset=train)
qda.fits
## Call:
## qda(Direction ~ Lag2 + Lag4:Lag2, data = Weekly, subset = train)
##
## Prior probabilities of groups:
## Down Up
## 0.4477157 0.5522843
##
## Group means:
## Lag2 Lag2:Lag4
## Down -0.03568254 0.78824608
## Up 0.26036581 0.04407141
#Create class
qda.class=predict(qda.fits,Weekly.0910)$class
table(qda.class,Direction.0910)
## Direction.0910
## qda.class Down Up
## Down 7 6
## Up 36 55
mean(qda.class == Direction.0910)
## [1] 0.5961538
The QDA predicted correctly 59.6% of the time.
KNN
Trying Knn with different values of k for the earlier model - which had only 50% of accuracy.
library(class)
train.X=as.matrix(Lag2[train])
test.X=as.matrix(Lag2[!train])
train.Direction=Direction[train]
dim(train.X)
## [1] 985 1
dim(test.X)
## [1] 104 1
length(train.Direction)
## [1] 985
#Set the seed to ensure the reproducibility of the results
set.seed(1)
knn.pred=knn(train.X,test.X,train.Direction,k=10)
table(knn.pred,Direction.0910)
## Direction.0910
## knn.pred Down Up
## Down 17 21
## Up 26 40
mean(knn.pred==Direction.0910)
## [1] 0.5480769
The KNN model with k=10 predicted correctly 54.8% of the time.Increasing k=100.
library(class)
train.X=as.matrix(Lag2[train])
test.X=as.matrix(Lag2[!train])
train.Direction=Direction[train]
dim(train.X)
## [1] 985 1
dim(test.X)
## [1] 104 1
length(train.Direction)
## [1] 985
#Set the seed to ensure the reproducibility of the results
set.seed(1)
knn.pred=knn(train.X,test.X,train.Direction,k=100)
table(knn.pred,Direction.0910)
## Direction.0910
## knn.pred Down Up
## Down 10 11
## Up 33 50
mean(knn.pred==Direction.0910)
## [1] 0.5769231
Now, the KNN predicted correctly by 57.69% of the time when k=100 for this model.
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.
library(ISLR)
attach(Auto)
summary(Auto)
## mpg cylinders displacement horsepower weight
## Min. : 9.00 Min. :3.000 Min. : 68.0 Min. : 46.0 Min. :1613
## 1st Qu.:17.00 1st Qu.:4.000 1st Qu.:105.0 1st Qu.: 75.0 1st Qu.:2225
## Median :22.75 Median :4.000 Median :151.0 Median : 93.5 Median :2804
## Mean :23.45 Mean :5.472 Mean :194.4 Mean :104.5 Mean :2978
## 3rd Qu.:29.00 3rd Qu.:8.000 3rd Qu.:275.8 3rd Qu.:126.0 3rd Qu.:3615
## Max. :46.60 Max. :8.000 Max. :455.0 Max. :230.0 Max. :5140
##
## acceleration year origin name
## Min. : 8.00 Min. :70.00 Min. :1.000 amc matador : 5
## 1st Qu.:13.78 1st Qu.:73.00 1st Qu.:1.000 ford pinto : 5
## Median :15.50 Median :76.00 Median :1.000 toyota corolla : 5
## Mean :15.54 Mean :75.98 Mean :1.577 amc gremlin : 4
## 3rd Qu.:17.02 3rd Qu.:79.00 3rd Qu.:2.000 amc hornet : 4
## Max. :24.80 Max. :82.00 Max. :3.000 chevrolet chevette: 4
## (Other) :365
median(mpg)
## [1] 22.75
Auto$mpg01 <- ifelse(Auto$mpg>22.75, 1, 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.
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
##
## select
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
##
## Attaching package: 'ggplot2'
## The following object is masked from 'Auto':
##
## mpg
#Calling another plotting library
library(GGally)
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
#For easy plotting removing the columns - mpg and name from Auto
Auto1 <- Auto[,-c(1,9)]
#We use the function "ifelse" to assess the categorical based on mpg
Auto1$mpg01 <- ifelse(Auto1$mpg01 >= 1, "above", "below")
ggpairs(Auto1, aes(colour = mpg01))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
The box plot shows that ‘weight’ and ‘year’ are clearly showing the separation between ‘above’ and ‘below’ median. For ‘cylinder’, ‘displacement’, ‘horsepower’ the decision boundary is clear. However, the distribution of observations are far from normal. It is difficult to classify ‘acceleration’ as well as ‘origin’.
(c) Split the data into a training set and a test set.
#Creating a vector index
attach(Auto)
## The following object is masked from package:ggplot2:
##
## mpg
## The following objects are masked from Auto (pos = 6):
##
## acceleration, cylinders, displacement, horsepower, mpg, name,
## origin, weight, year
train=(year<81)
#Creating a test dataset
Auto.8182= Auto[!train,]
(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?
##Checking what variables are most associated with mpg01
glm.fita=glm(mpg01~cylinders+displacement+horsepower+weight+acceleration+year, data = Auto,family=binomial)
summary(glm.fita)
##
## Call:
## glm(formula = mpg01 ~ cylinders + displacement + horsepower +
## weight + acceleration + year, family = binomial, data = Auto)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.1999 -0.1126 0.0115 0.2249 3.3019
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -15.828787 5.653426 -2.800 0.00511 **
## cylinders -0.015009 0.405220 -0.037 0.97045
## displacement -0.006745 0.009961 -0.677 0.49831
## horsepower -0.035608 0.023543 -1.512 0.13042
## weight -0.003986 0.001085 -3.673 0.00024 ***
## acceleration 0.007983 0.141357 0.056 0.95497
## year 0.414204 0.072700 5.697 1.22e-08 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 543.43 on 391 degrees of freedom
## Residual deviance: 159.34 on 385 degrees of freedom
## AIC: 173.34
##
## Number of Fisher Scoring iterations: 8
‘weight’ and ‘year’ are significantly associated with mpg01. Hence, the LDA is performed to predict mpg01 using weight and year.
LDA
lda.fita<-lda(mpg01~ weight+year, data=Auto, subset=train)
lda.fita
## Call:
## lda(mpg01 ~ weight + year, data = Auto, subset = train)
##
## Prior probabilities of groups:
## 0 1
## 0.5748503 0.4251497
##
## Group means:
## weight year
## 0 3629.292 74.25521
## 1 2299.430 76.04930
##
## Coefficients of linear discriminants:
## LD1
## weight -0.001685936
## year 0.087475780
#plot(lda.fits)
lda.pred=predict(lda.fita,Auto.8182)
lda.class=lda.pred$class
mpg01.8182=mpg01[!train]
table(lda.class,mpg01.8182)
## mpg01.8182
## lda.class 0 1
## 0 2 2
## 1 2 52
mean(lda.class==mpg01.8182)
## [1] 0.9310345
mean(lda.class!=mpg01.8182)
## [1] 0.06896552
The test error rate of LDA model is 6.89%.The LDA correctly predicted 93.1% of the time.
(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.fita<-qda(mpg01~ weight+year, data=Auto, subset=train)
qda.fita
## Call:
## qda(mpg01 ~ weight + year, data = Auto, subset = train)
##
## Prior probabilities of groups:
## 0 1
## 0.5748503 0.4251497
##
## Group means:
## weight year
## 0 3629.292 74.25521
## 1 2299.430 76.04930
#Create class
qda.class=predict(qda.fita,Auto.8182)$class
table(qda.class,mpg01.8182)
## mpg01.8182
## qda.class 0 1
## 0 2 2
## 1 2 52
mean(qda.class == mpg01.8182)
## [1] 0.9310345
mean(qda.class != mpg01.8182)
## [1] 0.06896552
Using QDA, we got the similar results. QDA model correctly predicted 93.1% of the time.The test error rate is 6.89%.
(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.fits=glm(mpg01~weight+year, data=Auto, subset=train, family=binomial)
mpg01.8182=mpg01[!train]
glm.probs=predict(glm.fits, Auto.8182, type='response')
glm.pred=rep('Down', 52)
glm.pred[glm.probs>0.5]='Up'
table(glm.pred,mpg01.8182)
## mpg01.8182
## glm.pred 0 1
## Down 2 2
## Up 2 52
The percentage of correct prediction is (52+2)/(52+2+2+2) = 0.9310. i.e., the model predicted up and down trends correctly 93% of the time. The test error rate is (2+2)/(52+2+2+2)=6.89%.
(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?
library(class)
train.X=cbind(weight,year)[train,]
test.X=cbind(weight,year)[!train,]
train.mpg01=mpg01[train]
dim(train.X)
## [1] 334 2
dim(test.X)
## [1] 58 2
length(train.mpg01)
## [1] 334
#Set the seed to ensure the reproducibility of the results
set.seed(1)
knn.pred=knn(train.X,test.X,train.mpg01,k=1)
table(knn.pred,mpg01.8182)
## mpg01.8182
## knn.pred 0 1
## 0 3 13
## 1 1 41
mean(knn.pred==mpg01.8182)
## [1] 0.7586207
The KNN model resulted in classifying model with an accuracy of only 75.86% for k=1. In this dataset, logistic regression, LDA and QDA performed better than KNN.Trying for k=10.
library(class)
train.X=cbind(weight,year)[train,]
test.X=cbind(weight,year)[!train,]
train.mpg01=mpg01[train]
dim(train.X)
## [1] 334 2
dim(test.X)
## [1] 58 2
length(train.mpg01)
## [1] 334
#Set the seed to ensure the reproducibility of the results
set.seed(1)
knn.pred=knn(train.X,test.X,train.mpg01,k=10)
table(knn.pred,mpg01.8182)
## mpg01.8182
## knn.pred 0 1
## 0 4 13
## 1 0 41
mean(knn.pred==mpg01.8182)
## [1] 0.7758621
For K=10, KNN predicted correctly 77.59%. As k increases, KNN model is getting better.
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.
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
median(mpg)
## [1] 22.75
attach(Boston)
median(crim) #Median is 0.25651
## [1] 0.25651
Boston1<-Boston
Boston1$crim01 <- ifelse(Boston1$crim>0.25651, 1, 0)
View(Boston1)
attach(Boston1)
## The following objects are masked from Boston:
##
## age, black, chas, crim, dis, indus, lstat, medv, nox, ptratio, rad,
## rm, tax, zn
#The data is split such that 80% is training dataset and 20% is the test dataset
## 80% of the sample size
smp_size <- floor(0.80 * nrow(Boston1))
## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(Boston1)), size = smp_size)
Boston.train <- Boston1[train_ind, ]
Boston.test <- Boston1[-train_ind, ]
#test1<-dim(test)
#Check the dimensions
dim(Boston.train)
## [1] 404 15
dim(Boston.test)
## [1] 102 15
library(corrplot)
corrplot(cor(Boston1), method="square")
The variable, ‘indus’, ‘nox’, ‘age’, ‘rad’and ’tax’ are correlated with ‘crim01’.
Logistic regression
set.seed(1)
glm.fitb = glm(crim01 ~ indus+nox+age+rad+tax,data = Boston.train, family=binomial)
#crim01test=crim01[test1]
summary(glm.fitb)
##
## Call:
## glm(formula = crim01 ~ indus + nox + age + rad + tax, family = binomial,
## data = Boston.train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.90833 -0.27994 -0.02743 0.01473 2.74633
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -19.819313 3.230436 -6.135 8.51e-10 ***
## indus -0.013366 0.053069 -0.252 0.801152
## nox 35.379066 6.954376 5.087 3.63e-07 ***
## age 0.015777 0.009910 1.592 0.111359
## rad 0.554555 0.130690 4.243 2.20e-05 ***
## tax -0.009433 0.002815 -3.351 0.000805 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 560.02 on 403 degrees of freedom
## Residual deviance: 199.63 on 398 degrees of freedom
## AIC: 211.63
##
## Number of Fisher Scoring iterations: 8
glm.probb=predict(glm.fitb, Boston.test, type='response')
glm.predb=rep('Down', length(glm.probb))
glm.predb[glm.probb>0.5]='Up'
View(Boston.test)
#dim(Boston.train$crim01)
table(glm.predb,Boston.test$crim01)
##
## glm.predb 0 1
## Down 44 6
## Up 5 47
The logistic regression model correctly predicted (44+47)/(44+47+6+5), i.e., 81.22% of the time.
LDA
lda.fitb<-lda(crim01 ~ indus+nox+age+rad+tax,data = Boston.train, family=binomial)
lda.fitb
## Call:
## lda(crim01 ~ indus + nox + age + rad + tax, data = Boston.train,
## family = binomial)
##
## Prior probabilities of groups:
## 0 1
## 0.5049505 0.4950495
##
## Group means:
## indus nox age rad tax
## 0 6.831618 0.4699054 50.94363 4.22549 309.6765
## 1 15.332850 0.6361000 86.59250 14.79000 508.6700
##
## Coefficients of linear discriminants:
## LD1
## indus 0.039468916
## nox 6.599459223
## age 0.014213119
## rad 0.106187045
## tax -0.003217974
#plot(lda.fits)
lda.predb=predict(lda.fitb,Boston.test)
lda.classb=lda.predb$class
table(lda.classb,Boston.test$crim01)
##
## lda.classb 0 1
## 0 44 13
## 1 5 40
mean(lda.classb==Boston.test$crim01)
## [1] 0.8235294
LDA predicted 82.35% of the time. The previous model is better than LDA.
KNN
library(class)
train.X=cbind(indus,nox,age,rad,tax)[Boston.train$crim01,]
test.X=cbind(indus,nox,age,rad,tax)[Boston.test$crim01,]
train.crim01=crim01[Boston.train$crim01]
#Set the seed to ensure the reproducibility of the results
set.seed(1)
knn.pred=knn(train.X,test.X,train.crim01,k=1)
#table(knn.pred,Boston.test$crim01)
mean(knn.pred==Boston.test$crim01)
## Warning in `==.default`(knn.pred, Boston.test$crim01): longer object length is
## not a multiple of shorter object length
## Warning in is.na(e1) | is.na(e2): longer object length is not a multiple of
## shorter object length
## [1] 0.4803922
#table(knn.pred,mpg01.8182)
#mean(knn.pred==mpg01.8182)
KNN predicted only 48.03% of the time only. Thus, LDA is a better model.