Question 5:

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:

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 y-axis.

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.

lm.fit = glm(y ~ x1 + x2, family = binomial)
summary(lm.fit)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
## 
## 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.

library(ggplot2)
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")
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. X21 , X1 ×X2, log(X2),and so forth).

lm.fit = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = data, 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.

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")
points(data.neg$x1, data.neg$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)
## 
## Attaching package: 'e1071'
## The following object is masked from 'package:ggplot2':
## 
##     element
svm.fit = svm(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.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 = "blue", xlab = "X1", ylab = "X2")
points(data.neg$x1, data.neg$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.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 = "blue", xlab = "X1", ylab = "X2")
points(data.neg$x1, data.neg$x2, col = "red")

i) in h) where we fit SVM using a non-linear kernel, we found linear boundary clearly, compared to other models

Question 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)
## The following object is masked from package:ggplot2:
## 
##     mpg
mpg_med = median(Auto$mpg)
bin.var = ifelse(Auto$mpg > mpg_med, 1, 0)
Auto$mpglevel = as.factor(bin.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.

library(e1071)
set.seed(1)
tune_out = tune(svm, mpg~., 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
##   0.1
## 
## - best performance: 8.981009 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1 1e-02 10.305990   5.295587
## 2 1e-01  8.981009   4.750742
## 3 1e+00  9.647184   4.313908
## 4 5e+00 10.149220   4.755080
## 5 1e+01 10.306219   4.953047
## 6 1e+02 10.684083   5.080506

cost = 0.1 is the lowest error rate

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.

set.seed(2)
tune_out = tune(svm, mpg ~ ., 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
##    10      2
## 
## - best performance: 50.95606 
## 
## - Detailed performance results:
##    cost degree    error dispersion
## 1   0.1      2 61.59446   13.60292
## 2   1.0      2 60.15304   13.79293
## 3   5.0      2 55.06386   15.19391
## 4  10.0      2 50.95606   15.72388
## 5   0.1      3 61.71831   13.56940
## 6   1.0      3 61.39833   13.54758
## 7   5.0      3 59.99304   13.43208
## 8  10.0      3 58.28857   13.27760
## 9   0.1      4 61.75343   13.57197
## 10  1.0      4 61.74822   13.57317
## 11  5.0      4 61.72510   13.57851
## 12 10.0      4 61.69626   13.58520

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

set.seed(33)
tune_out = tune(svm, mpg ~ ., data = Auto, kernel = "radial", 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
##    10      2
## 
## - best performance: 7.294024 
## 
## - Detailed performance results:
##    cost degree     error dispersion
## 1   0.1      2 22.211472   8.440215
## 2   1.0      2 10.118772   4.285877
## 3   5.0      2  7.649544   2.993582
## 4  10.0      2  7.294024   2.818545
## 5   0.1      3 22.211472   8.440215
## 6   1.0      3 10.118772   4.285877
## 7   5.0      3  7.649544   2.993582
## 8  10.0      3  7.294024   2.818545
## 9   0.1      4 22.211472   8.440215
## 10  1.0      4 10.118772   4.285877
## 11  5.0      4  7.649544   2.993582
## 12 10.0      4  7.294024   2.818545
svm_lin = 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 = "")), col = c("darkgreen", "orange"))
    }
}
plotpairs(svm_lin)

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

library(ISLR)
## 
## Attaching package: 'ISLR'
## The following object is masked _by_ '.GlobalEnv':
## 
##     Auto
## The following objects are masked from 'package:ISLR2':
## 
##     Auto, Credit
set.seed(9004)
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.

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:  442
## 
##  ( 222 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 432  51
##   MM  80 237
mean(train.pred!=OJ.train$Purchase)
## [1] 0.16375

The new training error rate is 16.12%.

test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 146  24
##   MM  22  78
mean(test.pred!=OJ.test$Purchase)
## [1] 0.1703704

The new test error rate is almost equal to the training error rate, 16.29%.

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

set.seed(1554)
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
##  3.162278
## 
## - best performance: 0.1625 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.16750 0.03395258
## 2   0.01778279 0.16875 0.02960973
## 3   0.03162278 0.16625 0.02638523
## 4   0.05623413 0.16875 0.03076005
## 5   0.10000000 0.16875 0.02901748
## 6   0.17782794 0.16750 0.02838231
## 7   0.31622777 0.17000 0.02898755
## 8   0.56234133 0.16875 0.02841288
## 9   1.00000000 0.16500 0.03106892
## 10  1.77827941 0.16500 0.03106892
## 11  3.16227766 0.16250 0.03118048
## 12  5.62341325 0.16375 0.02664713
## 13 10.00000000 0.16750 0.02581989

The best performer is 0.1625

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 428  55
##   MM  74 243
mean(train.pred!=OJ.train$Purchase)
## [1] 0.16125

The new training error rate for cost=10 is 16.12%.

test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 146  24
##   MM  20  80
mean(test.pred!=OJ.test$Purchase)
## [1] 0.162963

The new test error rate is 17.03%.

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

set.seed(410)
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:  371
## 
##  ( 188 183 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

The SVM created 371 support vectors out of the 800 training points.188 belong to Citrus Hill while 183 are Minute Maid’s

train.pred2 = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred2)
##     train.pred2
##       CH  MM
##   CH 441  42
##   MM  74 243
mean(train.pred2!=OJ.train$Purchase)
## [1] 0.145

The training error rate is 14%.

test.pred2 = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred2)
##     test.pred2
##       CH  MM
##   CH 148  22
##   MM  27  73
mean(test.pred2!=OJ.test$Purchase)
## [1] 0.1814815

The test error rate is 18.14%.

#Radial (d)
set.seed(5)
tune.outy2=tune(svm,Purchase~.,data=OJ.train,kernel='radial',ranges=list(cost=10^seq(-2,1,by=0.25)))
summary(tune.outy2)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##       cost
##  0.1778279
## 
## - best performance: 0.16875 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39625 0.03586723
## 2   0.01778279 0.39625 0.03586723
## 3   0.03162278 0.34875 0.04267529
## 4   0.05623413 0.19750 0.04958158
## 5   0.10000000 0.17500 0.04714045
## 6   0.17782794 0.16875 0.04832256
## 7   0.31622777 0.17000 0.05309844
## 8   0.56234133 0.17125 0.04860913
## 9   1.00000000 0.17250 0.04816061
## 10  1.77827941 0.17500 0.04930066
## 11  3.16227766 0.17375 0.05252314
## 12  5.62341325 0.18250 0.05533986
## 13 10.00000000 0.18375 0.05272110

Our optimal cost is 0.16875

#Radial (e): New training error for cost=3.162278
best2=tune.outy2$best.parameters$cost
svm.newcost2=svm(Purchase~.,kernel='radial',data=OJ.train,cost=best2)
train.pred2=predict(svm.newcost2,OJ.train)
table(OJ.train$Purchase,train.pred2)
##     train.pred2
##       CH  MM
##   CH 439  44
##   MM  82 235
mean(train.pred2!=OJ.train$Purchase)
## [1] 0.1575

Our new training error rate is 15.75%.

#Radial (e): New test error for cost=3.162278
test.pred2=predict(svm.newcost2,OJ.test)
table(OJ.test$Purchase,test.pred2)
##     test.pred2
##       CH  MM
##   CH 145  25
##   MM  30  70
mean(test.pred2!=OJ.test$Purchase)
## [1] 0.2037037

Our new test error rate is 20.37%, which is higher

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

#Poly (b)
poly.OJ=svm(Purchase~.,kernel='polynomial',data=OJ.train,degree=2)
summary(poly.OJ)
## 
## 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
#Poly (c) Training error
train.pred3=predict(poly.OJ,OJ.train)
table(OJ.train$Purchase,train.pred3)
##     train.pred3
##       CH  MM
##   CH 450  33
##   MM 111 206
mean(train.pred3!=OJ.train$Purchase)
## [1] 0.18

The training error here is 18%

#Poly (c) Test error
test.pred3=predict(poly.OJ,OJ.test)
table(OJ.test$Purchase,test.pred3)
##     test.pred3
##       CH  MM
##   CH 149  21
##   MM  34  66
mean(test.pred3!=OJ.test$Purchase)
## [1] 0.2037037

The test error rate here is 20.37%.

#Poly (d)
set.seed(5)
tune.outy3=tune(svm,Purchase~.,data=OJ.train,kernel='poly',degree=2,ranges=list(cost=10^seq(-2,1,by=0.25)))
summary(tune.outy3)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##      cost
##  5.623413
## 
## - best performance: 0.1775 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39375 0.03596391
## 2   0.01778279 0.37375 0.04185375
## 3   0.03162278 0.36375 0.03793727
## 4   0.05623413 0.34625 0.03821086
## 5   0.10000000 0.30625 0.04093101
## 6   0.17782794 0.24250 0.04794383
## 7   0.31622777 0.21125 0.04387878
## 8   0.56234133 0.20375 0.04931827
## 9   1.00000000 0.19375 0.03963812
## 10  1.77827941 0.19375 0.04832256
## 11  3.16227766 0.18750 0.05368374
## 12  5.62341325 0.17750 0.05426274
## 13 10.00000000 0.19000 0.05062114
#Poly (e): New training error for cost=10
best3=tune.outy3$best.parameters$cost
svm.newcost3=svm(Purchase~.,kernel='poly',degree=2,data=OJ.train,cost=best3)
train.newpred3=predict(svm.newcost3,OJ.train)
table(OJ.train$Purchase,train.newpred3)
##     train.newpred3
##       CH  MM
##   CH 448  35
##   MM  84 233
mean(train.newpred3!=OJ.train$Purchase)
## [1] 0.14875

The training error rate here is 14.87%.

#Poly (e): New test error for cost=10
test.newpred3=predict(svm.newcost3,OJ.test)
table(OJ.test$Purchase,test.newpred3)
##     test.newpred3
##       CH  MM
##   CH 149  21
##   MM  30  70
mean(test.newpred3!=OJ.test$Purchase)
## [1] 0.1888889

The test error rate here is 18.88%.

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

The polynomial approach with degree=2 and cost=10 seems to give the best results.