#5
We have seen that we can fit an SVM with a non-linear kernel in order to perform classification using a non-linear decision boundary.We will now see that we can also obtain a non-linear decision boundary by performing logistic regression using non-linear transformations of the features.
##(a) Generate a data set with n = 500 and p = 2, such that the observations belong to two classes with a quadratic decision boundary between them. For instance, you can do this as follows: x1=runif (500) -0.5, x2=runif (500) -0.5, y=1*( x12 -x22> 0)
set.seed(10)
x1=runif(500)-.5
x2=runif(500)-.5
y= as.integer(x1^2-x2^2 > 0)
plot(x1[y==0], x2[y==0], xlab='X1', ylab='X2', col='green', pch= '+')
points(x1[y==1], x2[y==1],col='blue', pch=4)
#(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
datax = data.frame(x1=x1, x2=x2, y=y)
lm.fit<-glm(y~ ., data= datax, family=binomial)
summary(lm.fit)
##
## Call:
## glm(formula = y ~ ., family = binomial, data = datax)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.347 -1.152 1.024 1.166 1.297
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.02449 0.08988 0.272 0.7853
## x1 0.23573 0.31281 0.754 0.4511
## x2 -0.52372 0.30367 -1.725 0.0846 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.12 on 499 degrees of freedom
## Residual deviance: 689.57 on 497 degrees of freedom
## AIC: 695.57
##
## Number of Fisher Scoring iterations: 3
Predictors \(X_1\) and \(X_2\) are not statistically significant predictors for the y variable at the level of significance \(\alpha\)=0.05. This coincides with the non-linear boundry represented in the plot.
#(d) Apply this model to the training data in order to obtain a predicted class label for each training observation. Plot the observations, colored according to the predicted class labels. The decision boundary should be linear.
lm.prob <- predict(lm.fit, newdata = datax, type = 'response')
lm.pred <- ifelse(lm.prob > 0.5, 1, 0)
data.pos<-datax[lm.pred == 1, ]
data.neg<-datax[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "green", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "blue", pch = 4)
The threshold of 0.5 creates a new linear boundary
#(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X12, X1 ×$ X_2,log( X_2$),and so forth).
lmx.fit<-glm(y~poly(x1,2)+log(x2)+I(x1*x2), data=datax, family='binomial')
## Warning in log(x2): NaNs produced
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(lmx.fit)
##
## Call:
## glm(formula = y ~ poly(x1, 2) + log(x2) + I(x1 * x2), family = "binomial",
## data = datax)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.50938 -0.08764 -0.01227 0.08100 1.64313
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -10.400 1.841 -5.650 1.61e-08 ***
## poly(x1, 2)1 -3.904 20.766 -0.188 0.851
## poly(x1, 2)2 94.416 16.435 5.745 9.20e-09 ***
## log(x2) -6.882 1.224 -5.621 1.90e-08 ***
## I(x1 * x2) 4.533 8.865 0.511 0.609
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 351.347 on 253 degrees of freedom
## Residual deviance: 76.659 on 249 degrees of freedom
## (246 observations deleted due to missingness)
## AIC: 86.659
##
## Number of Fisher Scoring iterations: 8
The new model using non-linear predictors resulted in a few predictors being statistically significant. The predictors that are statistically significant are {X_1}^2 and the log of X_2.
#(f) Apply this model to the training data in order to obtain a predicted class label for each training observation. Plot the observations, colored according to the predicted class labels. The decision boundary should be obviously non-linear. If it is not,then repeat (a)-(e) until you come up with an example in which the predicted class labels are obviously non-linear.
lmx.prob <- predict(lmx.fit, newdata = datax, type = 'response')
## Warning in log(x2): NaNs produced
lmx.pred <- ifelse(lmx.prob > 0.5, 1, 0)
data.pos = datax[lmx.pred == 1, ]
data.neg = datax[lmx.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
The new model resulted in a non-linear boundary but different the original non-linear boundary.
#(g) Fit a support vector classifier to the data with X1 and X2 as predictors. Obtain a class prediction for each training observation.Plot the observations, colored according to the predicted class labels.
library(e1071)
svm.fit<-svm(as.factor(y)~ x1+x2, data=datax, kernel='linear', cost=0.1)
svm.pred<-predict(svm.fit, newdata=datax)
data.pos = datax[svm.pred == 1, ]
data.neg = datax[svm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
The linear kernel creates a small linear boundary with a few values in
one of the boundaries but majority of values are classified into one
group.
#(h) Fit a SVM using a non-linear kernel to the data. Obtain a class prediction for each training observation. Plot the observations, colored according to the predicted class labels.
nonsvm.fit<-svm(as.factor(y)~ x1+x2, data=datax, gamma=1)
nonsvm.pred<-predict(nonsvm.fit, newdata=datax)
data.pos = datax[nonsvm.pred == 1, ]
data.neg = datax[nonsvm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
The predicted labels of the non-linear boundary is similiar to the
original decision boundary.
#(i) Comment on your results.
Initially, applying logistic regression with a linear kernel resulted in a decision boundary that was linear in nature. However, when using support vector machines (SVM) or logistic regression with non-linear predictors, we were able to generate similar non-linear boundaries that closely matched the true decision boundaries for this dataset.
##7
#In this problem, you will use support vector approaches in order to predict whether a given car gets high or low gas mileage based on the Auto data set.
#(a) Create a binary variable that takes on a 1 for cars with gas mileage above the median, and a 0 for cars with gas mileage below the median.
library(ISLR)
library(e1071)
attach(Auto)
gas.med<-median(mpg)
mpg01<-ifelse(mpg> gas.med,1,0)
Auto$mpglevel<-as.factor(mpg01)
set.seed(100)
tune.auto<-tune(svm, mpglevel ~ ., data=Auto, kernel='linear', ranges = list(cost=c(0.01,.1, 1, 10, 100)))
summary(tune.auto)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.01512821
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07391026 0.04398186
## 2 1e-01 0.05102564 0.03408666
## 3 1e+00 0.01512821 0.02421271
## 4 1e+01 0.02538462 0.02372507
## 5 1e+02 0.03564103 0.02125655
The cross validation error is most minimized at cost=1.
#(c) Now repeat (b), this time using SVMs with radial and polynomial basis kernels, with different values of gamma and degree and cost. Comment on your results.
set.seed(15)
auto.tune=tune(svm, mpglevel ~ ., data=Auto, kernel='polynomial', ranges = list(cost=c(0.01,.1, 1, 10, 100),degree= c(2,3,4,5)))
summary(auto.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 2
##
## - best performance: 0.2958333
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5458974 0.03582002
## 2 1e-01 2 0.5458974 0.03582002
## 3 1e+00 2 0.5458974 0.03582002
## 4 1e+01 2 0.5074359 0.06089646
## 5 1e+02 2 0.2958333 0.05351892
## 6 1e-02 3 0.5458974 0.03582002
## 7 1e-01 3 0.5458974 0.03582002
## 8 1e+00 3 0.5458974 0.03582002
## 9 1e+01 3 0.5458974 0.03582002
## 10 1e+02 3 0.3416026 0.08294367
## 11 1e-02 4 0.5458974 0.03582002
## 12 1e-01 4 0.5458974 0.03582002
## 13 1e+00 4 0.5458974 0.03582002
## 14 1e+01 4 0.5458974 0.03582002
## 15 1e+02 4 0.5458974 0.03582002
## 16 1e-02 5 0.5458974 0.03582002
## 17 1e-01 5 0.5458974 0.03582002
## 18 1e+00 5 0.5458974 0.03582002
## 19 1e+01 5 0.5458974 0.03582002
## 20 1e+02 5 0.5458974 0.03582002
auto.tuner=tune(svm, mpglevel ~ ., data=Auto, kernel='radial', ranges = list(cost=c(0.01,.1, 1, 10, 100),gamma= c(0.001,.01,.1,1,10)))
summary(auto.tuner)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 100 0.01
##
## - best performance: 0.01262821
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-02 1e-03 0.52403846 0.15933274
## 2 1e-01 1e-03 0.50352564 0.15808999
## 3 1e+00 1e-03 0.09410256 0.07444599
## 4 1e+01 1e-03 0.07371795 0.05504698
## 5 1e+02 1e-03 0.02794872 0.02216297
## 6 1e-02 1e-02 0.52153846 0.16674888
## 7 1e-01 1e-02 0.08897436 0.06845468
## 8 1e+00 1e-02 0.07115385 0.05414380
## 9 1e+01 1e-02 0.02794872 0.02524480
## 10 1e+02 1e-02 0.01262821 0.01778017
## 11 1e-02 1e-01 0.20166667 0.08964137
## 12 1e-01 1e-01 0.08134615 0.06266074
## 13 1e+00 1e-01 0.05076923 0.04450789
## 14 1e+01 1e-01 0.02544872 0.02689601
## 15 1e+02 1e-01 0.03314103 0.02424635
## 16 1e-02 1e+00 0.51903846 0.17420809
## 17 1e-01 1e+00 0.51903846 0.17420809
## 18 1e+00 1e+00 0.06115385 0.04029713
## 19 1e+01 1e+00 0.06371795 0.03456945
## 20 1e+02 1e+00 0.06371795 0.03456945
## 21 1e-02 1e+01 0.56403846 0.06078333
## 22 1e-01 1e+01 0.56403846 0.06078333
## 23 1e+00 1e+01 0.52583333 0.07372510
## 24 1e+01 1e+01 0.52076923 0.07579852
## 25 1e+02 1e+01 0.52076923 0.07579852
The lowest cross-validation error for SVM polynomial based kernel is obtained with cost =100 and degree =2 The lowest cross-validation error for SVM radial based kernel is obtained with cost = 100 and gamma=0.01
#(d) Make some plots to back up your assertions in (b) and (c).
svm.linear = svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 100,
degree = 2)
svm.radial = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 100, gamma = 0.01)
plotpairs = function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpglevel", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}
plotpairs(svm.linear)
plotpairs(svm.poly)
detach(Auto)
#8 #This problem involves the OJ data set which is part of the ISLR package.
#(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
library(ISLR)
attach(OJ)
set.seed(53)
train<-sample(dim(OJ)[1], 800)
train.OJ<-OJ[train,]
test.OJ<-OJ[-train,]
#(b) Fit a support vector classifier to the training data using cost=0.01, with Purchase as the response and the other variables as predictors. Use the summary() function to produce summary statistics, and describe the results obtained.
library(e1071)
svm.linearOJ<- svm(Purchase ~ ., kernel='linear', data=train.OJ, cost=0.01)
summary(svm.linearOJ)
##
## Call:
## svm(formula = Purchase ~ ., data = train.OJ, kernel = "linear", cost = 0.01)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 0.01
##
## Number of Support Vectors: 433
##
## ( 217 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The support vector classifer creates 444 support vectors out of the 433 observations available in the dataset. Citrus Hill and Minute Maid are evenly split amongst the support vectors with 217 and 216.
train.pred<-predict(svm.linearOJ, train.OJ)
table(train.OJ$Purchase, train.pred)
## train.pred
## CH MM
## CH 444 49
## MM 72 235
mean(train.pred != train.OJ$Purchase)
## [1] 0.15125
The training error rate is ~ 15.13%
test.pred<-predict(svm.linearOJ, test.OJ)
table(test.OJ$Purchase, test.pred)
## test.pred
## CH MM
## CH 140 20
## MM 35 75
mean(test.pred != test.OJ$Purchase)
## [1] 0.2037037
The test error rate is ~ 20.37%
#(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10
tune.OJ<-tune(svm, Purchase ~ ., data=train.OJ, kernel='linear', ranges=list(cost=10^seq(-2,1, by=.5)))
summary(tune.OJ)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.01
##
## - best performance: 0.155
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.15500 0.05075814
## 2 0.03162278 0.15625 0.05043216
## 3 0.10000000 0.15875 0.05337563
## 4 0.31622777 0.15875 0.04966904
## 5 1.00000000 0.16000 0.04923018
## 6 3.16227766 0.15625 0.04611655
## 7 10.00000000 0.15875 0.05205833
The tuning selected cost=.01 as the most optimal.
#(e) Compute the training and test error rates using this new value for cost.
newsvm.linearoj<-svm(Purchase ~ ., kernel='linear', data=train.OJ, cost=tune.OJ$best.parameters$cost)
train.pred<-predict(newsvm.linearoj, train.OJ)
table(train.OJ$Purchase, train.pred)
## train.pred
## CH MM
## CH 444 49
## MM 72 235
mean(train.pred != train.OJ$Purchase)
## [1] 0.15125
The training error has decreased with the use of the optimal cost to ~ 15.13%
test.pred<-predict(newsvm.linearoj, test.OJ)
table(test.OJ$Purchase, test.pred)
## test.pred
## CH MM
## CH 140 20
## MM 35 75
mean(test.pred != test.OJ$Purchase)
## [1] 0.2037037
Unlike the training error rate, the test error rate increased with the use of the optimal cost to ~ 20.37%.
#(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
svm.radialoj<-svm(Purchase~ ., kernel='radial', data=train.OJ )
summary(svm.radialoj)
##
## Call:
## svm(formula = Purchase ~ ., data = train.OJ, kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 370
##
## ( 189 181 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The radial basis kernel with default gamma creates 370 support vectors out of the 800 observations available in the dataset. Citrus Hill and Minute Maid are split into 189 and 181 vectors respectively.
train.pred<-predict(svm.radialoj, train.OJ)
table(train.OJ$Purchase, train.pred)
## train.pred
## CH MM
## CH 456 37
## MM 75 232
mean(train.pred != train.OJ$Purchase)
## [1] 0.14
The training error for radial basis kernel is ~ 14.00%.
test.pred<-predict(svm.radialoj, test.OJ)
table(test.OJ$Purchase, test.pred)
## test.pred
## CH MM
## CH 138 22
## MM 33 77
mean(test.pred != test.OJ$Purchase)
## [1] 0.2037037
he test error for the radial basis kernel is ~20.37%.
tunerad.OJ<-tune(svm, Purchase ~ ., data=train.OJ, kernel='radial', ranges=list(cost=10^seq(-2,1, by=.5)))
summary(tunerad.OJ)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.165
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.38375 0.05104804
## 2 0.03162278 0.36875 0.06045258
## 3 0.10000000 0.17500 0.04894725
## 4 0.31622777 0.17125 0.05337563
## 5 1.00000000 0.16500 0.05197489
## 6 3.16227766 0.16875 0.05008673
## 7 10.00000000 0.17750 0.04923018
The tuning selected cost=1 as the most optimal.
newsvm.radialoj<-svm(Purchase ~ ., kernel='radial', data=train.OJ, cost=tunerad.OJ$best.parameters$cost)
train.pred<-predict(newsvm.radialoj, train.OJ)
table(train.OJ$Purchase, train.pred)
## train.pred
## CH MM
## CH 456 37
## MM 75 232
mean(train.pred != train.OJ$Purchase)
## [1] 0.14
The training error for the basis radial kernel with the most optimal cost is ~14.00%; this is a slight increase than the default gamma.
test.pred<-predict(newsvm.radialoj, test.OJ)
table(test.OJ$Purchase, test.pred)
## test.pred
## CH MM
## CH 138 22
## MM 33 77
mean(test.pred != test.OJ$Purchase)
## [1] 0.2037037
The test error rate for the basis radial kernel with the most optimal cost is ~ 20.37%; this is an increase from the default gamma.
#(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
svm.polyoj<-svm(Purchase~ ., kernel='polynomial', data=train.OJ, degree=2 )
summary(svm.polyoj)
##
## Call:
## svm(formula = Purchase ~ ., data = train.OJ, kernel = "polynomial",
## degree = 2)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 1
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 450
##
## ( 229 221 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The polynomial kernel with two degrees creae 450 support vectors. 229 vectors belong to Citrus Hill, while 221 vectors belong to Minute Maid.
train.pred<-predict(svm.polyoj, train.OJ)
table(train.OJ$Purchase, train.pred)
## train.pred
## CH MM
## CH 461 32
## MM 113 194
mean(train.pred != train.OJ$Purchase)
## [1] 0.18125
The training error for the polynomial kernels with two degrees is ~18.13%
test.pred<-predict(svm.polyoj, test.OJ)
table(test.OJ$Purchase, test.pred)
## test.pred
## CH MM
## CH 147 13
## MM 40 70
mean(test.pred != test.OJ$Purchase)
## [1] 0.1962963
The test error for the polynomial kernels with two degrees is ~19.62%
tunepoly.OJ<-tune(svm, Purchase ~ ., data=train.OJ, kernel='polynomial', degree=2, ranges=list(cost=10^seq(-2,1, by=.5)))
summary(tunepoly.OJ)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.17375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.38250 0.05565269
## 2 0.03162278 0.35250 0.05062114
## 3 0.10000000 0.31375 0.05382908
## 4 0.31622777 0.20625 0.05111602
## 5 1.00000000 0.20375 0.05864500
## 6 3.16227766 0.18875 0.05219155
## 7 10.00000000 0.17375 0.04803428
The tuning selected cost=10 as the most optimal.
newsvm.polyoj<-svm(Purchase ~ ., kernel='polynomial', data=train.OJ, degree=2, cost=tunerad.OJ$best.parameters$cost)
train.pred<-predict(newsvm.polyoj, train.OJ)
table(train.OJ$Purchase, train.pred)
## train.pred
## CH MM
## CH 461 32
## MM 113 194
mean(train.pred != train.OJ$Purchase)
## [1] 0.18125
The training error for the polynomial kernel with the most optimal cost is ~18.13%; this is a significant reduction of error compared to the original polynomial kernel.
test.pred<-predict(newsvm.polyoj, test.OJ)
table(test.OJ$Purchase, test.pred)
## test.pred
## CH MM
## CH 147 13
## MM 40 70
mean(test.pred != test.OJ$Purchase)
## [1] 0.1962963
detach(OJ)
The test error for the polynomial kernel with the most optimal cost is ~19.63%; this is a significant reduction of error compared to the original polynomial kernel.
#(h) Overall, which approach seems to give the best results on this data?
#Overall the approach that give the best results on this data is basis radial kernel with the default gamma. This approach resulted in the lowest misclassification rate for both the training and test datasets