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.

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.

plot(x1, x2, col = (3-y))

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

log.fit <- glm(y ~ x1 + x2, 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.

data <- data.frame(x1 = x1, x2 = x2, y = y)
probs <- predict(log.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.5] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1))
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0))

(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors

log_nl.fit <- 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

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

probs <- predict(log_nl.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.5] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1))
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0))

(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

data$y <- as.factor(data$y)
library(e1071)
## Warning: package 'e1071' was built under R version 4.1.2
svmfit=svm(y~., data=data, kernel="linear",  gamma=1, cost=1)
plot(svmfit, 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.

svmfit=svm(y~., data=data, kernel="radial",  gamma=1, cost=1)
plot(svmfit, data)

(i) Comment on your results.

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)
mpg.var <- ifelse(Auto$mpg > median(Auto$mpg), 1, 0)
Auto$mpg <- as.factor(mpg.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, mpg ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100, 1000)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##  0.01
## 
## - best performance: 0.08679487 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.08679487 0.04867313
## 2 1e-01 0.08942308 0.04889872
## 3 1e+00 0.10198718 0.05097706
## 4 5e+00 0.10698718 0.05330111
## 5 1e+01 0.10705128 0.06351583
## 6 1e+02 0.10961538 0.05105094
## 7 1e+03 0.11217949 0.06494039

Looks like the error on the cost value 0.01 does the 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.out <- tune(svm, mpg ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), gamma = c(0.5, 1, 5, 10, 100)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##     5     1
## 
## - best performance: 0.07391026 
## 
## - Detailed performance results:
##     cost gamma      error dispersion
## 1  1e-02   0.5 0.54070513 0.03076812
## 2  1e-01   0.5 0.08666667 0.04364606
## 3  1e+00   0.5 0.07653846 0.02949678
## 4  5e+00   0.5 0.07397436 0.02819088
## 5  1e+01   0.5 0.08160256 0.03573688
## 6  1e+02   0.5 0.08673077 0.03456265
## 7  1e-02   1.0 0.54070513 0.03076812
## 8  1e-01   1.0 0.54070513 0.03076812
## 9  1e+00   1.0 0.07391026 0.04228832
## 10 5e+00   1.0 0.07391026 0.03693807
## 11 1e+01   1.0 0.07391026 0.03693807
## 12 1e+02   1.0 0.07391026 0.03693807
## 13 1e-02   5.0 0.54070513 0.03076812
## 14 1e-01   5.0 0.54070513 0.03076812
## 15 1e+00   5.0 0.46666667 0.07001247
## 16 5e+00   5.0 0.46666667 0.06680896
## 17 1e+01   5.0 0.46666667 0.06680896
## 18 1e+02   5.0 0.46666667 0.06680896
## 19 1e-02  10.0 0.54070513 0.03076812
## 20 1e-01  10.0 0.54070513 0.03076812
## 21 1e+00  10.0 0.49987179 0.05092898
## 22 5e+00  10.0 0.49730769 0.05499122
## 23 1e+01  10.0 0.49730769 0.05499122
## 24 1e+02  10.0 0.49730769 0.05499122
## 25 1e-02 100.0 0.54070513 0.03076812
## 26 1e-01 100.0 0.54070513 0.03076812
## 27 1e+00 100.0 0.54070513 0.03076812
## 28 5e+00 100.0 0.54070513 0.03076812
## 29 1e+01 100.0 0.54070513 0.03076812
## 30 1e+02 100.0 0.54070513 0.03076812
tune.out <- tune(svm, mpg ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), degree = c(1,2,3)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##   100      1
## 
## - best performance: 0.08705128 
## 
## - Detailed performance results:
##     cost degree      error dispersion
## 1  1e-02      1 0.56910256 0.03113623
## 2  1e-01      1 0.28576923 0.11269167
## 3  1e+00      1 0.10730769 0.04832576
## 4  5e+00      1 0.08961538 0.06661789
## 5  1e+01      1 0.08961538 0.06983016
## 6  1e+02      1 0.08705128 0.06317910
## 7  1e-02      2 0.56910256 0.03113623
## 8  1e-01      2 0.56910256 0.03113623
## 9  1e+00      2 0.56910256 0.03113623
## 10 5e+00      2 0.56910256 0.03113623
## 11 1e+01      2 0.55897436 0.03735346
## 12 1e+02      2 0.31397436 0.10024160
## 13 1e-02      3 0.56910256 0.03113623
## 14 1e-01      3 0.56910256 0.03113623
## 15 1e+00      3 0.56910256 0.03113623
## 16 5e+00      3 0.56910256 0.03113623
## 17 1e+01      3 0.56910256 0.03113623
## 18 1e+02      3 0.40294872 0.11585855

For the radial kernel, the best performance has a cost of 5 and a gamma of .5. For the polynomial kernel, the best performance has a cost of 100 and degree of 1.
(d) Make some plots to back up your assertions in (b) and (c).
### 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.

train <- sample(nrow(OJ), 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.

svm.fit <- svm(Purchase ~ ., data = OJ.train, kernel = "linear", cost = 0.01)
summary(svm.fit)
## 
## 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:  431
## 
##  ( 216 215 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

There are 431 support vectors and 216 of them are for CH and the others are for MM.
(c) What are the training and test error rates?

preds.train <- predict(svm.fit, OJ.train)
table(OJ.train$Purchase, preds.train)
##     preds.train
##       CH  MM
##   CH 423  64
##   MM  68 245
(68+64)/800
## [1] 0.165
preds.test <- predict(svm.fit, OJ.test)
table(OJ.test$Purchase, preds.test)
##     preds.test
##       CH  MM
##   CH 144  22
##   MM  24  80
(22+24)/270
## [1] 0.1703704

(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 = c(0.01, 0.1, 1, 5, 10)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     5
## 
## - best performance: 0.16625 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.17125 0.03910900
## 2  0.10 0.16750 0.04377975
## 3  1.00 0.16875 0.04497299
## 4  5.00 0.16625 0.03866254
## 5 10.00 0.16750 0.04048319

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

svm.fit <- svm(Purchase ~ ., data = OJ.train, kernel = "linear", cost = 5)
preds.train <- predict(svm.fit, OJ.train)
table(OJ.train$Purchase, preds.train)
##     preds.train
##       CH  MM
##   CH 428  59
##   MM  70 243
(70+59)/800
## [1] 0.16125
preds.test <- predict(svm.fit, OJ.test)
table(OJ.test$Purchase, preds.test)
##     preds.test
##       CH  MM
##   CH 148  18
##   MM  24  80
(24/18)/270
## [1] 0.004938272

(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.train, kernel = "radial", cost = 1)
preds.train <- predict(svm.fit, OJ.train)
table(OJ.train$Purchase, preds.train)
##     preds.train
##       CH  MM
##   CH 443  44
##   MM  71 242
(44+71)/800
## [1] 0.14375
preds.test <- predict(svm.fit, OJ.test)
table(OJ.test$Purchase, preds.test)
##     preds.test
##       CH  MM
##   CH 148  18
##   MM  27  77
(27+18)/270
## [1] 0.1666667
tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.1725 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.39125 0.06615691
## 2  0.10 0.18625 0.02791978
## 3  1.00 0.17250 0.03322900
## 4  5.00 0.18125 0.03019037
## 5 10.00 0.18625 0.03087272

Well, luckily for me, the optimal cost is already 1, so I’m going to skip the other steps.
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.

svm.fit <- svm(Purchase ~ ., data = OJ.train, kernel = "polynomial", cost = 1, degree = 2)
preds.train <- predict(svm.fit, OJ.train)
table(OJ.train$Purchase, preds.train)
##     preds.train
##       CH  MM
##   CH 445  42
##   MM  98 215
(98+42)/800
## [1] 0.175
preds.test <- predict(svm.fit, OJ.test)
table(OJ.test$Purchase, preds.test)
##     preds.test
##       CH  MM
##   CH 147  19
##   MM  40  64
(40+19)/270
## [1] 0.2185185
tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "polynomial", ranges = list(cost = c(0.01, 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
##    10      2
## 
## - best performance: 0.17125 
## 
## - Detailed performance results:
##     cost degree   error dispersion
## 1   0.01      2 0.38875 0.04308019
## 2   0.10      2 0.32250 0.04281744
## 3   1.00      2 0.19750 0.03374743
## 4   5.00      2 0.17250 0.03717451
## 5  10.00      2 0.17125 0.04084609
## 6   0.01      3 0.37250 0.05458174
## 7   0.10      3 0.30000 0.05034602
## 8   1.00      3 0.20250 0.05645795
## 9   5.00      3 0.19000 0.04851976
## 10 10.00      3 0.19375 0.05179085
## 11  0.01      4 0.37250 0.05296750
## 12  0.10      4 0.32750 0.05916080
## 13  1.00      4 0.23500 0.05886661
## 14  5.00      4 0.19250 0.04866267
## 15 10.00      4 0.19500 0.05839283
svm.fit <- svm(Purchase ~ ., data = OJ.train, kernel = "polynomial", cost = 10, degree = 2)
table(OJ.train$Purchase, preds.train)
##     preds.train
##       CH  MM
##   CH 445  42
##   MM  98 215
(98+42)/800
## [1] 0.175
preds.test <- predict(svm.fit, OJ.test)
table(OJ.test$Purchase, preds.test)
##     preds.test
##       CH  MM
##   CH 149  17
##   MM  33  71
(33+17)/270
## [1] 0.1851852

Overall, the radial kernal performed the best.