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.

library(e1071)

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

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, xlab = "X1", ylab = "X2", col = (4 - y), pch = (3 - y))

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

logit.fit <- glm(y ~ x1 + x2, family = "binomial")
summary(logit.fit)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = "binomial")
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -1.45338  -1.12969  -0.01151   1.16434   1.44522  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.01597    0.09059   0.176  0.86008   
## x1          -0.47687    0.32003  -1.490  0.13620   
## x2           0.91682    0.31149   2.943  0.00325 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 693.15  on 499  degrees of freedom
## Residual deviance: 681.99  on 497  degrees of freedom
## AIC: 687.99
## 
## Number of Fisher Scoring iterations: 4
## (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(logit.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.47] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0))

## (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")
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
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.021e-03  -2.000e-08   0.000e+00   2.000e-08   8.025e-04  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)
## (Intercept)     -78.77   12476.21  -0.006    0.995
## poly(x1, 2)1    337.45  155680.16   0.002    0.998
## poly(x1, 2)2  22454.53  813043.19   0.028    0.978
## poly(x2, 2)1   2007.29  178586.16   0.011    0.991
## poly(x2, 2)2 -24233.22  860086.63  -0.028    0.978
## I(x1 * x2)     -245.92  157750.44  -0.002    0.999
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9315e+02  on 499  degrees of freedom
## Residual deviance: 2.5763e-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.

probs <- predict(logitnl.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.47] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 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)
svm.fit <- svm(y ~ x1 + x2, data, kernel = "linear", cost = 0.01)
preds <- predict(svm.fit, data)
xlim = c(min(data[preds == 0, ]$x1), max(data[preds == 0, ]$x1))
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))

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

data$y <- as.factor(data$y)
svmnl.fit <- svm(y ~ x1 + x2, data, kernel = "radial", gamma = 1)
preds <- predict(svmnl.fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))

## (i) Comment on your results.

## We may conclude that SVM with non-linear kernel and logistic regression with interaction terms are equally very powerful for finding non-linear decision boundaries. 

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(ISLR2)
var <- ifelse(Auto$mpg > median(Auto$mpg), 1, 0)
Auto$mpglevel <- as.factor(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. Note you will need to fit the classifier without the gas mileage variable to produce sensible results.

tune.out <- tune(svm, mpglevel ~ ., 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
##     1
## 
## - best performance: 0.01782051 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.07897436 0.05517109
## 2 1e-01 0.05358974 0.04722483
## 3 1e+00 0.01782051 0.02413263
## 4 5e+00 0.02038462 0.02337923
## 5 1e+01 0.02551282 0.02402645
## 6 1e+02 0.03320513 0.02099200
## 7 1e+03 0.03320513 0.02099200
## 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.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), degree = c(2, 3, 4)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##   100      2
## 
## - best performance: 0.3087821 
## 
## - Detailed performance results:
##     cost degree     error dispersion
## 1  1e-02      2 0.5636538 0.03433469
## 2  1e-01      2 0.5636538 0.03433469
## 3  1e+00      2 0.5636538 0.03433469
## 4  5e+00      2 0.5636538 0.03433469
## 5  1e+01      2 0.5432051 0.05318341
## 6  1e+02      2 0.3087821 0.06367382
## 7  1e-02      3 0.5636538 0.03433469
## 8  1e-01      3 0.5636538 0.03433469
## 9  1e+00      3 0.5636538 0.03433469
## 10 5e+00      3 0.5636538 0.03433469
## 11 1e+01      3 0.5636538 0.03433469
## 12 1e+02      3 0.3496795 0.07525934
## 13 1e-02      4 0.5636538 0.03433469
## 14 1e-01      4 0.5636538 0.03433469
## 15 1e+00      4 0.5636538 0.03433469
## 16 5e+00      4 0.5636538 0.03433469
## 17 1e+01      4 0.5636538 0.03433469
## 18 1e+02      4 0.5636538 0.03433469
## For a polynomial kernel, the lowest cross-validation error is obtained for a degree of 2 and a cost of 100.

tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), 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
##   100  0.01
## 
## - best performance: 0.01275641 
## 
## - Detailed performance results:
##     cost gamma      error dispersion
## 1  1e-02 1e-02 0.48064103 0.16090774
## 2  1e-01 1e-02 0.08942308 0.04402669
## 3  1e+00 1e-02 0.07666667 0.05803491
## 4  5e+00 1e-02 0.05365385 0.04438487
## 5  1e+01 1e-02 0.03064103 0.02913640
## 6  1e+02 1e-02 0.01275641 0.01344780
## 7  1e-02 1e-01 0.16852564 0.08154919
## 8  1e-01 1e-01 0.08173077 0.05640965
## 9  1e+00 1e-01 0.05878205 0.05552107
## 10 5e+00 1e-01 0.03057692 0.03578795
## 11 1e+01 1e-01 0.02551282 0.02417610
## 12 1e+02 1e-01 0.03320513 0.01737168
## 13 1e-02 1e+00 0.48064103 0.16090774
## 14 1e-01 1e+00 0.48064103 0.16090774
## 15 1e+00 1e+00 0.05871795 0.04535877
## 16 5e+00 1e+00 0.06128205 0.04719001
## 17 1e+01 1e+00 0.06128205 0.04719001
## 18 1e+02 1e+00 0.06128205 0.04719001
## 19 1e-02 5e+00 0.52064103 0.03728103
## 20 1e-01 5e+00 0.52064103 0.03728103
## 21 1e+00 5e+00 0.44647436 0.11234735
## 22 5e+00 5e+00 0.46192308 0.05863210
## 23 1e+01 5e+00 0.46192308 0.05863210
## 24 1e+02 5e+00 0.46192308 0.05863210
## 25 1e-02 1e+01 0.52314103 0.03034858
## 26 1e-01 1e+01 0.52314103 0.03034858
## 27 1e+00 1e+01 0.49756410 0.03597088
## 28 5e+00 1e+01 0.49243590 0.03910408
## 29 1e+01 1e+01 0.49243590 0.03910408
## 30 1e+02 1e+01 0.49243590 0.03910408
## 31 1e-02 1e+02 0.52814103 0.01893035
## 32 1e-01 1e+02 0.52814103 0.01893035
## 33 1e+00 1e+02 0.52814103 0.01893035
## 34 5e+00 1e+02 0.52814103 0.01893035
## 35 1e+01 1e+02 0.52814103 0.01893035
## 36 1e+02 1e+02 0.52814103 0.01893035
## For a radial kernel, the lowest cross-validation error is obtained for a gamma of 0.01 and a cost of 100.

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

svm.linear <- svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly <- svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 100, degree = 2)
svm.radial <- svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 100, 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 ISLR2 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.linear <- svm(Purchase ~ ., data = OJ.train, kernel = "linear", 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:  440
## 
##  ( 220 220 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
## (c) What are the training and test error rates?

train.pred <- predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 430  57
##   MM  76 237
(78 + 55) / (439 + 228 + 78 + 55)
## [1] 0.16625
test.pred <- predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 147  19
##   MM  28  76
(31 + 18) / (141 + 80 + 31 + 18)
## [1] 0.1814815
## The training error rate is 16.6% and test error rate is about 18.1%.

## (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
##  0.3162278
## 
## - best performance: 0.17 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.17500 0.04823265
## 2   0.01778279 0.17875 0.05001736
## 3   0.03162278 0.17625 0.04693746
## 4   0.05623413 0.17500 0.04930066
## 5   0.10000000 0.17375 0.04910660
## 6   0.17782794 0.17125 0.04450733
## 7   0.31622777 0.17000 0.04571956
## 8   0.56234133 0.17250 0.04479893
## 9   1.00000000 0.17250 0.04594683
## 10  1.77827941 0.17125 0.04752558
## 11  3.16227766 0.17375 0.04543387
## 12  5.62341325 0.17125 0.03998698
## 13 10.00000000 0.17125 0.04489571
## We may see that the optimal cost is 0.1.

## (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.parameter$cost)
train.pred <- predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 431  56
##   MM  72 241
(71 + 56) / (438 + 235 + 71 + 56)
## [1] 0.15875
test.pred <- predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 146  20
##   MM  30  74
(32 + 19) / (140 + 79 + 32 + 19)
## [1] 0.1888889
## We may see that, with the best cost, the training error rate is now 15.8% and the test error rate is 18.8%.

## (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 ~ ., kernel = "radial", data = OJ.train)
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:  371
## 
##  ( 188 183 )
## 
## 
## 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 443  44
##   MM  67 246
(77 + 39) / (455 + 229 + 77 + 39)
## [1] 0.145
test.pred <- predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 148  18
##   MM  32  72
(28 + 18) / (141 + 83 + 28 + 18)
## [1] 0.1703704
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
##  0.3162278
## 
## - best performance: 0.17625 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39125 0.06615691
## 2   0.01778279 0.39125 0.06615691
## 3   0.03162278 0.36875 0.08400769
## 4   0.05623413 0.20125 0.02531057
## 5   0.10000000 0.17750 0.03322900
## 6   0.17782794 0.17625 0.03030516
## 7   0.31622777 0.17625 0.02729087
## 8   0.56234133 0.17625 0.03143004
## 9   1.00000000 0.17750 0.03476109
## 10  1.77827941 0.17625 0.03143004
## 11  3.16227766 0.18000 0.03184162
## 12  5.62341325 0.18250 0.03736085
## 13 10.00000000 0.19500 0.03827895
svm.radial <- svm(Purchase ~ ., kernel = "radial", data = OJ.train, cost = tune.out$best.parameter$cost)
summary(svm.radial)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "radial", cost = tune.out$best.parameter$cost)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  0.3162278 
## 
## Number of Support Vectors:  441
## 
##  ( 223 218 )
## 
## 
## 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 442  45
##   MM  77 236
(77 + 39) / (455 + 229 + 77 + 39)
## [1] 0.145
test.pred <- predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 148  18
##   MM  30  74
(28 + 18) / (141 + 83 + 28 + 18)
## [1] 0.1703704
## (g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.

svm.poly <- svm(Purchase ~ ., kernel = "polynomial", data = OJ.train, degree = 2)
summary(svm.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "polynomial", 
##     degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  1 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  456
## 
##  ( 232 224 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred <- predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 456  31
##   MM 104 209
(105 + 33) / (461 + 201 + 105 + 33)
## [1] 0.1725
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 153  13
##   MM  45  59
(41 + 10) / (149 + 70 + 41 + 10)
## [1] 0.1888889
tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "polynomial", degree = 2, 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
##  5.623413
## 
## - best performance: 0.1675 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39125 0.06068189
## 2   0.01778279 0.37125 0.05864500
## 3   0.03162278 0.36000 0.05130248
## 4   0.05623413 0.33500 0.04706674
## 5   0.10000000 0.31750 0.04972145
## 6   0.17782794 0.26125 0.06386020
## 7   0.31622777 0.21625 0.05070681
## 8   0.56234133 0.20375 0.04251225
## 9   1.00000000 0.19375 0.03294039
## 10  1.77827941 0.19125 0.03230175
## 11  3.16227766 0.18625 0.04730589
## 12  5.62341325 0.16750 0.03496029
## 13 10.00000000 0.16750 0.03736085
svm.poly <- svm(Purchase ~ ., kernel = "polynomial", degree = 2, data = OJ.train, cost = tune.out$best.parameter$cost)
summary(svm.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "polynomial", 
##     degree = 2, cost = tune.out$best.parameter$cost)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  5.623413 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  357
## 
##  ( 185 172 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred <- predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 451  36
##   MM  76 237
(72 + 44) / (450 + 234 + 72 + 44)
## [1] 0.145
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 148  18
##   MM  37  67
(31 + 19) / (140 + 80 + 31 + 19)
## [1] 0.1851852
## (h) Overall, which approach seems to give the best results on this data?

## Overall, radial basis kernel seems to be producing minimum misclassification error on both train and test data.