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*(x12-x22 > 0)**

set.seed(421)
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")

(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.278  -1.227   1.089   1.135   1.175  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  0.11999    0.08971   1.338    0.181
## x1          -0.16881    0.30854  -0.547    0.584
## x2          -0.08198    0.31476  -0.260    0.795
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 691.35  on 499  degrees of freedom
## Residual deviance: 690.99  on 497  degrees of freedom
## AIC: 696.99
## 
## 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.52, 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 = "red")

(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.fit2 = glm(y ~ log(x1) + poly(x2, 2) + I(x1 * x2), data = data, family = binomial)
summary(lm.fit2)
## 
## Call:
## glm(formula = y ~ log(x1) + poly(x2, 2) + I(x1 * x2), family = binomial, 
##     data = data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.7333  -0.1688   0.0476   0.2295   3.5101  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept)    6.2844     1.0263   6.123 9.16e-10 ***
## log(x1)        4.1047     0.6615   6.205 5.48e-10 ***
## poly(x2, 2)1  27.0972    17.8783   1.516    0.130    
## poly(x2, 2)2 -82.8381    11.8321  -7.001 2.54e-12 ***
## I(x1 * x2)   -14.6134     8.3195  -1.757    0.079 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 348.57  on 251  degrees of freedom
## Residual deviance: 104.31  on 247  degrees of freedom
##   (248 observations deleted due to missingness)
## AIC: 114.31
## 
## Number of Fisher Scoring iterations: 7

(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.prob2 = predict(lm.fit2, data, type = "response")
lm.pred2 = ifelse(lm.prob2 > 0.5, 1, 0)
data.pos2 = data[lm.pred2 == 1, ]
data.neg2 = data[lm.pred2 == 0, ]
plot(data.pos2$x1, data.pos2$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg2$x1, data.neg2$x2, col = "red")

(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.fit = svm(as.factor(y) ~ ., data, kernel = "linear", cost = 0.1)
svm.pred = predict(svm.fit, data)
data.pos3 = data[svm.pred == 1, ]
data.neg3 = data[svm.pred == 0, ]
plot(data.pos3$x1, data.pos3$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg3$x1, data.neg3$x2, col = "red")

(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(as.factor(y) ~ x1 + x2, data, gamma = 1)
svm.pred2 = predict(svm.fit2, data)
data.pos4 = data[svm.pred2 == 1, ]
data.neg4 = data[svm.pred2 == 0, ]
plot(data.pos4$x1, data.pos4$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg4$x1, data.neg4$x2, col = "red")

(i) Comment on your results.

In the support vector machine using the radial kernels, the non-linear relationship is clearly visible in the plot. There is no clear relationship in the SVM model in part (g) as it appears all of the predictions are positive.

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.

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

library(e1071)
Auto2 <- subset(Auto, select = c(-mpg))
set.seed(1)
tune.out = tune(svm, mpglevel~ ., data = Auto2, 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
##   0.1
## 
## - best performance: 0.08673077 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.08923077 0.04698309
## 2 1e-01 0.08673077 0.04040897
## 3 1e+00 0.09961538 0.04923181
## 4 5e+00 0.11230769 0.05826857
## 5 1e+01 0.11237179 0.05701890
## 6 1e+02 0.11750000 0.06208951

When the cost is 0.1 it produces the best parameters for this model.

(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.out2 = tune(svm, mpglevel~., data = Auto2, kernel = "polynomial", ranges = list(cost = c(0.1, 1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out2)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##    10      2
## 
## - best performance: 0.5841667 
## 
## - Detailed performance results:
##    cost degree     error dispersion
## 1   0.1      2 0.6019231 0.06346118
## 2   1.0      2 0.6019231 0.06346118
## 3   5.0      2 0.6019231 0.06346118
## 4  10.0      2 0.5841667 0.07806609
## 5   0.1      3 0.6019231 0.06346118
## 6   1.0      3 0.6019231 0.06346118
## 7   5.0      3 0.6019231 0.06346118
## 8  10.0      3 0.6019231 0.06346118
## 9   0.1      4 0.6019231 0.06346118
## 10  1.0      4 0.6019231 0.06346118
## 11  5.0      4 0.6019231 0.06346118
## 12 10.0      4 0.6019231 0.06346118
tune.out3 =tune(svm, mpglevel ~ ., data = Auto2, kernel = "radial", ranges = list(cost = c(0.1, 
    1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out3)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##     1      2
## 
## - best performance: 0.08955128 
## 
## - Detailed performance results:
##    cost degree      error dispersion
## 1   0.1      2 0.17628205 0.06267717
## 2   1.0      2 0.08955128 0.04406483
## 3   5.0      2 0.09198718 0.02485852
## 4  10.0      2 0.09705128 0.02892629
## 5   0.1      3 0.17628205 0.06267717
## 6   1.0      3 0.08955128 0.04406483
## 7   5.0      3 0.09198718 0.02485852
## 8  10.0      3 0.09705128 0.02892629
## 9   0.1      4 0.17628205 0.06267717
## 10  1.0      4 0.08955128 0.04406483
## 11  5.0      4 0.09198718 0.02485852
## 12 10.0      4 0.09705128 0.02892629

In the polynomial model the error rate is lowest when cost is 10 with a degree of 2. In the radial model the optimal parameters are cost 5 and degree 2.

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

svm_lin = svm(mpglevel ~ ., data = Auto2, kernel = "linear", cost = 0.1)
svm_poly = svm(mpglevel ~ ., data = Auto2, kernel = "polynomial", cost = 10, 
    degree = 2)
svm_radial = svm(mpglevel ~ ., data = Auto2, kernel = "radial", cost = 5, 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_lin)

plotpairs(svm_poly)

plotpairs(svm_radial)

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.

detach(Auto)
attach(OJ)
set.seed(1)
data_Train = sample(nrow(OJ), 800)
oj_train = OJ[data_Train,]
oj_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=oj_train,kernel='linear',cost=0.01)
summary(svc)
## 
## 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:  435
## 
##  ( 219 216 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

435 vectors have been created, with 219 of those belonging to level CH and 216 belonging to level MM.

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

pred_train = predict(svc, oj_train)
(t<-table(oj_train$Purchase, pred_train))
##     pred_train
##       CH  MM
##   CH 420  65
##   MM  75 240
(65+75)/800
## [1] 0.175
pred_test = predict(svc, oj_test)
table(oj_test$Purchase, pred_test)
##     pred_test
##       CH  MM
##   CH 153  15
##   MM  33  69
(15+33)/270
## [1] 0.1777778

The training error rate is .175 and the testing error rate is .178.

(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_train, 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
##   0.1
## 
## - best performance: 0.1725 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.17625 0.02853482
## 2  0.10 0.17250 0.03162278
## 3  1.00 0.17500 0.02946278
## 4 10.00 0.17375 0.03197764

The lowest error rate is 0.1725 at 0.1 cost.

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

svm_lin_1 = svm(Purchase ~ ., kernel = "linear", data = oj_train, cost = 0.1)
pred_train_1 = predict(svm_lin_1, oj_train)
table(oj_train$Purchase, pred_train_1)
##     pred_train_1
##       CH  MM
##   CH 422  63
##   MM  69 246
(63+69)/800
## [1] 0.165
test_pred_1 = predict(svm_lin_1, oj_test)
(t<-table(oj_test$Purchase, test_pred_1))
##     test_pred_1
##       CH  MM
##   CH 155  13
##   MM  31  71
(13+31)/270
## [1] 0.162963

The training error rate is .165 and the test error rate is .163.

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

set.seed(1)
svm_rad_1 = svm(Purchase ~ ., data = oj_train, kernel = "radial")
summary(svm_rad_1)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj_train, kernel = "radial")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  1 
## 
## Number of Support Vectors:  373
## 
##  ( 188 185 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
pred_train_2 = predict(svm_rad_1, oj_train)
table(oj_train$Purchase, pred_train_2)
##     pred_train_2
##       CH  MM
##   CH 441  44
##   MM  77 238
(44+77)/800
## [1] 0.15125
test_pred_2 = predict(svm_rad_1, oj_test)
table(oj_test$Purchase, test_pred_2)
##     test_pred_2
##       CH  MM
##   CH 151  17
##   MM  33  69
(17+33)/270
## [1] 0.1851852
svm_rad_1 = svm(Purchase ~ ., data = oj_train, kernel = "radial", cost = 1)
pred_train = predict(svm_rad_1, oj_train)
table(oj_train$Purchase, pred_train_1)
##     pred_train_1
##       CH  MM
##   CH 422  63
##   MM  69 246
(63+69)/800
## [1] 0.165
test_pred_3 = predict(svm_rad_1, oj_test)
(t<-table(oj_test$Purchase, test_pred_3))
##     test_pred_3
##       CH  MM
##   CH 151  17
##   MM  33  69
(17+33)/270
## [1] 0.1851852

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

svm_pol_1 = svm(Purchase ~ ., kernel = "poly", data = oj_train, degree=2)
summary(svm_pol_1)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj_train, kernel = "poly", degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  1 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  447
## 
##  ( 225 222 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
pred_train_2 = predict(svm_pol_1, oj_train)
(t<-table(oj_train$Purchase, pred_train_2))
##     pred_train_2
##       CH  MM
##   CH 449  36
##   MM 110 205
(36+110)/800
## [1] 0.1825
test_pred_3 = predict(svm_pol_1, oj_test)
(t<-table(oj_test$Purchase, test_pred_3))
##     test_pred_3
##       CH  MM
##   CH 153  15
##   MM  45  57
(15+45)/270
## [1] 0.2222222
set.seed(1)
tune_svc = tune(svm, Purchase ~ ., data = oj_train, kernel = "poly", degree = 2, ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
summary(tune_svc)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##      cost
##  3.162278
## 
## - best performance: 0.1775 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39125 0.04210189
## 2   0.01778279 0.37125 0.03537988
## 3   0.03162278 0.36500 0.03476109
## 4   0.05623413 0.33750 0.04714045
## 5   0.10000000 0.32125 0.05001736
## 6   0.17782794 0.24500 0.04758034
## 7   0.31622777 0.19875 0.03972562
## 8   0.56234133 0.20500 0.03961621
## 9   1.00000000 0.20250 0.04116363
## 10  1.77827941 0.18500 0.04199868
## 11  3.16227766 0.17750 0.03670453
## 12  5.62341325 0.18375 0.03064696
## 13 10.00000000 0.18125 0.02779513

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

The linear approach gives the best results for this data with a training error rate of 0.165 and a test error rate of 0.163.