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.

set.seed(32)
x1 = runif(500)-0.5
x2 = runif(500)-0.5
y = 1*(x1^2 - x2^2 > 0 )
#x1[1:30]
#x2[1:30]

(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,col = ifelse(y,'black','red'))

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

glm.fit = glm(y~. ,family = 'binomial', data = data.frame(x1,x2,y))
summary(glm.fit)
## 
## Call:
## glm(formula = y ~ ., family = "binomial", data = data.frame(x1, 
##     x2, y))
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.345  -1.187   1.039   1.150   1.309  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  0.02536    0.08981   0.282    0.778
## x1          -0.45362    0.31125  -1.457    0.145
## x2          -0.27891    0.30938  -0.901    0.367
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 693.02  on 499  degrees of freedom
## Residual deviance: 689.98  on 497  degrees of freedom
## AIC: 695.98
## 
## 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.pred = predict(glm.fit,data.frame(x1,x2))  
plot(x1,x2,col = ifelse(glm.pred > 0,'black','red'),
     pch = ifelse(as.integer(glm.pred > 0) == y,1,4))

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

glm.fit = glm(y~poly(x1,2) + poly(x2,2) ,family = 'binomial', data = data.frame(x1,x2,y))
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm.fit)
## 
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2), family = "binomial", 
##     data = data.frame(x1, x2, y))
## 
## Deviance Residuals: 
##        Min          1Q      Median          3Q         Max  
## -2.796e-03  -2.000e-08   2.000e-08   2.000e-08   2.723e-03  
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)
## (Intercept)      -79.49    1950.17  -0.041    0.967
## poly(x1, 2)1   -5445.42  109702.57  -0.050    0.960
## poly(x1, 2)2   63255.47 1102254.75   0.057    0.954
## poly(x2, 2)1   -1420.55   74675.96  -0.019    0.985
## poly(x2, 2)2  -66751.06 1166265.91  -0.057    0.954
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9302e+02  on 499  degrees of freedom
## Residual deviance: 1.5728e-05  on 495  degrees of freedom
## AIC: 10
## 
## 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.

glm.pred = predict(glm.fit,data.frame(x1,x2)) 
plot(x1,x2,col = ifelse(glm.pred > 0,'black','red'),
     pch = ifelse(as.integer(glm.pred > 0) == y,1,4))

(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(y~.,data=data.frame(x1,x2,y=as.factor(y)),kernel='linear')
svm.pred=predict(svm.fit,data.frame(x1,x2),type='response')
plot(x1,x2,col=ifelse(svm.pred!=0,'black','red'),pch=ifelse(svm.pred == y,1,4))

(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(y~.,data=data.frame(x1,x2,y=as.factor(y)),kernel="radial", gamma = 1, cost = 1)
svm.pred=predict(svm.fit,data.frame(x1,x2),type='response')
plot(x1,x2,col=ifelse(svm.pred!=0,'black','red'),pch=ifelse(svm.pred == y,1,4))

(i) Comment on your results.

After going through this process, using linear classifiers seemed to produce the least accurate results. From the plots nonlinear classification plots it seems like the polynomial logit model performs, by a slight margin, better than an SVM with a radial kernel on the training data. Both of the nonlinear classifying models significantly improved the performance compared to the linear classifiers.

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(ISLR)
attach(Auto)
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.

set.seed(1)
tune.out=tune(svm,mpglevel~.,data = Auto,kernel ="linear",
              ranges=list(cost=c(0.001,0.01,0.1,1,5,10,100)))
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-03 0.09442308 0.04519425
## 2 1e-02 0.07653846 0.03617137
## 3 1e-01 0.04596154 0.03378238
## 4 1e+00 0.01025641 0.01792836
## 5 5e+00 0.02051282 0.02648194
## 6 1e+01 0.02051282 0.02648194
## 7 1e+02 0.03076923 0.03151981
bestmod=tune.out$best.model
summary(bestmod)
## 
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, ranges = list(cost = c(0.001, 
##     0.01, 0.1, 1, 5, 10, 100)), kernel = "linear")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  1 
## 
## Number of Support Vectors:  56
## 
##  ( 26 30 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  0 1

According to the above results the lowest cross-validation error rate, which is 0.01025641, occurs when Cost is 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.

#polynomial based
set.seed(1)
tune.out1 = 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.out1)
## 
## 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
#radial based
set.seed(1)
tune.out2 = tune(svm,mpglevel~.,data = Auto, kernel ="radial",
ranges = list(cost=c(0.1,1,10,100,1000),gamma=c(0.5,1,2,3,4)))
summary(tune.out2)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##    10   0.5
## 
## - best performance: 0.04865385 
## 
## - Detailed performance results:
##     cost gamma      error dispersion
## 1  1e-01   0.5 0.07910256 0.04234351
## 2  1e+00   0.5 0.05115385 0.02716416
## 3  1e+01   0.5 0.04865385 0.03075209
## 4  1e+02   0.5 0.05121795 0.03424201
## 5  1e+03   0.5 0.05121795 0.03424201
## 6  1e-01   1.0 0.55115385 0.04366593
## 7  1e+00   1.0 0.06384615 0.04375618
## 8  1e+01   1.0 0.05884615 0.04020934
## 9  1e+02   1.0 0.05884615 0.04020934
## 10 1e+03   1.0 0.05884615 0.04020934
## 11 1e-01   2.0 0.55115385 0.04366593
## 12 1e+00   2.0 0.14019231 0.07984711
## 13 1e+01   2.0 0.13512821 0.08055403
## 14 1e+02   2.0 0.13512821 0.08055403
## 15 1e+03   2.0 0.13512821 0.08055403
## 16 1e-01   3.0 0.55115385 0.04366593
## 17 1e+00   3.0 0.41326923 0.14331350
## 18 1e+01   3.0 0.38025641 0.14908523
## 19 1e+02   3.0 0.38025641 0.14908523
## 20 1e+03   3.0 0.38025641 0.14908523
## 21 1e-01   4.0 0.55115385 0.04366593
## 22 1e+00   4.0 0.47705128 0.05783758
## 23 1e+01   4.0 0.47705128 0.06151011
## 24 1e+02   4.0 0.47705128 0.06151011
## 25 1e+03   4.0 0.47705128 0.06151011

According to the above results the the lowest cross-validation error rate for the polynomial based SVM, which is 0.3013462, occurs at a cost = 100 and degree = 2. Furthermore, the lowest cross-validation error rate for the radial based SVM, which is 0.04865385, occurs at a cost = 10 and gamma = 0.5. When considering the combination of a low error rate and low cost, it appears the linear based classifier is still significantly outperforming the radial or polynomil based svms, wit a Cost of 1 and a cross validation error of 0.01025641. The plots below should reflect this.

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

Linear kernel SVM Plot

#Linear SVM Plot
svm.line = svm(mpglevel~., data = Auto, kernel = "linear", cost = 1)
plot(svm.line, Auto, mpg~year)

plot(svm.line, Auto, mpg~acceleration)

plot(svm.line, Auto, mpg~horsepower)

plot(svm.line, Auto, mpg~weight)

Polynomial kernel SVM Plot

svm.pol = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 100, degree = 2)
plot(svm.pol, Auto, mpg~year)

plot(svm.pol, Auto, mpg~acceleration)

plot(svm.pol, Auto, mpg~horsepower)

plot(svm.pol, Auto, mpg~weight)

Radial kernel SVM Plot

svm.rad = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 10, gamma = 0.5)
plot(svm.rad, Auto, mpg~year)

plot(svm.rad, Auto, mpg~acceleration)

plot(svm.rad, Auto, mpg~horsepower)

plot(svm.rad, Auto, mpg~weight)

So, to reiterate, the only qualifiable set of graphs that demonstrate a good performance are the first 4, which were generated from the linear classifer. Everything else has x’s and o’s classified all over the place, which isn’t preferable.

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

attach(OJ)
set.seed(2)
train = sample(1: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.line2 = svm(Purchase ~ ., data = oj.train,  kernel = "linear", cost = 0.01)
summary(svm.line2)
## 
## 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:  426
## 
##  ( 212 214 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

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

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

train.pred = predict(svm.line2, oj.train)
table(oj.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 430  60
##   MM  73 237
test.pred = predict(svm.line2, oj.test)
table(oj.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 144  19
##   MM  33  74
train_error = 133/800
test_error = 52/270
train_error
## [1] 0.16625
test_error
## [1] 0.1925926

The training error appears to be 0.16625 and the test error appears to be 0.1925926

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

set.seed(1)
tune.out=tune(svm,Purchase~.,data = OJ,kernel ="linear",
              ranges=list(cost=c(0.01,0.1,0.5,1,5,10)))
summary(tune.out) 
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.1626168 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1  0.01 0.1691589 0.04024604
## 2  0.10 0.1663551 0.03984617
## 3  0.50 0.1682243 0.03606180
## 4  1.00 0.1626168 0.03945456
## 5  5.00 0.1654206 0.03917066
## 6 10.00 0.1682243 0.03865942

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

svm.line3 = svm(Purchase~., data = OJ, kernel = "linear", cost = 1)
train.pred = predict(svm.line3, oj.train)
table(oj.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 433  57
##   MM  71 239
test.pred = predict(svm.line3, oj.test)
table(oj.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 146  17
##   MM  27  80
train_error2 = 128/800
test_error2 = 44/270
train_error2
## [1] 0.16
test_error2
## [1] 0.162963

According to the above results, when applying a cost = 1 instead of 0.01, a lower training error and test error are produced, which are now both respectively 0.16 and 0.162963.

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

svm.rad2 = svm(Purchase ~ ., kernel = "radial", data = oj.train, cost = 0.01)
summary(svm.rad2)
## 
## 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:  623
## 
##  ( 310 313 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred = predict(svm.rad2, oj.train)
table(oj.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 490   0
##   MM 310   0
test.pred = predict(svm.rad2, oj.test)
table(oj.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 163   0
##   MM 107   0
train_error = 310/800
test_error = 107/270
train_error
## [1] 0.3875
test_error
## [1] 0.3962963

The training error appears to be 0.3875 and the test error appears to be 0.3962963.

set.seed(1)
tune.out=tune(svm,Purchase~.,data = OJ,kernel ="radial",
              ranges=list(cost=c(0.01,0.1,0.5,1,5,10)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##   0.5
## 
## - best performance: 0.1654206 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1  0.01 0.3897196 0.05138771
## 2  0.10 0.1794393 0.03573740
## 3  0.50 0.1654206 0.04450579
## 4  1.00 0.1700935 0.03519008
## 5  5.00 0.1757009 0.03600793
## 6 10.00 0.1728972 0.03447966
svm.rad3 = svm(Purchase ~ ., kernel = "radial", data = oj.train, cost = 0.5)
train.pred = predict(svm.rad3, oj.train)
table(oj.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 447  43
##   MM  67 243
test.pred = predict(svm.rad3, oj.test)
table(oj.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 145  18
##   MM  35  72
train_error = 110/800
test_error = 53/270
train_error
## [1] 0.1375
test_error
## [1] 0.1962963

According to the above results, when applying a cost = 0.5 instead of 0.01, a lower training error and test error are produced, which are now both respectively 0.1375 and 0.1962963.

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

svm.poly2 = svm(Purchase~., data = oj.train, kernel = "poly", cost = 0.01, degree = 2)
summary(svm.poly2)
## 
## 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:  624
## 
##  ( 310 314 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred = predict(svm.poly2, oj.train)
table(oj.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 489   1
##   MM 292  18
test.pred = predict(svm.poly2, oj.test)
table(oj.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 162   1
##   MM 100   7
train_error = 293/800
test_error = 101/270
train_error
## [1] 0.36625
test_error
## [1] 0.3740741

The training error appears to be 0.36625 and the test error appears to be 0.3740741

set.seed(1)
tune.out=tune(svm,Purchase~.,data = OJ,kernel ="polynomial", degree = 2,
              ranges=list(cost=c(0.01,0.1,0.5,1,5,10)))
summary(tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##    10
## 
## - best performance: 0.1728972 
## 
## - Detailed performance results:
##    cost     error dispersion
## 1  0.01 0.3691589 0.04625932
## 2  0.10 0.2981308 0.05510586
## 3  0.50 0.2028037 0.03553314
## 4  1.00 0.1925234 0.03332023
## 5  5.00 0.1803738 0.04406751
## 6 10.00 0.1728972 0.03770629
svm.poly3 = svm(Purchase~., data = oj.train, kernel = "poly", cost = 10, degree = 2)
summary(svm.poly3)
## 
## Call:
## svm(formula = Purchase ~ ., data = oj.train, kernel = "poly", cost = 10, 
##     degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  10 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  329
## 
##  ( 163 166 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred = predict(svm.poly3, oj.train)
table(oj.train$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 452  38
##   MM  66 244
test.pred = predict(svm.poly3, oj.test)
table(oj.test$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 141  22
##   MM  32  75
train_error = 104/800
test_error = 54/270
train_error
## [1] 0.13
test_error
## [1] 0.2

According to the above results, when applying a cost = 10 instead of 0.01, a lower training error and test error are produced, which are now both respectively 0.13 and 0.2.

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

When considering all of the approaches, it appears that the svm using a linear based kernel with a cost = 1 is producing the lowest test error, at a value of 0.162963, thus producing the best results.