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:

set.seed(7)
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=20)
points(x1[y==1], x2[y==1], col="blue", pch=20)

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

dat = data.frame(x1 = x1, x2 = x2, y = as.factor(y))
glm.fit = glm(y~., data=dat, family="binomial")
summary(glm.fit)
## 
## Call:
## glm(formula = y ~ ., family = "binomial", data = dat)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.293  -1.127  -1.017   1.202   1.361  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.07024    0.08986  -0.782    0.434
## x1           0.29100    0.32001   0.909    0.363
## x2          -0.49403    0.30840  -1.602    0.109
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 692.50  on 499  degrees of freedom
## Residual deviance: 688.94  on 497  degrees of freedom
## AIC: 694.94
## 
## 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.

glm.prob = predict(glm.fit, newdata=dat, type = "response")
glm.pred = ifelse(glm.prob > 0.5, 1, 0)
data.pos = dat[glm.pred == 1, ]
data.neg = dat[glm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = 20)
points(data.neg$x1, data.neg$x2, col = "red", pch = 16)

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

glm.fit2 = glm(y~poly(x1,2) + poly(x2,2) + log(x2) + I(x1*x2), data=dat, family = "binomial")
## Warning in log(x2): NaNs produced
## 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. 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.

glm.probs2 = predict(glm.fit2, newdata = dat, type = "response")
## Warning in log(x2): NaNs produced
glm.pred2 = ifelse(glm.probs2 >= 0.5, 1, 0)
data.pos2 = dat[glm.pred2 == 1,]
data.neg2 = dat[glm.pred2 == 0,]
plot(data.pos2$x1, data.pos2$x2, col="blue", xlab="X1", ylab="X2", pch=20)
points(data.neg2$x1, data.neg2$x2, col="red", pch=16)

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

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

library(e1071)
svm.fit2=svm(as.factor(y)~x1+x2, dat, kernel="radial", gamma=1, cost=1)
svm.pred2=predict(svm.fit2, dat)
svm.pos2= dat[svm.pred2==1,]
svm.neg2= dat[svm.pred2==0,]
plot(svm.pos2$x1, svm.pos2$x2, col="blue", xlab="X1", ylab="X2", pch=20)
points(svm.neg2$x1, svm.neg2$x2, col="red", pch=16)

(i) Comment on your results.

Both the Linear SVM and Non-Linear SVM resemable the true classifications for this data. The Logistic Regressions did not accurately predict the classification.

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.

library(ISLR)
## Warning: package 'ISLR' was built under R version 3.6.3
data(Auto)
summary(Auto)
##       mpg          cylinders      displacement     horsepower   
##  Min.   : 9.00   Min.   :3.000   Min.   : 68.0   Min.   : 46.0  
##  1st Qu.:17.00   1st Qu.:4.000   1st Qu.:105.0   1st Qu.: 75.0  
##  Median :22.75   Median :4.000   Median :151.0   Median : 93.5  
##  Mean   :23.45   Mean   :5.472   Mean   :194.4   Mean   :104.5  
##  3rd Qu.:29.00   3rd Qu.:8.000   3rd Qu.:275.8   3rd Qu.:126.0  
##  Max.   :46.60   Max.   :8.000   Max.   :455.0   Max.   :230.0  
##                                                                 
##      weight      acceleration        year           origin     
##  Min.   :1613   Min.   : 8.00   Min.   :70.00   Min.   :1.000  
##  1st Qu.:2225   1st Qu.:13.78   1st Qu.:73.00   1st Qu.:1.000  
##  Median :2804   Median :15.50   Median :76.00   Median :1.000  
##  Mean   :2978   Mean   :15.54   Mean   :75.98   Mean   :1.577  
##  3rd Qu.:3615   3rd Qu.:17.02   3rd Qu.:79.00   3rd Qu.:2.000  
##  Max.   :5140   Max.   :24.80   Max.   :82.00   Max.   :3.000  
##                                                                
##                  name    
##  amc matador       :  5  
##  ford pinto        :  5  
##  toyota corolla    :  5  
##  amc gremlin       :  4  
##  amc hornet        :  4  
##  chevrolet chevette:  4  
##  (Other)           :365

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

gas.med = median(Auto$mpg)
gas.class = ifelse(Auto$mpg > gas.med, 1, 0)
Auto$mpglevel = as.factor(gas.class)
str(Auto$mpglevel)
##  Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...

(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.
We can see from the below output that the cross-validation error of 0.01269231 is minimized at cost = 100. The optimal model selected is a Radial SVM model with C = 100 and 63 Support Vectors with 30 of them classified as “low MPG” and 33 classified as “high MPG”.

set.seed(7)
tune.out=tune(svm, mpglevel~., data=Auto, kernal="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
##   100
## 
## - best performance: 0.01269231 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.55858974 0.03870200
## 2 1e-01 0.10730769 0.04825106
## 3 1e+00 0.07660256 0.03813639
## 4 5e+00 0.06891026 0.03816032
## 5 1e+01 0.05358974 0.03060885
## 6 1e+02 0.01269231 0.02154160
tune.out$best.parameters
##   cost
## 6  100
best.svmLinear = tune.out$best.model
summary(best.svmLinear)
## 
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, 
##     ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100)), kernal = "linear")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  100 
## 
## Number of Support Vectors:  63
## 
##  ( 30 33 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  0 1

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

For the Radial Kernal, the model selected has a Cost of 100 and Gamma of 0.01 and yielded an error of 0.02294872. There are 57 Support Vectors with 27 of them classified as “low MPG” and 30 classified as “high MPG”.

For the Polynomial Kernal, the model selected has a Cost of 100 and degree of 2 and yielded an error of 0.01269231. There are 63 Support Vectors with 30 of them classified as “low MPG” and 33 classified as “high MPG”.

set.seed(7)
tune.out.rad = tune(svm, mpglevel~., data=Auto, kernal="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.rad)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##   100  0.01
## 
## - best performance: 0.02294872 
## 
## - Detailed performance results:
##     cost gamma      error dispersion
## 1  1e-02 1e-02 0.55858974 0.03870200
## 2  1e-01 1e-02 0.09198718 0.04227017
## 3  1e+00 1e-02 0.07403846 0.03704323
## 4  5e+00 1e-02 0.05352564 0.03286051
## 5  1e+01 1e-02 0.02801282 0.03036301
## 6  1e+02 1e-02 0.02294872 0.02820642
## 7  1e-02 1e-01 0.21160256 0.08418936
## 8  1e-01 1e-01 0.07660256 0.04179222
## 9  1e+00 1e-01 0.05871795 0.02711605
## 10 5e+00 1e-01 0.03307692 0.02397013
## 11 1e+01 1e-01 0.02794872 0.02199962
## 12 1e+02 1e-01 0.03051282 0.02612821
## 13 1e-02 1e+00 0.55858974 0.03870200
## 14 1e-01 1e+00 0.55858974 0.03870200
## 15 1e+00 1e+00 0.06897436 0.04669593
## 16 5e+00 1e+00 0.06897436 0.04669593
## 17 1e+01 1e+00 0.06897436 0.04669593
## 18 1e+02 1e+00 0.06897436 0.04669593
## 19 1e-02 5e+00 0.55858974 0.03870200
## 20 1e-01 5e+00 0.55858974 0.03870200
## 21 1e+00 5e+00 0.50256410 0.04642607
## 22 5e+00 5e+00 0.49743590 0.04482497
## 23 1e+01 5e+00 0.49743590 0.04482497
## 24 1e+02 5e+00 0.49743590 0.04482497
## 25 1e-02 1e+01 0.55858974 0.03870200
## 26 1e-01 1e+01 0.55858974 0.03870200
## 27 1e+00 1e+01 0.51782051 0.05141170
## 28 5e+00 1e+01 0.51782051 0.05141170
## 29 1e+01 1e+01 0.51782051 0.05141170
## 30 1e+02 1e+01 0.51782051 0.05141170
## 31 1e-02 1e+02 0.55858974 0.03870200
## 32 1e-01 1e+02 0.55858974 0.03870200
## 33 1e+00 1e+02 0.55858974 0.03870200
## 34 5e+00 1e+02 0.55858974 0.03870200
## 35 1e+01 1e+02 0.55858974 0.03870200
## 36 1e+02 1e+02 0.55858974 0.03870200
tune.out.rad$best.performance
## [1] 0.02294872
best.rad.model = tune.out.rad$best.model
summary(best.rad.model)
## 
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, 
##     ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), gamma = c(0.01, 
##         0.1, 1, 5, 10, 100)), kernal = "radial")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  100 
## 
## Number of Support Vectors:  57
## 
##  ( 27 30 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  0 1
set.seed(7)
tune.out.poly = tune(svm, mpglevel~., data=Auto, kernal="polynomial", ranges=list(cost=c(0.01, 0.1, 1, 5, 10, 100), degree=c(2,3,4,5)))
summary(tune.out.poly)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##   100      2
## 
## - best performance: 0.01269231 
## 
## - Detailed performance results:
##     cost degree      error dispersion
## 1  1e-02      2 0.55858974 0.03870200
## 2  1e-01      2 0.10730769 0.04825106
## 3  1e+00      2 0.07660256 0.03813639
## 4  5e+00      2 0.06891026 0.03816032
## 5  1e+01      2 0.05358974 0.03060885
## 6  1e+02      2 0.01269231 0.02154160
## 7  1e-02      3 0.55858974 0.03870200
## 8  1e-01      3 0.10730769 0.04825106
## 9  1e+00      3 0.07660256 0.03813639
## 10 5e+00      3 0.06891026 0.03816032
## 11 1e+01      3 0.05358974 0.03060885
## 12 1e+02      3 0.01269231 0.02154160
## 13 1e-02      4 0.55858974 0.03870200
## 14 1e-01      4 0.10730769 0.04825106
## 15 1e+00      4 0.07660256 0.03813639
## 16 5e+00      4 0.06891026 0.03816032
## 17 1e+01      4 0.05358974 0.03060885
## 18 1e+02      4 0.01269231 0.02154160
## 19 1e-02      5 0.55858974 0.03870200
## 20 1e-01      5 0.10730769 0.04825106
## 21 1e+00      5 0.07660256 0.03813639
## 22 5e+00      5 0.06891026 0.03816032
## 23 1e+01      5 0.05358974 0.03060885
## 24 1e+02      5 0.01269231 0.02154160
tune.out.poly$best.performance
## [1] 0.01269231
best.poly.model = tune.out.poly$best.model
summary(best.poly.model)
## 
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, 
##     ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), degree = c(2, 
##         3, 4, 5)), kernal = "polynomial")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  100 
## 
## Number of Support Vectors:  63
## 
##  ( 30 33 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  0 1

(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 > plot(svmfit , dat) where svmfit contains your fitted model and dat is a data frame containing your data, you can type > plot(svmfit , dat , x1∼x4) in order to plot just the first and fourth variables. However, you must replace x1 and x4 with the correct variable names. To find out more, type ?plot.svm.

Linear Support Vector Classifier Plots

svm.linear=svm(mpglevel~., data=Auto, kernal="linear", cost=100)
svm.rad=svm(mpglevel~., data=Auto, kernal="radial", cost=100, gamma=0.01)
svm.poly=svm(mpglevel~., data=Auto, kernal="polynomial", cost=100, degree=2)
plotpairs = function(autofit) {
    for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpglevel", "name"))]) {
        plot(autofit, Auto, as.formula(paste("mpg~", name, sep = "")))
    }
}
plotpairs(svm.linear)

## Polynomial Support Vector Classifier

plotpairs(svm.poly)

Problem 8

This problem involves the OJ data set which is part of the ISLR package.

library(ISLR)
data(OJ)
summary(OJ)
##  Purchase WeekofPurchase     StoreID        PriceCH         PriceMM     
##  CH:653   Min.   :227.0   Min.   :1.00   Min.   :1.690   Min.   :1.690  
##  MM:417   1st Qu.:240.0   1st Qu.:2.00   1st Qu.:1.790   1st Qu.:1.990  
##           Median :257.0   Median :3.00   Median :1.860   Median :2.090  
##           Mean   :254.4   Mean   :3.96   Mean   :1.867   Mean   :2.085  
##           3rd Qu.:268.0   3rd Qu.:7.00   3rd Qu.:1.990   3rd Qu.:2.180  
##           Max.   :278.0   Max.   :7.00   Max.   :2.090   Max.   :2.290  
##      DiscCH            DiscMM         SpecialCH        SpecialMM     
##  Min.   :0.00000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000  
##  1st Qu.:0.00000   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:0.0000  
##  Median :0.00000   Median :0.0000   Median :0.0000   Median :0.0000  
##  Mean   :0.05186   Mean   :0.1234   Mean   :0.1477   Mean   :0.1617  
##  3rd Qu.:0.00000   3rd Qu.:0.2300   3rd Qu.:0.0000   3rd Qu.:0.0000  
##  Max.   :0.50000   Max.   :0.8000   Max.   :1.0000   Max.   :1.0000  
##     LoyalCH          SalePriceMM     SalePriceCH      PriceDiff      
##  Min.   :0.000011   Min.   :1.190   Min.   :1.390   Min.   :-0.6700  
##  1st Qu.:0.325257   1st Qu.:1.690   1st Qu.:1.750   1st Qu.: 0.0000  
##  Median :0.600000   Median :2.090   Median :1.860   Median : 0.2300  
##  Mean   :0.565782   Mean   :1.962   Mean   :1.816   Mean   : 0.1465  
##  3rd Qu.:0.850873   3rd Qu.:2.130   3rd Qu.:1.890   3rd Qu.: 0.3200  
##  Max.   :0.999947   Max.   :2.290   Max.   :2.090   Max.   : 0.6400  
##  Store7      PctDiscMM        PctDiscCH       ListPriceDiff  
##  No :714   Min.   :0.0000   Min.   :0.00000   Min.   :0.000  
##  Yes:356   1st Qu.:0.0000   1st Qu.:0.00000   1st Qu.:0.140  
##            Median :0.0000   Median :0.00000   Median :0.240  
##            Mean   :0.0593   Mean   :0.02731   Mean   :0.218  
##            3rd Qu.:0.1127   3rd Qu.:0.00000   3rd Qu.:0.300  
##            Max.   :0.4020   Max.   :0.25269   Max.   :0.440  
##      STORE      
##  Min.   :0.000  
##  1st Qu.:0.000  
##  Median :2.000  
##  Mean   :1.631  
##  3rd Qu.:3.000  
##  Max.   :4.000

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

set.seed(7)
inTrain=sample(1:nrow(OJ), 800)
oj.train = OJ[inTrain,]
oj.test = OJ[-inTrain,]
dim(oj.train)
## [1] 800  18
dim(oj.test)
## [1] 270  18

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

The Support Vector Classifier with Cost = 0.01 results in 438 Support Vectors with 218 being classified as CH and 220 being classified as MM.

library(e1071)
oj.svm <- svm(Purchase~., data = oj.train, kernel = "linear", cost = 0.01)
summary(oj.svm)
## 
## 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:  438
## 
##  ( 218 220 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

(c) What are the training and test error rates?
The training error rate is 17%, and the test error rate is 16.2%.

#training error
oj.train.pred <- predict(oj.svm, oj.train)
table(oj.train$Purchase, oj.train.pred)
##     oj.train.pred
##       CH  MM
##   CH 424  60
##   MM  76 240
(60+76)/800
## [1] 0.17
#test error
oj.test.pred <- predict(oj.svm, oj.test)
table(oj.test$Purchase, oj.test.pred)
##     oj.test.pred
##       CH  MM
##   CH 154  15
##   MM  29  72
(15+29)/270
## [1] 0.162963

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

The optimal Cost value is 5 with an error of 0.1725.

set.seed(7)
oj.tune.out = tune(svm, Purchase ~., data = oj.train, kernel = "linear", ranges = list(cost=c(0.01, 0.1, 1, 5, 10)))
summary(oj.tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     5
## 
## - best performance: 0.1725 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.17750 0.03106892
## 2  0.10 0.17750 0.03270236
## 3  1.00 0.17625 0.02531057
## 4  5.00 0.17250 0.02486072
## 5 10.00 0.17375 0.02316157

(e) Compute the training and test error rates using this new value for cost.
For the optimal Cost value of 5, the training error is 16.75% , and the test error is 16.29%.

#training error
oj.new.svm = svm(Purchase ~., kernel = "linear", data = oj.train, cost = 5)
oj.new.train.pred = predict(oj.new.svm, oj.train)
table(oj.train$Purchase, oj.new.train.pred)
##     oj.new.train.pred
##       CH  MM
##   CH 425  59
##   MM  75 241
(59+75)/800
## [1] 0.1675
#test error
oj.new.test.pred = predict(oj.new.svm, oj.test)
table(oj.test$Purchase, oj.new.test.pred)
##     oj.new.test.pred
##       CH  MM
##   CH 154  15
##   MM  29  72
(15+29)/270
## [1] 0.162963

(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
For the Radial SVM with a Cost value of 0.01, 636 Support Vectors were used. 320 are classified as CH and 316 are classified as MM. The training error for this model is 39.5% and the test error is 37.4%.
After tuning the Radial SVM, the best Cost Value is 1 with an error of 0.17375. In this model, 381 Support Vectors were used with 194 classified as CH and 187 classified as MM.The training error for this model is 15.75%, and the test error of 15.9%.

oj.svm.rad = svm(Purchase~., data = oj.train, kernel = "radial", cost = 0.01)
summary(oj.svm.rad)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj.train, kernel = "radial", 
##     cost = 0.01)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  0.01 
## 
## Number of Support Vectors:  636
## 
##  ( 320 316 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
#training error
oj.rad.train.pred = predict(oj.svm.rad, oj.train)
table(oj.train$Purchase, oj.rad.train.pred)
##     oj.rad.train.pred
##       CH  MM
##   CH 484   0
##   MM 316   0
(316/800)
## [1] 0.395
oj.rad.test.pred = predict(oj.svm.rad, oj.test)
table(oj.test$Purchase, oj.rad.test.pred)
##     oj.rad.test.pred
##       CH  MM
##   CH 169   0
##   MM 101   0
(101/270)
## [1] 0.3740741
#tuning - optimal cost=1
set.seed(7)
oj.rad.tune = tune(svm, Purchase~., data = oj.train, kernal = "radial", ranges = list(cost=c(0.01, 0.1, 1, 5, 10)))
summary(oj.rad.tune)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.17375 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.39500 0.07197608
## 2  0.10 0.18750 0.04330127
## 3  1.00 0.17375 0.04730589
## 4  5.00 0.18500 0.04073969
## 5 10.00 0.18375 0.03682259
oj.svm.rad2 = svm(Purchase~., data = oj.train, kernel = "radial", cost = 1)
summary(oj.svm.rad2)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj.train, kernel = "radial", 
##     cost = 1)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  1 
## 
## Number of Support Vectors:  381
## 
##  ( 194 187 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
#training error
oj.train.rad.pred2 = predict(oj.svm.rad2, oj.train)
table(oj.train$Purchase, oj.train.rad.pred2)
##     oj.train.rad.pred2
##       CH  MM
##   CH 433  51
##   MM  75 241
(51+75)/800
## [1] 0.1575
#test error
oj.test.rad.pred2 = predict(oj.svm.rad2, oj.test)
table(oj.test$Purchase, oj.test.rad.pred2)
##     oj.test.rad.pred2
##       CH  MM
##   CH 158  11
##   MM  29  72
(11+29)/270
## [1] 0.1481481

(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
For the Polynomial SVM with a degree equal to 2, 637 Support Vectors were used. 321 are classified as CH and 316 are classified as MM. The training error for this model is 39.3% and the test error is 37.4%.
After tuning the Polynomial SVM, the best Cost Value is 5 with an error of 0.18625. In this model, 374 Support Vectors were used with 190 classified as CH and 184 classified as MM. The training error for this model is 16.3%, and the test error of 14.89%.

oj.svm.poly = svm(Purchase~., data = oj.train, kernel = "poly", cost = 0.01, degree = 2)
summary(oj.svm.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj.train, kernel = "poly", 
##     cost = 0.01, degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  0.01 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  637
## 
##  ( 321 316 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
#training error
oj.poly.train.pred = predict(oj.svm.poly, oj.train)
table(oj.train$Purchase, oj.poly.train.pred)
##     oj.poly.train.pred
##       CH  MM
##   CH 484   0
##   MM 315   1
(315/800)
## [1] 0.39375
#test error
oj.poly.test.pred = predict(oj.svm.poly, oj.test)
table(oj.test$Purchase, oj.poly.test.pred)
##     oj.poly.test.pred
##       CH  MM
##   CH 169   0
##   MM 101   0
(101/270)
## [1] 0.3740741
#tuning
set.seed(1234)
oj.poly.tune = tune(svm, Purchase~., data = oj.train, kernel = "poly", ranges = list(cost=c(0.01, 0.1, 1, 5, 10)), degree = 2)
summary(oj.poly.tune)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     5
## 
## - best performance: 0.18625 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.39625 0.03910900
## 2  0.10 0.32875 0.01671867
## 3  1.00 0.20875 0.01772671
## 4  5.00 0.18625 0.04059026
## 5 10.00 0.19000 0.04073969
oj.svm.poly2 = svm(Purchase~., data = oj.train, kernel = "poly", cost = 5, degree = 2)
summary(oj.svm.poly2)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj.train, kernel = "poly", 
##     cost = 5, degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  5 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  374
## 
##  ( 190 184 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
#training error
oj.train.poly.pred2 = predict(oj.svm.poly2, oj.train)
table(oj.train$Purchase, oj.train.poly.pred2)
##     oj.train.poly.pred2
##       CH  MM
##   CH 441  43
##   MM  88 228
(43+88)/800
## [1] 0.16375
#test error
oj.test.poly.pred2 = predict(oj.svm.poly2, oj.test)
table(oj.test$Purchase, oj.test.poly.pred2)
##     oj.test.poly.pred2
##       CH  MM
##   CH 161   8
##   MM  35  66
(8+35)/270
## [1] 0.1592593

(h) Overall, which approach seems to give the best results on this data?
The Tuned Polynomial SVM with Cost = and Degree = 2 results in the lowest test error of 14.89% for the OJ data set.