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:

x1 <- runif (500) - 0.5 x2 <- runif (500) - 0.5 y <- 1 * (x1^2 - x2^2 > 0)

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 X1 on the x-axis, and X2 on the yaxis.

plot(x1[y==0],x2[y==0],col="red",xlab="X1",ylab="X2")
points(x1[y==1],x2[y==1],col="blue")

(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.

dat=data.frame(x1 = x1, x2 = x2, y = as.factor(y))
glm.fit=glm(y~.,data=dat,family='binomial')

(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.prob=predict(glm.fit,newdata=dat,type='response')
glm.pred=ifelse(glm.prob>0.5,1,0)
plot(dat$x1,dat$x2,col=glm.pred+2)

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

glm.fit2=glm(y~poly(x1,2)+poly(x2,2),data=dat,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), family = "binomial", 
##     data = dat)
## 
## Deviance Residuals: 
##        Min          1Q      Median          3Q         Max  
## -1.079e-03  -2.000e-08  -2.000e-08   2.000e-08   1.297e-03  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)
## (Intercept)     -94.48    2963.78  -0.032    0.975
## poly(x1, 2)1   3442.52  104411.28   0.033    0.974
## poly(x1, 2)2  30110.74  858421.66   0.035    0.972
## poly(x2, 2)1    162.82   26961.99   0.006    0.995
## poly(x2, 2)2 -31383.76  895267.48  -0.035    0.972
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9218e+02  on 499  degrees of freedom
## Residual deviance: 4.2881e-06  on 495  degrees of freedom
## AIC: 10
## 
## 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.prob2=predict(glm.fit2,newdata=dat,type='response')
glm.pred2=ifelse(glm.prob2>0.5,1,0)
plot(dat$x1,dat$x2,col=glm.pred2+2)

(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.lin=svm(y~.,data=dat,kernel='linear',cost=0.01)
plot(svm.lin,dat)

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

svm2=svm(y~.,data=dat,kernel='radial',gamma=1)
plot(svm2,data=dat)

(i) Comment on your results.

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 Auto data set.

library(ISLR2)
attach(Auto)

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

mileage.median=median(Auto$mpg)
Auto$mb=ifelse(Auto$mpg > mileage.median, 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.

cost.grid=c(0.001,0.1,1,100)
set.seed(1)
tune.res=tune(svm,mpg~.-mpg,data=Auto,kernel='linear',ranges=list(cost=cost.grid))
summary(tune.res)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##   0.1
## 
## - best performance: 8.950531 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1 1e-03 15.593316   7.097943
## 2 1e-01  8.950531   4.661059
## 3 1e+00  9.619835   4.271469
## 4 1e+02 10.696932   5.095624

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

Cost and Gamma in radial kernel:

cost.grid=c(0.01,0.1,1,10,100)
gamma.grid=c(0.5,1,2,3,4)
tune.radial=tune(svm,mpg~.,data=Auto,kernel='radial',ranges=list(cost=cost.grid,gamma=gamma.grid))
summary(tune.radial)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##    10   0.5
## 
## - best performance: 8.84154 
## 
## - Detailed performance results:
##     cost gamma     error dispersion
## 1  1e-02   0.5 53.889639  12.813200
## 2  1e-01   0.5 20.783129   8.528583
## 3  1e+00   0.5  9.637913   4.363780
## 4  1e+01   0.5  8.841540   3.069269
## 5  1e+02   0.5  8.878976   3.014105
## 6  1e-02   1.0 61.148831  13.422393
## 7  1e-01   1.0 47.302839  12.035967
## 8  1e+00   1.0 21.396914   7.182358
## 9  1e+01   1.0 20.384189   5.921957
## 10 1e+02   1.0 20.384189   5.921957
## 11 1e-02   2.0 62.667246  13.411598
## 12 1e-01   2.0 60.921482  13.466680
## 13 1e+00   2.0 50.636987  11.396770
## 14 1e+01   2.0 49.359733   9.710761
## 15 1e+02   2.0 49.359733   9.710761
## 16 1e-02   3.0 62.781188  13.414861
## 17 1e-01   3.0 62.052634  13.544340
## 18 1e+00   3.0 57.222912  12.150480
## 19 1e+01   3.0 56.637765  10.366356
## 20 1e+02   3.0 56.637765  10.366356
## 21 1e-02   4.0 62.801126  13.413553
## 22 1e-01   4.0 62.258685  13.562284
## 23 1e+00   4.0 58.371929  12.266698
## 24 1e+01   4.0 57.888845  10.494682
## 25 1e+02   4.0 57.888845  10.494682

cost and degree in polynomial kernel

deg.grid=c(1,2,3,4)
tune.degree=tune(svm,mpg~.,data=Auto,kernel='polynomial', ranges=list(cost=cost.grid,degree=deg.grid))
summary(tune.degree)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##    10      1
## 
## - best performance: 9.006678 
## 
## - Detailed performance results:
##     cost degree     error dispersion
## 1  1e-02      1 57.758089  11.739685
## 2  1e-01      1 28.634338   9.354720
## 3  1e+00      1 11.042935   4.865596
## 4  1e+01      1  9.006678   4.158427
## 5  1e+02      1  9.029539   3.600240
## 6  1e-02      2 62.673629  11.685645
## 7  1e-01      2 62.589751  11.726243
## 8  1e+00      2 61.793551  12.189967
## 9  1e+01      2 58.174576  16.421170
## 10 1e+02      2 44.049899  14.153171
## 11 1e-02      3 62.678482  11.681058
## 12 1e-01      3 62.637712  11.679699
## 13 1e+00      3 62.231863  11.667875
## 14 1e+01      3 58.363548  11.700548
## 15 1e+02      3 38.491281  10.257053
## 16 1e-02      4 62.682946  11.681222
## 17 1e-01      4 62.682335  11.681318
## 18 1e+00      4 62.676224  11.682280
## 19 1e+01      4 62.615299  11.692104
## 20 1e+02      4 62.024315  11.809049

(d) Make some plots to back up your assertions in (b) and (c). Hint: In the lab, we used the plot() function for svm objects only in cases with p = 2. When p > 2, you can use the plot() function to create plots displaying pairs of variables at a time. Essentially, instead of typing

plot (svmfit , dat)

where svmfit contains your fitted model and dat is a data frame containing your data, you can type

plot (svmfit , dat , x1 ∼ x4)

in order to plot just the first and fourth variables. However, you must replace x1 and x4 with the correct variable names. To find out more, type ?plot.svm.

plot(tune.radial$best.model,Auto,mpg~horsepower)

Problem 8

This problem involves the OJ data set which is part of the ISLR2 package.

detach(Auto)
attach(OJ)

(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

set.seed(1)
data.train=sample(nrow(OJ),800)
train=OJ[data.train, ]
test=OJ[-data.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.

svc=svm(Purchase~.,data=train,kernel='linear',cost=0.01)
summary(svc)
## 
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "linear", cost = 0.01)
## 
## 
## 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

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

Training Error

train.pred=predict(svc,newdata=train)
table(predict=train.pred,truth=train$Purchase)
##        truth
## predict  CH  MM
##      CH 420  75
##      MM  65 240
(75+65)/800
## [1] 0.175

Training Error

test.pred=predict(svc,newdata=test)
table(predict=test.pred,truth=test$Purchase)
##        truth
## predict  CH  MM
##      CH 153  33
##      MM  15  69
(33+15)/800
## [1] 0.06

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

set.seed(1)
tune.svc=tune(svm,Purchase~.,data=OJ,kernel="linear",ranges=list(cost=c(0.01,0.1,1,10)))
summary(tune.svc)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.1626168 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1  0.01 0.1691589 0.04024604
## 2  0.10 0.1663551 0.03984617
## 3  1.00 0.1626168 0.03945456
## 4 10.00 0.1682243 0.03865942
summary(tune.svc$best.model)
## 
## Call:
## best.tune(method = svm, train.x = Purchase ~ ., data = OJ, ranges = list(cost = c(0.01, 
##     0.1, 1, 10)), kernel = "linear")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  1 
## 
## Number of Support Vectors:  442
## 
##  ( 221 221 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

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

train.pred=predict(tune.svc$best.model,newdata=train)
table(predict=train.pred,truth=train$Purchase)
##        truth
## predict  CH  MM
##      CH 424  69
##      MM  61 246
test.pred=predict(tune.svc$best.model,newdata=test)
table(predict=test.pred,truth=test$Purchase)
##        truth
## predict  CH  MM
##      CH 155  29
##      MM  13  73
(69+61)/800
## [1] 0.1625
(29+13)/18
## [1] 2.333333

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

tune.radial=tune(svm,Purchase~.,data=OJ,kernel="radial",ranges=list(cost=c(0.01,0.1,1, 10)))
summary(tune.radial)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.1728972 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1  0.01 0.3897196 0.05100860
## 2  0.10 0.1813084 0.02961960
## 3  1.00 0.1728972 0.02863672
## 4 10.00 0.1841121 0.03208874
summary(tune.radial$best.model)
## 
## Call:
## best.tune(method = svm, train.x = Purchase ~ ., data = OJ, ranges = list(cost = c(0.01, 
##     0.1, 1, 10)), kernel = "radial")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  1 
## 
## Number of Support Vectors:  485
## 
##  ( 245 240 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred=predict(tune.radial$best.model,newdata=train)
table(predict=train.pred,truth=train$Purchase)
##        truth
## predict  CH  MM
##      CH 442  77
##      MM  43 238
test.pred=predict(tune.radial$best.model,newdata=test)
table(predict=test.pred,truth=test$Purchase)
##        truth
## predict  CH  MM
##      CH 155  31
##      MM  13  71
(77+43)/800
## [1] 0.15
(31+13)/800
## [1] 0.055

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

tune.poly=tune(svm,Purchase~.,data=OJ,kernel="polynomial",degree=2,ranges=list(cost=c(0.01,0.1,1,10)))
summary(tune.poly)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##    10
## 
## - best performance: 0.1691589 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1  0.01 0.3691589 0.03447966
## 2  0.10 0.3028037 0.03717491
## 3  1.00 0.1953271 0.03564222
## 4 10.00 0.1691589 0.03339296
summary(tune.poly$best.model)
## 
## Call:
## best.tune(method = svm, train.x = Purchase ~ ., data = OJ, ranges = list(cost = c(0.01, 
##     0.1, 1, 10)), kernel = "polynomial", degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  10 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  450
## 
##  ( 230 220 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred=predict(tune.poly$best.model,newdata=train)
table(predict=train.pred,truth=train$Purchase)
##        truth
## predict  CH  MM
##      CH 442  74
##      MM  43 241
test.pred=predict(tune.poly$best.model,newdata=test)
table(predict=test.pred,truth=test$Purchase)
##        truth
## predict  CH  MM
##      CH 156  29
##      MM  12  73
(74+43)/800
## [1] 0.14625
(29+12)/800
## [1] 0.05125

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