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(1234)
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", 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.

lm.fit = glm(y ~ x1 + x2, family = binomial)
summary(lm.fit)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.161  -1.107  -1.072   1.243   1.308  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)  
## (Intercept) -0.16814    0.08985  -1.871   0.0613 .
## x1           0.15254    0.31736   0.481   0.6308  
## x2          -0.12672    0.30048  -0.422   0.6732  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 689.62  on 499  degrees of freedom
## Residual deviance: 689.21  on 497  degrees of freedom
## AIC: 695.21
## 
## Number of Fisher Scoring iterations: 3

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.

data = data.frame(x1 = x1, x2 = x2, y = y)
lm.prob = predict(lm.fit, data, type = "response")
lm.pred = ifelse(lm.prob > 0.47, 1, 0)
data.pos = data[lm.pred == 1, ]
data.neg = data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "green", pch = 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).

lm.fit = glm(y ~ x1**3 + x2**2 + I(x1 * x2) , data = data, family = binomial)

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

lm.prob = predict(lm.fit, data, type = "response")
lm.pred = ifelse(lm.prob > 0.5, 1, 0)
data.pos = data[lm.pred == 1, ]
data.neg = data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "green", pch = 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)
## Warning: package 'e1071' was built under R version 4.0.3
svm.fit = svm(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.1)
svm.pred = predict(svm.fit, data)

plot(svm.fit, data)

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.

set.seed(1234)
svm.fit = svm(as.factor(y) ~ x1 + x2, data,  gamma = 1)
svm.pred = predict(svm.fit, data)
data.pos = data[svm.pred == 1, ]
data.neg = data[svm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "green", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)

  1. Comment on your results. This data is definetly not linear therefore SVM was demostrated its usefullness on it.

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)
## Warning: package 'ISLR' was built under R version 4.0.3
gas.med = median(Auto$mpg)
new.var = ifelse(Auto$mpg > gas.med, 1, 0)
Auto$mpglevel = as.factor(new.var)

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.

tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 
    0.1, 1, 5, 10, 100)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.01525641 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.07391026 0.04070168
## 2 1e-01 0.04583333 0.03106348
## 3 1e+00 0.01525641 0.01784872
## 4 5e+00 0.02038462 0.02019157
## 5 1e+01 0.02807692 0.03071101
## 6 1e+02 0.03833333 0.03260322

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.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1, 
    1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##   0.1      3
## 
## - best performance: 0.5387179 
## 
## - Detailed performance results:
##    cost degree     error dispersion
## 1   0.1      2 0.5412179 0.07096466
## 2   1.0      2 0.5412179 0.07096466
## 3   5.0      2 0.5412179 0.07096466
## 4  10.0      2 0.5437821 0.09030050
## 5   0.1      3 0.5387179 0.07849079
## 6   1.0      3 0.5387179 0.07849079
## 7   5.0      3 0.5387179 0.07849079
## 8  10.0      3 0.5387179 0.07849079
## 9   0.1      4 0.5562179 0.03020018
## 10  1.0      4 0.5562179 0.03020018
## 11  5.0      4 0.5562179 0.03020018
## 12 10.0      4 0.5562179 0.03020018
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.1, 
    1, 5, 10), gamma = c(0.01, 0.1, 1, 5, 10, 100)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##    10   0.1
## 
## - best performance: 0.03070513 
## 
## - Detailed performance results:
##    cost gamma      error dispersion
## 1   0.1 1e-02 0.08185897 0.04971433
## 2   1.0 1e-02 0.07160256 0.04663610
## 3   5.0 1e-02 0.05371795 0.04091175
## 4  10.0 1e-02 0.03326923 0.04019418
## 5   0.1 1e-01 0.07929487 0.04767788
## 6   1.0 1e-01 0.05628205 0.04154079
## 7   5.0 1e-01 0.03583333 0.03668306
## 8  10.0 1e-01 0.03070513 0.03784941
## 9   0.1 1e+00 0.49083333 0.15659348
## 10  1.0 1e+00 0.05628205 0.05101229
## 11  5.0 1e+00 0.06397436 0.04235062
## 12 10.0 1e+00 0.06397436 0.04235062
## 13  0.1 5e+00 0.52833333 0.04298729
## 14  1.0 5e+00 0.48993590 0.04925670
## 15  5.0 5e+00 0.48737179 0.05007669
## 16 10.0 5e+00 0.48737179 0.05007669
## 17  0.1 1e+01 0.53333333 0.03081816
## 18  1.0 1e+01 0.50275641 0.04882846
## 19  5.0 1e+01 0.50275641 0.04882846
## 20 10.0 1e+01 0.50275641 0.04882846
## 21  0.1 1e+02 0.53583333 0.02623328
## 22  1.0 1e+02 0.53583333 0.02623328
## 23  5.0 1e+02 0.53583333 0.02623328
## 24 10.0 1e+02 0.53583333 0.02623328

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

svm.linear = svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 10, 
    degree = 2)
svm.radial = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 10, 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)

plotpairs(svm.radial)

8

This problem involves the OJ data set which is part of the ISLR package. 372 9. Support Vector Machines

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

library(ISLR)
attach(OJ)
train = sample(dim(OJ)[1], 800)
OJ.train= OJ[train, ]
OJ.test= 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.linear = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = 0.01)
summary(svm.linear)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "linear", cost = 0.01)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  0.01 
## 
## Number of Support Vectors:  417
## 
##  ( 210 207 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

C. What are the training and test error rates? .835 calculated from matrix below..

train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 453  52
##   MM  69 226
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 130  18
##   MM  41  81

.8222 from matrix above

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

tune.out = tune(svm, Purchase ~ ., data = OJ.train, kernel = "linear", ranges = list(cost = 10^seq(-2, 
    1, by = 0.25)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##    10
## 
## - best performance: 0.1525 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.15375 0.02128673
## 2   0.01778279 0.15375 0.02433134
## 3   0.03162278 0.15625 0.02841288
## 4   0.05623413 0.15625 0.03076005
## 5   0.10000000 0.15625 0.03186887
## 6   0.17782794 0.15875 0.03821086
## 7   0.31622777 0.15875 0.03821086
## 8   0.56234133 0.15750 0.03641962
## 9   1.00000000 0.15875 0.03821086
## 10  1.77827941 0.15625 0.03498512
## 11  3.16227766 0.15375 0.03283481
## 12  5.62341325 0.15375 0.03283481
## 13 10.00000000 0.15250 0.03322900

E. Compute the training and test error rates using this new value for cost.

svm.linear = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = tune.out$best.parameters$cost)
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 451  54
##   MM  65 230

= .8425

test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 130  18
##   MM  42  80

= .8222

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

svm.radial = svm(Purchase ~ ., data = OJ.train, kernel = "radial")
summary(svm.radial)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "radial")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  1 
## 
## Number of Support Vectors:  350
## 
##  ( 179 171 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 464  41
##   MM  67 228

= .8425

tune.out = tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list(cost = 10^seq(-2, 
    1, by = 0.25)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.1475 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.36875 0.07822910
## 2   0.01778279 0.36875 0.07822910
## 3   0.03162278 0.36500 0.08494279
## 4   0.05623413 0.20000 0.05400617
## 5   0.10000000 0.16125 0.05152197
## 6   0.17782794 0.16250 0.05464532
## 7   0.31622777 0.15875 0.05529278
## 8   0.56234133 0.15250 0.05916080
## 9   1.00000000 0.14750 0.05583955
## 10  1.77827941 0.15625 0.05440652
## 11  3.16227766 0.16375 0.04803428
## 12  5.62341325 0.16750 0.05109903
## 13 10.00000000 0.17250 0.05552777
svm.radial = svm(Purchase ~ ., data = OJ.train, kernel = "radial", cost = tune.out$best.parameters$cost)
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 464  41
##   MM  67 228

= .855

H. Overall, which approach seems to give the best results on this data? The best result seen was in the last model at .855 . This suggest that the SVM with polynomial kernel is best. It is worth noting that when using the tune function, we also say an increase in performance once we used the optimal cost. then taking it a step further in part G had the best result.