Q4

Generate a simulated two-class data set with 100 observations and two features in which there is a visible but non-linear separation between the two classes. Show that in this setting, a support vector machine with a polynomial kernel (with degree greater than 1) or a radial kernel will outperform a support vector classifier on the training data. Which technique performs best on test data ? Make plots and report training and test error rates in order to back up your assertions.

  1. Creating a data set with non-linear separation between the two classes.
library(ISLR)
library(e1071)
set.seed(1)
x = rnorm(100)
y = 4*x^2+1+rnorm(100)
class = sample(100,50)
y[class] = y[class] + 3
y[-class] = y[-class] - 3
plot(x[class],y[class],col="red",xlab="X",ylab="Y",ylim=c(-6,30))
points(x[-class],y[-class],col="blue")

  1. Fit a support vector classifier on the training data.
z = rep(-1,100)
z[class] = 1
data = data.frame(x=x,y=y,z=as.factor(z))
train = sample(100,50)
data.train = data[train,]
data.test = data[-train,]
svm.linear = svm(z~.,data=data.train,kernel="linear",cost=10)
plot(svm.linear,data.train)

table(predict=predict(svm.linear,data.train),truth=data.train$z)
##        truth
## predict -1  1
##      -1 22  0
##      1   3 25

The support vector classifier makes 3 errors on the training data.

  1. Fit a support vector machine with a polynomial kernel.
svm.poly = svm(z~.,data=data.train,kernel="polynomial",cost=10)
plot(svm.poly,data.train)

table(predict = predict(svm.poly, data.train), truth = data.train$z)
##        truth
## predict -1  1
##      -1 21  0
##      1   4 25

The support vector machine with a polynomial kernel of degree 3 makes 4 errors on the training data.

  1. Fit a support vector machine with a radial kernel and a gamma of 1.
svm.radial = svm(z~.,data=data.train,kernel="radial",gamma=1,cost=10)
plot(svm.radial,data.train)

table(predict = predict(svm.radial, data.train), truth = data.train$z)
##        truth
## predict -1  1
##      -1 25  0
##      1   0 25

The support vector machine with a radial kernel makes 0 error on the training data.

  1. Now, we check how these models fare when applied to the test data.
plot(svm.linear,data.test)

table(predict = predict(svm.linear, data.test), truth = data.test$z)
##        truth
## predict -1  1
##      -1 18  0
##      1   7 25
plot(svm.poly, data.test)

table(predict = predict(svm.poly, data.test), truth = data.test$z)
##        truth
## predict -1  1
##      -1 18  0
##      1   7 25
plot(svm.radial, data.test)

table(predict = predict(svm.radial, data.test), truth = data.test$z)
##        truth
## predict -1  1
##      -1 19  0
##      1   6 25

We may see that the linear, polynomial and radial support vector machines classify respectively 7, 7 and 6 observations incorrectly. So, radial kernel is the best model in this setting.

Q5

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. Your plot should display \(X_1\) on the x-axis and \(X_2\) on the y-axis.

plot(x1,x2,xlab="X1",ylab="X2",col=(4-y),pch=(3-y))

c.Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.

library(glmnet)
## 载入需要的程辑包:Matrix
## Loaded glmnet 4.1-1
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.179  -1.139  -1.112   1.206   1.257  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.087260   0.089579  -0.974    0.330
## x1           0.196199   0.316864   0.619    0.536
## x2          -0.002854   0.305712  -0.009    0.993
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 692.18  on 499  degrees of freedom
## Residual deviance: 691.79  on 497  degrees of freedom
## AIC: 697.79
## 
## Number of Fisher Scoring iterations: 3

None of the variables are statistically significants.

d.Apply this model to 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))

The decision boundary is obviously linear.

e.Now fit a logistic regression model to the data using non-linear functions of \(X_1\) and \(X_2\) as predictors.

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  
## -8.240e-04  -2.000e-08  -2.000e-08   2.000e-08   1.163e-03  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept)    -102.2     4302.0  -0.024    0.981
## poly(x1, 2)1   2715.3   141109.5   0.019    0.985
## poly(x1, 2)2  27218.5   842987.2   0.032    0.974
## poly(x2, 2)1   -279.7    97160.4  -0.003    0.998
## poly(x2, 2)2 -28693.0   875451.3  -0.033    0.974
## I(x1 * x2)     -206.4    41802.8  -0.005    0.996
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9218e+02  on 499  degrees of freedom
## Residual deviance: 3.5810e-06  on 494  degrees of freedom
## AIC: 12
## 
## Number of Fisher Scoring iterations: 25

Here again, none of the variables are statistically significants.

f.Apply this model to 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 obviously be 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))

The non-linear decision boundary is surprisingly very similar to the true decision boundary.

g.Fit a support vector classifier to the data with \(X_1\) and \(X_2\) 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)
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))

This support vector classifier (even with low cost) classifies all points to a single class.

h.Fit a SVM using a non-linear kernel to the data with \(X_1\) and \(X_2\) 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)
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))

Here again, the non-linear decision boundary is surprisingly very similar to the true decision boundary.

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. Also, SVM with linear kernel and logistic regression without any interaction term are very bad when it comes to finding non-linear decision boundaries. However, one argument in favor of SVM is that it requires some manual tuning to find the right interaction terms when using logistic regression, although when using SVM we only need to tune gamma.

Q6

At the end of Section 9.6.1, it is claimed that in the case of data that is just barely linearly separable, a support vector classifier with a small value of “cost” that misclassifies a couple of training observations may perform better on test data than one with a huge value of “cost” that does not misclassify any training observations. You will now investigate that claim.

a.Generate two-class data with p=2 in such a way that the classes are just barely linearly separable.

We randomly generate 1000 points and scatter them across line \(x=y\) with wide margin. We also create noisy points along the line \(5x−4y−50=0\). These points make the classes barely separable and also shift the maximum margin classifier.

set.seed(1)
x.one = runif(500,0,90)
y.one = runif(500,x.one+10,100)
x.one.noise = runif(50,20,80)
y.one.noise = 5/4*(x.one.noise-10)+0.1

x.zero = runif(500,10,100)
y.zero = runif(500,0,x.zero-10)
x.zero.noise = runif(50,20,80)
y.zero.noise = 5/4*(x.zero.noise-10)-0.1

class.one = seq(1,550)
x = c(x.one,x.one.noise,x.zero,x.zero.noise)
y = c(y.one,y.one.noise,y.zero,y.zero.noise)

plot(x[class.one],y[class.one],col="blue",pch="+",ylim=c(0,100))
points(x[-class.one],y[-class.one],col="red",pch=4)

b.Compute the cross-validation error rates for support vector classifiers with a range of “cost” values. How many training errors are misclassified for each value of “cost” considered, and how does this relate to the cross-validation errors obtained ?

set.seed(2)
z = rep(0,1100)
z[class.one] = 1
data = data.frame(x=x,y=y,z=as.factor(z))
tune.out = tune(svm,z~.,data=data,kernel="linear",
                ranges=list(cost=c(0.01,0.1,1,5,10,100,1000,10000)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##   cost
##  10000
## 
## - best performance: 0 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.06181818 0.03201239
## 2 1e-01 0.04818182 0.02101641
## 3 1e+00 0.04818182 0.02101641
## 4 5e+00 0.05000000 0.02153435
## 5 1e+01 0.05000000 0.02153435
## 6 1e+02 0.05272727 0.02259558
## 7 1e+03 0.04636364 0.03467016
## 8 1e+04 0.00000000 0.00000000

A cost of 10000 seems the best choice of parameter.

data.frame(cost=tune.out$performances$cost,
           misclass=tune.out$performances$error*1100)
##    cost misclass
## 1 1e-02       68
## 2 1e-01       53
## 3 1e+00       53
## 4 5e+00       55
## 5 1e+01       55
## 6 1e+02       58
## 7 1e+03       51
## 8 1e+04        0

Here a cost of 10000 classify all training points correctly.

c.Generate an appropriate test data set, and compute the test errors corresponding to each of the values of “cost” considered. Which value of “cost” leads to the values of “cost” that yield the fewest training errors and the fewest cross-validation errors ?

x.test <- runif(1000, 0, 100)
class.one <- sample(1000, 500)
y.test <- rep(NA, 1000)

# Set y > x for class.one
for (i in class.one){
  y.test[i] = runif(1,x.test[i],100)
}

# set y < x for class.zero
for (i in setdiff(1:1000, class.one)) {
    y.test[i] = runif(1, 0, x.test[i])
}

plot(x.test[class.one], y.test[class.one], col = "blue", pch = "+")
points(x.test[-class.one], y.test[-class.one], col = "red", pch = 4)

set.seed(3)
z.test = rep(0,1000)
z.test[class.one] = 1
data.test = data.frame(x=x.test,y=y.test,z=as.factor(z.test))
costs = c(0.01,0.1,1,5,10,100,1000,10000)
test.err = rep(NA,length(costs))
for (i in 1:length(costs)){
  svm.fit = svm(z~.,data=data,kernel="linear",cost=costs[i])
  pred = predict(svm.fit,data.test)
  test.err[i] = sum(pred!=data.test$z)
}
data.frame(cost=costs,misclass=test.err)
##    cost misclass
## 1 1e-02       61
## 2 1e-01       20
## 3 1e+00        2
## 4 5e+00        0
## 5 1e+01        0
## 6 1e+02      191
## 7 1e+03      209
## 8 1e+04      212

Costs of 1, 5 or 10 seem to perform better on test observations, this is much smaller than the value of 10000 for training observations.

d.Discuss your results.

We again see an overfitting phenomenon for linear kernel. A large cost tries to correctly classify noisy-points and hence overfits the train data. A small cost, however, makes a few errors on the noisy test points and performs better on test data.

Q7

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)
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 of low gas mileage. Report the cross-validation errors associated with different values of this parameter. Comment on your results.

set.seed(1)
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.01025641 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.07653846 0.03617137
## 2 1e-01 0.04596154 0.03378238
## 3 1e+00 0.01025641 0.01792836
## 4 5e+00 0.02051282 0.02648194
## 5 1e+01 0.02051282 0.02648194
## 6 1e+02 0.03076923 0.03151981
## 7 1e+03 0.03076923 0.03151981

A cost of 1seems 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.

set.seed(1)
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.3013462 
## 
## - Detailed performance results:
##     cost degree     error dispersion
## 1  1e-02      2 0.5511538 0.04366593
## 2  1e-01      2 0.5511538 0.04366593
## 3  1e+00      2 0.5511538 0.04366593
## 4  5e+00      2 0.5511538 0.04366593
## 5  1e+01      2 0.5130128 0.08963366
## 6  1e+02      2 0.3013462 0.09961961
## 7  1e-02      3 0.5511538 0.04366593
## 8  1e-01      3 0.5511538 0.04366593
## 9  1e+00      3 0.5511538 0.04366593
## 10 5e+00      3 0.5511538 0.04366593
## 11 1e+01      3 0.5511538 0.04366593
## 12 1e+02      3 0.3446154 0.09821588
## 13 1e-02      4 0.5511538 0.04366593
## 14 1e-01      4 0.5511538 0.04366593
## 15 1e+00      4 0.5511538 0.04366593
## 16 5e+00      4 0.5511538 0.04366593
## 17 1e+01      4 0.5511538 0.04366593
## 18 1e+02      4 0.5511538 0.04366593

For a polynomial kernel, the lowest cross-validation error is obtained for a degree of 2 and a cost of 100.

set.seed(1)
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.01282051 
## 
## - Detailed performance results:
##     cost gamma      error dispersion
## 1  1e-02 1e-02 0.55115385 0.04366593
## 2  1e-01 1e-02 0.08929487 0.04382379
## 3  1e+00 1e-02 0.07403846 0.03522110
## 4  5e+00 1e-02 0.04852564 0.03303346
## 5  1e+01 1e-02 0.02557692 0.02093679
## 6  1e+02 1e-02 0.01282051 0.01813094
## 7  1e-02 1e-01 0.21711538 0.09865227
## 8  1e-01 1e-01 0.07903846 0.03874545
## 9  1e+00 1e-01 0.05371795 0.03525162
## 10 5e+00 1e-01 0.02820513 0.03299190
## 11 1e+01 1e-01 0.03076923 0.03375798
## 12 1e+02 1e-01 0.03583333 0.02759051
## 13 1e-02 1e+00 0.55115385 0.04366593
## 14 1e-01 1e+00 0.55115385 0.04366593
## 15 1e+00 1e+00 0.06384615 0.04375618
## 16 5e+00 1e+00 0.05884615 0.04020934
## 17 1e+01 1e+00 0.05884615 0.04020934
## 18 1e+02 1e+00 0.05884615 0.04020934
## 19 1e-02 5e+00 0.55115385 0.04366593
## 20 1e-01 5e+00 0.55115385 0.04366593
## 21 1e+00 5e+00 0.49493590 0.04724924
## 22 5e+00 5e+00 0.48217949 0.05470903
## 23 1e+01 5e+00 0.48217949 0.05470903
## 24 1e+02 5e+00 0.48217949 0.05470903
## 25 1e-02 1e+01 0.55115385 0.04366593
## 26 1e-01 1e+01 0.55115385 0.04366593
## 27 1e+00 1e+01 0.51794872 0.05063697
## 28 5e+00 1e+01 0.51794872 0.04917316
## 29 1e+01 1e+01 0.51794872 0.04917316
## 30 1e+02 1e+01 0.51794872 0.04917316
## 31 1e-02 1e+02 0.55115385 0.04366593
## 32 1e-01 1e+02 0.55115385 0.04366593
## 33 1e+00 1e+02 0.55115385 0.04366593
## 34 5e+00 1e+02 0.55115385 0.04366593
## 35 1e+01 1e+02 0.55115385 0.04366593
## 36 1e+02 1e+02 0.55115385 0.04366593

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)

Q8

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.

library(ISLR)
set.seed(1)
train = sample(nrow(OJ),800) #800个1到1070随机数
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:  435
## 
##  ( 219 216 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

Support vector classifier creates 432 support vectors out of 800 training points. Out of these, 216 belong to level MM and remaining 219 belong to level CH.

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 420  65
##   MM  75 240
(65+75)/800
## [1] 0.175
test.pred = predict(svm.linear,OJ.test)
table(OJ.test$Purchase,test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  33  69
(33+15)/(153+15+33+69)
## [1] 0.1777778

The training error rate is 17.5% and test error rate is about 17.8%.

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

set.seed(2)
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
##  1.778279
## 
## - best performance: 0.1675 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.17625 0.04059026
## 2   0.01778279 0.17625 0.04348132
## 3   0.03162278 0.17125 0.04604120
## 4   0.05623413 0.17000 0.04005205
## 5   0.10000000 0.17125 0.04168749
## 6   0.17782794 0.17000 0.04090979
## 7   0.31622777 0.17125 0.04411554
## 8   0.56234133 0.17125 0.04084609
## 9   1.00000000 0.17000 0.04090979
## 10  1.77827941 0.16750 0.03782269
## 11  3.16227766 0.16750 0.03782269
## 12  5.62341325 0.16750 0.03545341
## 13 10.00000000 0.17000 0.03736085

We may see that the optimal cost is 1.778279.

e.Compute the training and test error rates using this new value for “cost”.

svm.linear = svm(Purchase~.,data=OJ.train,kernel="linear",
                 cost=tune.out$best.parameters$cost)
train.pred = predict(svm.linear,OJ.train)
test.pred = predict(svm.linear,OJ.test)
table(OJ.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 423  62
##   MM  69 246
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 156  12
##   MM  29  73
(62+69)/(423+62+69+246) # Training error rate
## [1] 0.16375
(12+29)/(156+12+29+73) # Test error rate
## [1] 0.1518519

We may see that, with the best cost, the training error rate is now 16.4% and the test error rate is 15.2%.

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~.,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:  373
## 
##  ( 188 185 )
## 
## 
## 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 441  44
##   MM  77 238
test.pred = predict(svm.radial,OJ.test)
table(OJ.test$Purchase,test.pred)
##     test.pred
##       CH  MM
##   CH 151  17
##   MM  33  69
(44+77)/(441+44+77+238) # Training error rate
## [1] 0.15125
(17+33)/(151+17+33+69) # Test error rate
## [1] 0.1851852

Radial kernel with default gamma creates 373 support vectors, out of which, 188 belong to level CH and remaining 185 belong to level MM. The classifier has a training error of 15.1% and a test error of 18.5% which is not a improvement over linear kernel. We now use cross validation to find optimal cost.

set.seed(2)
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
##     1
## 
## - best performance: 0.1725 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39375 0.03240906
## 2   0.01778279 0.39375 0.03240906
## 3   0.03162278 0.34750 0.05552777
## 4   0.05623413 0.19250 0.03016160
## 5   0.10000000 0.19500 0.03782269
## 6   0.17782794 0.18000 0.04048319
## 7   0.31622777 0.17250 0.03809710
## 8   0.56234133 0.17500 0.04124790
## 9   1.00000000 0.17250 0.03162278
## 10  1.77827941 0.17750 0.03717451
## 11  3.16227766 0.18375 0.03438447
## 12  5.62341325 0.18500 0.03717451
## 13 10.00000000 0.18750 0.03173239

The optimal cost is 1.

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

svm.poly = svm(Purchase~.,data=OJ.train,kernel="polynomial",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:  447
## 
##  ( 225 222 )
## 
## 
## 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 449  36
##   MM 110 205
test.pred = predict(svm.poly,OJ.test)
table(OJ.test$Purchase,test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  45  57
(110+36)/(449+36+110+205)  # Training error rate
## [1] 0.1825
(43+15)/(153+15+43+57) # Test error rate
## [1] 0.2164179

Polynomial kernel with default gamma creates 447 support vectors, out of which, 225 belong to level CH and remaining 222 belong to level MM. The classifier has a training error of 18.3% and a test error of 21.6% which is no improvement over linear kernel. We now use cross validation to find optimal cost.

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.18125 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39250 0.04216370
## 2   0.01778279 0.36750 0.04456581
## 3   0.03162278 0.36375 0.04348132
## 4   0.05623413 0.33625 0.04910660
## 5   0.10000000 0.31750 0.04533824
## 6   0.17782794 0.23250 0.04609772
## 7   0.31622777 0.19875 0.02531057
## 8   0.56234133 0.20375 0.03910900
## 9   1.00000000 0.19500 0.03872983
## 10  1.77827941 0.18875 0.03251602
## 11  3.16227766 0.18500 0.03670453
## 12  5.62341325 0.18125 0.03784563
## 13 10.00000000 0.19125 0.04041881
svm.poly = svm(Purchase~.,data=OJ.train,kernel="polynomial",
               degree=2,cost=tune.out$best.parameters$cost)
summary(svm.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "polynomial", 
##     degree = 2, cost = tune.out$best.parameters$cost)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  5.623413 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  361
## 
##  ( 182 179 )
## 
## 
## 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 447  38
##   MM  88 227
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 154  14
##   MM  36  66
train.err = (88+38)/(447+38+88+227)
test.err = (14+36)/(154+14+36+66)
train.err
## [1] 0.1575
test.err
## [1] 0.1851852

Tuning reduce train and test error rates.

h.Overall, which approach seems to give the best results on this data ? Overall, support vector classifier with the cost value of 1.778279. seems to be producing minimum misclassification error on both train and test data.