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*(x1^2-x2^2 > 0 )
(b) Plot the observations, colored according to their class labels. Your plot should display X1 on the x-axis, and X2 on the yaxis.
plot(x1,x2,col=ifelse(y,'green','blue'))
(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
library(tidyverse)
glm.fit=glm(y~. ,family='binomial', data=data.frame(x1,x2,y))
glm.fit
##
## Call: glm(formula = y ~ ., family = "binomial", data = data.frame(x1,
## x2, y))
##
## Coefficients:
## (Intercept) x1 x2
## 0.02799 -0.02328 -0.64130
##
## Degrees of Freedom: 499 Total (i.e. Null); 497 Residual
## Null Deviance: 693.1
## Residual Deviance: 688.6 AIC: 694.6
(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
glm.pred=predict(glm.fit,data.frame(x1,x2))
plot(x1,x2,col=ifelse(glm.pred>0,'green','blue'),pch=ifelse(as.integer(glm.pred>0) == y,1,4))
(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X2 1 , X1×X2, log(X2), and so forth).
logitnl.fit = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = "binomial")
summary(logitnl.fit)
##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = "binomial")
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.478e-03 -2.000e-08 2.000e-08 2.000e-08 1.824e-03
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -38.65 72076.03 -0.001 1.000
## poly(x1, 2)1 752.19 830354.98 0.001 0.999
## poly(x1, 2)2 40822.66 1427882.80 0.029 0.977
## poly(x2, 2)1 -3877.08 780686.62 -0.005 0.996
## poly(x2, 2)2 -39990.93 1021164.85 -0.039 0.969
## I(x1 * x2) 170.81 853432.31 0.000 1.000
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9308e+02 on 499 degrees of freedom
## Residual deviance: 6.8765e-06 on 494 degrees of freedom
## AIC: 12
##
## Number of Fisher Scoring iterations: 25
(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.
glm.pred=predict(logitnl.fit,data.frame(x1,x2)) # returns the log-odds.
plot(x1,x2,col=ifelse(glm.pred>0,'blue','green'),pch=ifelse(as.integer(glm.pred>0) == y,1,4))
(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(y~.,data=data.frame(x1,x2,y=as.factor(y)),kernel='linear')
svm.pred=predict(svm.fit,data.frame(x1,x2),type='response')
plot(x1,x2,col=ifelse(svm.pred!=0,'green','blue'),pch=ifelse(svm.pred == y,1,4))
(i) Comment on your results.
from the results above we can conclude that the poly logit model performs better than svm with a poly Kernel
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.
library(ISLR)
(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
Auto$mpg=ifelse(Auto$mpg>median(Auto$mpg),1,0)
table(Auto$mpg)
##
## 0 1
## 196 196
(b) Fit a support vector classifier to the data with various values of cost, in order to predict whether a car gets high or low gas mileage. Report the cross-validation errors associated with different values of this parameter. Comment on your results.
library(e1071)
costs=data.frame(cost=seq(0.05,100,length.out = 15))
svm.tune=tune(svm,mpg~.,data=Auto,ranges=costs,kernel='linear')
svm.tune
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 7.189286
##
## - best performance: 0.1033537
plot(svm.tune$performance[,c(1,2)],type='l')
(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.
dat=data.frame(cost=seq(0.05,100,length.out = 5),degree=seq(1,100,length.out = 5))
svm.fit=tune(svm,mpg~.,data=Auto,ranges=dat,kernel='polynomial')
svm.fit
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 1
##
## - best performance: 0.09644461
(d) Make some plots to back up your assertions in (b) and (c).
plot(svm.fit)
This problem involves the OJ data set which is part of the ISLR package
library(ISLR)
library(e1071)
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(20)
train=sample(1:1070,800)
test=(1:1070)[-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.
svm.fit=svm(Purchase~.,data=OJ,subset=train,cost=0.01,kernel='linear')
summary(svm.fit)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ, cost = 0.01, kernel = "linear",
## subset = train)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 0.01
##
## Number of Support Vectors: 444
##
## ( 222 222 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
from our results we can see that 444 observations are used as support vectors
(c) What are the training and test error rates?
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
svm.tune=tune(svm,Purchase~.,data=OJ[train,],ranges=data.frame(cost=seq(0.01,10,25)),kernel='linear')
summary(svm.tune)
##
## Error estimation of 'svm' using 10-fold cross validation: 0.175
(e) Compute the training and test error rates using this new value for cost.
svm.pred=predict(svm.tune$best.model,OJ[train,])
mean(OJ$Purchase[train] != svm.pred)
## [1] 0.16625
svm.pred=predict(svm.tune$best.model,OJ[test,])
mean(OJ$Purchase[test] != svm.pred)
## [1] 0.162963
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
svm.fit=svm(Purchase~.,data=OJ,subset=train,cost=0.01,kernel='radial')
summary(svm.fit)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ, cost = 0.01, kernel = "radial",
## subset = train)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 0.01
##
## Number of Support Vectors: 630
##
## ( 316 314 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
svm.pred=predict(svm.fit,OJ[train,])
mean(OJ$Purchase[train] != svm.pred)
## [1] 0.3925
svm.pred=predict(svm.fit,OJ[test,])
mean(OJ$Purchase[test] != svm.pred)
## [1] 0.3814815
svm.tune=tune(svm,Purchase~.,data=OJ[train,],ranges=data.frame(cost=seq(0.01,10,25)))
summary(svm.tune)
##
## Error estimation of 'svm' using 10-fold cross validation: 0.3925
svm.pred=predict(svm.tune$best.model,OJ[train,])
mean(OJ$Purchase[train] != svm.pred)
## [1] 0.3925
svm.pred=predict(svm.tune$best.model,OJ[test,])
mean(OJ$Purchase[test] != svm.pred)
## [1] 0.3814815
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
svm.fit=svm(Purchase~.,data=OJ,subset=train,cost=0.01,kernel='polynomial')
summary(svm.fit)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ, cost = 0.01, kernel = "polynomial",
## subset = train)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 0.01
## degree: 3
## coef.0: 0
##
## Number of Support Vectors: 621
##
## ( 313 308 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
svm.pred=predict(svm.fit,OJ[train,])
mean(OJ$Purchase[train] != svm.pred)
## [1] 0.3725
svm.pred=predict(svm.fit,OJ[test,])
mean(OJ$Purchase[test] != svm.pred)
## [1] 0.3592593
svm.tune=tune(svm,Purchase~.,data=OJ[train,],ranges=data.frame(cost=seq(0.01,10,25)),kernel='polynomial')
summary(svm.tune)
##
## Error estimation of 'svm' using 10-fold cross validation: 0.3725
svm.pred=predict(svm.tune$best.model,OJ[train,])
mean(OJ$Purchase[train] != svm.pred)
## [1] 0.3725
svm.pred=predict(svm.tune$best.model,OJ[test,])
mean(OJ$Purchase[test] != svm.pred)
## [1] 0.3592593
(h) Overall, which approach seems to give the best results on this data?
The approach that provides the best results on this data seems to be the Linear SVM