Problem 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:

set.seed(1)
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 \(X_1\) on the x-axis, and \(X_2\) on the y-axis.

plot(x1, x2, col=ifelse(y, "red", "black"))

(c) Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.

glm.fit=glm(y~x1+x2, family="binomial")
summary(glm.fit)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = "binomial")
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.179  -1.139  -1.112   1.206   1.257  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.087260   0.089579  -0.974    0.330
## x1           0.196199   0.316864   0.619    0.536
## x2          -0.002854   0.305712  -0.009    0.993
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 692.18  on 499  degrees of freedom
## Residual deviance: 691.79  on 497  degrees of freedom
## AIC: 697.79
## 
## Number of Fisher Scoring iterations: 3

Neither variable is significant.

(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=data.frame(x1,x2))
plot(x1,x2,col=ifelse(glm.pred>0,"red","black"),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 \(X_1\) and \(X_2\) as predictors (e.g. \(X_1^2, X_1 × X_2 , log(X_2)\), and so forth).

glm.fit2=glm(y~poly(x1,2)+poly(x2,2)+I(x1*x2), family="binomial")
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm.fit2)
## 
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = "binomial")
## 
## Deviance Residuals: 
##        Min          1Q      Median          3Q         Max  
## -8.240e-04  -2.000e-08  -2.000e-08   2.000e-08   1.163e-03  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept)    -102.2     4302.0  -0.024    0.981
## poly(x1, 2)1   2715.3   141109.5   0.019    0.985
## poly(x1, 2)2  27218.5   842987.2   0.032    0.974
## poly(x2, 2)1   -279.7    97160.4  -0.003    0.998
## poly(x2, 2)2 -28693.0   875451.3  -0.033    0.974
## I(x1 * x2)     -206.4    41802.8  -0.005    0.996
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9218e+02  on 499  degrees of freedom
## Residual deviance: 3.5810e-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.pred2=predict(glm.fit2, data=data.frame(x1,x2))
plot(x1,x2,col=ifelse(glm.pred2>0,"red","black"),pch=ifelse(as.integer(glm.pred2>0) == y,1,4))

(g) Fit a support vector classifier to the data with \(X_1\) and \(X_2\) 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~x1+x2, data=data.frame(x1,x2,y=as.factor(y)), kernel="linear", cost=0.1)
svm.pred=predict(svm.fit,data.frame(x1,x2),type="response")
plot(x1,x2,col=ifelse(svm.pred!=0,"red","black"),pch=ifelse(as.integer(svm.pred!=0) == y,1,4))

(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.

svm.fit2=svm(y~x1+x2, data=data.frame(x1,x2,y=as.factor(y)), kernel="polynomial", degree=2)
svm.pred2=predict(svm.fit2,data.frame(x1,x2),type="response")
plot(x1,x2,col=ifelse(svm.pred2!=0,"red","black"),pch=ifelse(as.integer(svm.pred2!=0) == y,1,4))

(i) Comment on your results.

The non-linear SVM and non-linear logistic regression were both very effective at classifying the training data, where the linear versions struggled greatly.

Problem 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 Autodata 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(ISLR2)
attach(Auto)
Auto$mpglvl=ifelse(Auto$mpg>median(Auto$mpg),1,0)

(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. Note you will need to fit the classifier without the gas mileage variable to produce sensible results.

set.seed(1)
tune.auto=tune(svm,mpglvl~., data=Auto, kernel="linear",ranges=list(cost=c(0.01,0.1,1,10,100)))
summary(tune.auto)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.07424404 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.08379323 0.02362659
## 2 1e-01 0.07898470 0.02693908
## 3 1e+00 0.07424404 0.02693697
## 4 1e+01 0.08874314 0.03324316
## 5 1e+02 0.11389623 0.03717388

A cost of 1 seems to perform best.

(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.

tune.auto.poly=tune(svm,mpglvl~., data=Auto, kernel="polynomial", ranges=list(cost=c(0.01,0.1,1,10,100),degree=c(2,3,4,5)))
summary(tune.auto.poly)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##   100      3
## 
## - best performance: 0.212276 
## 
## - Detailed performance results:
##     cost degree     error dispersion
## 1  1e-02      2 0.5439966 0.05714637
## 2  1e-01      2 0.5423710 0.05735016
## 3  1e+00      2 0.5260761 0.05963162
## 4  1e+01      2 0.3970275 0.07660571
## 5  1e+02      2 0.2463942 0.07054428
## 6  1e-02      3 0.5440907 0.05713281
## 7  1e-01      3 0.5433474 0.05720586
## 8  1e+00      3 0.5358104 0.05796303
## 9  1e+01      3 0.4652288 0.06531582
## 10 1e+02      3 0.2122760 0.06052159
## 11 1e-02      4 0.5441723 0.05712482
## 12 1e-01      4 0.5441633 0.05712598
## 13 1e+00      4 0.5440734 0.05713754
## 14 1e+01      4 0.5431525 0.05727081
## 15 1e+02      4 0.5338836 0.05860305
## 16 1e-02      5 0.5441731 0.05712475
## 17 1e-01      5 0.5441714 0.05712519
## 18 1e+00      5 0.5441545 0.05712965
## 19 1e+01      5 0.5439858 0.05717423
## 20 1e+02      5 0.5422654 0.05764462
tune.auto.rad=tune(svm,mpglvl~., data=Auto, kernel="radial", ranges=list(cost=c(0.01,0.1,1,10,100),gamma=c(0.001,0.01,0.1,1,10)))
summary(tune.auto.rad)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##    10   0.1
## 
## - best performance: 0.03771976 
## 
## - Detailed performance results:
##     cost gamma      error  dispersion
## 1  1e-02 1e-03 0.49925078 0.070252933
## 2  1e-01 1e-03 0.23479047 0.044826973
## 3  1e+00 1e-03 0.08870040 0.014944737
## 4  1e+01 1e-03 0.08080910 0.021814968
## 5  1e+02 1e-03 0.07489968 0.022623805
## 6  1e-02 1e-02 0.28646656 0.048838834
## 7  1e-01 1e-02 0.08411439 0.014247071
## 8  1e+00 1e-02 0.07119793 0.019941318
## 9  1e+01 1e-02 0.06102335 0.017738964
## 10 1e+02 1e-02 0.05438431 0.010032019
## 11 1e-02 1e-01 0.14193120 0.027332367
## 12 1e-01 1e-01 0.05650568 0.016547521
## 13 1e+00 1e-01 0.04561577 0.014387831
## 14 1e+01 1e-01 0.03771976 0.009249431
## 15 1e+02 1e-01 0.04450103 0.016536123
## 16 1e-02 1e+00 0.51307748 0.072329389
## 17 1e-01 1e+00 0.32590832 0.063478211
## 18 1e+00 1e+00 0.09603941 0.012412616
## 19 1e+01 1e+00 0.09804621 0.014592129
## 20 1e+02 1e+00 0.09804621 0.014592129
## 21 1e-02 1e+01 0.53225520 0.072237908
## 22 1e-01 1e+01 0.48530322 0.067872785
## 23 1e+00 1e+01 0.24656110 0.004915056
## 24 1e+01 1e+01 0.24656109 0.004915177
## 25 1e+02 1e+01 0.24656109 0.004915177

For polynomial, the best degree is 3 at cost 100. For radial, the best gamma is 0.1 at cost 10.

(d) Make some plots to back up your assertions in (b) and (c).

svm.lin=svm(mpglvl~., data=Auto, kernel="linear", cost=1)
svm.poly=svm(mpglvl~., data=Auto, kernel="polynomial", cost=100, degree=3)
svm.rad=svm(mpglvl~., data=Auto, kernel="radial", cost=10, gamma=0.1)

plotpairs=function(fit){
  for(name in names(Auto)[!(names(Auto)) %in% c("mpg","name","mpglvl")]){
    plot(fit,Auto,as.formula(paste("mpg~",name,sep="")))
  }
}
plotpairs(svm.lin)
plotpairs(svm.poly)
plotpairs(svm.rad)

detach(Auto)

Problem 8

This problem involves the OJ data set which is part of the ISLR2 package.
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

set.seed(1)
attach(OJ)

train=sample(nrow(OJ),800)
test=-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:  435
## 
##  ( 219 216 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

With 435 support vectors from the 800 training points, we get 219 in CH and 215 in MM.

(c) What are the training and test error rates?

train.pred=predict(svm.fit, OJ[train,])
mean(train.pred!=OJ[train,"Purchase"])
## [1] 0.175
test.pred=predict(svm.fit, OJ[test,])
mean(test.pred!=OJ[test,"Purchase"])
## [1] 0.1777778

We get a training error rate of 17.5% and a test error rate of 17.8%.

(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.

set.seed(1)
tune.OJ=tune(svm,Purchase~.,data=OJ[train,],ranges=list(cost=c(0.1,0.2,0.5,0.8,1,2,3,5,8,10)),kernel="linear")
summary(tune.OJ)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##   0.5
## 
## - best performance: 0.16875 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1   0.1 0.17250 0.03162278
## 2   0.2 0.17125 0.02829041
## 3   0.5 0.16875 0.02651650
## 4   0.8 0.16875 0.02779513
## 5   1.0 0.17500 0.02946278
## 6   2.0 0.17250 0.02874698
## 7   3.0 0.16875 0.03019037
## 8   5.0 0.17250 0.03162278
## 9   8.0 0.17375 0.03197764
## 10 10.0 0.17375 0.03197764

(e) Compute the training and test error rates using this new value for cost.

svm.pred=predict(tune.OJ$best.model,OJ[train,])
mean(svm.pred!=OJ[train,"Purchase"])
## [1] 0.165
svm.test.pred=predict(tune.OJ$best.model,OJ[test,])
mean(svm.test.pred!=OJ[test,"Purchase"])
## [1] 0.1555556

We get a training error rate of 16.5% and a test error rate of 15.6%.

(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.

svm.fit.rad=svm(Purchase~.,data=OJ,subset=train,cost=0.01,kernel="radial")
summary(svm.fit.rad)
## 
## 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:  634
## 
##  ( 319 315 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred.rad=predict(svm.fit.rad, OJ[train,])
mean(train.pred.rad!=OJ[train,"Purchase"])
## [1] 0.39375
test.pred.rad=predict(svm.fit.rad, OJ[test,])
mean(test.pred.rad!=OJ[test,"Purchase"])
## [1] 0.3777778
set.seed(1)
tune.OJ.rad=tune(svm,Purchase~.,data=OJ[train,],ranges=list(cost=c(0.1,0.2,0.5,0.8,1,2,3,5,8,10)),kernel="radial")
summary(tune.OJ.rad)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##   0.5
## 
## - best performance: 0.1675 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1   0.1 0.18625 0.02853482
## 2   0.2 0.18250 0.03238227
## 3   0.5 0.16750 0.02443813
## 4   0.8 0.16875 0.02517301
## 5   1.0 0.17125 0.02128673
## 6   2.0 0.17750 0.02188988
## 7   3.0 0.17625 0.02239947
## 8   5.0 0.18000 0.02220485
## 9   8.0 0.18250 0.02648375
## 10 10.0 0.18625 0.02853482
svm.pred.rad=predict(tune.OJ.rad$best.model,OJ[train,])
mean(svm.pred.rad!=OJ[train,"Purchase"])
## [1] 0.1475
svm.test.pred.rad=predict(tune.OJ.rad$best.model,OJ[test,])
mean(svm.test.pred.rad!=OJ[test,"Purchase"])
## [1] 0.1777778

(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.

svm.fit.poly=svm(Purchase~.,data=OJ,subset=train,cost=0.01,degree=2,kernel="polynomial")
summary(svm.fit.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ, cost = 0.01, degree = 2, kernel = "polynomial", 
##     subset = train)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  0.01 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  636
## 
##  ( 321 315 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred.poly=predict(svm.fit.poly, OJ[train,])
mean(train.pred.poly!=OJ[train,"Purchase"])
## [1] 0.3725
test.pred.poly=predict(svm.fit.poly, OJ[test,])
mean(test.pred.poly!=OJ[test,"Purchase"])
## [1] 0.3666667
set.seed(1)
tune.OJ.poly=tune(svm,Purchase~.,data=OJ[train,],ranges=list(cost=c(0.1,0.2,0.5,0.8,1,2,3,5,8,10)),degree=2,kernel="polynomial")
summary(tune.OJ.poly)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     3
## 
## - best performance: 0.17625 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1   0.1 0.32125 0.05001736
## 2   0.2 0.22625 0.03557562
## 3   0.5 0.20625 0.04050463
## 4   0.8 0.20375 0.04251225
## 5   1.0 0.20250 0.04116363
## 6   2.0 0.18125 0.04177070
## 7   3.0 0.17625 0.03793727
## 8   5.0 0.18250 0.03496029
## 9   8.0 0.18000 0.03395258
## 10 10.0 0.18125 0.02779513
svm.pred.poly=predict(tune.OJ.poly$best.model,OJ[train,])
mean(svm.pred.poly!=OJ[train,"Purchase"])
## [1] 0.15375
svm.test.pred.poly=predict(tune.OJ.poly$best.model,OJ[test,])
mean(svm.test.pred.poly!=OJ[test,"Purchase"])
## [1] 0.2037037

(h) Overall, which approach seems to give the best results on this data?

The linear SVM appears to perform best on this data as it has the lowest test error rate when tuned to the best choice of cost.