Exercise 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(350)

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.

dt = data.table(y = as.factor(y), x1=x1, x2=x2)
ggplot(dt, aes(x=x1, y=x2, col=y)) + geom_point()

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

log.fit = glm(y ~ x1 + x2, family = binomial)
summary(log.fit)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.252  -1.141  -1.048   1.183   1.344  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.08878    0.08992  -0.987    0.323
## x1          -0.41667    0.31890  -1.307    0.191
## x2          -0.19655    0.30577  -0.643    0.520
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 692.35  on 499  degrees of freedom
## Residual deviance: 690.25  on 497  degrees of freedom
## AIC: 696.25
## 
## 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.

log.prob = predict(log.fit, dt, type="response")
log.pred = ifelse(log.prob > 0.42, 1, 0)
ggplot(data.table(x1=dt$x1, x2=dt$x2, pred = as.factor(log.pred)), aes(x=x1,y=x2,col=pred)) + geom_point()

(E) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X12, X1 ×X2, log(X2), and so forth).

log.nl.fit = glm(y ~ poly(x1, 2) + poly(x2, 2), family = binomial)
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(log.nl.fit)
## 
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2), family = binomial)
## 
## Deviance Residuals: 
##        Min          1Q      Median          3Q         Max  
## -1.526e-03  -2.000e-08  -2.000e-08   2.000e-08   1.385e-03  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept)    -128.9     3502.8  -0.037    0.971
## poly(x1, 2)1   -270.4    53518.5  -0.005    0.996
## poly(x1, 2)2  37001.3   933292.5   0.040    0.968
## poly(x2, 2)1  -1806.8    66665.3  -0.027    0.978
## poly(x2, 2)2 -37764.0   952310.2  -0.040    0.968
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9235e+02  on 499  degrees of freedom
## Residual deviance: 5.8784e-06  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.

log.nl.prob = predict(log.nl.fit, dt, type="response")
log.nl.pred = ifelse(log.nl.prob > 0.5, 1, 0)
ggplot(data.table(x1=dt$x1, x2=dt$x2, pred = as.factor(log.nl.pred)), aes(x=x1,y=x2,col=pred)) + geom_point()

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

svm.fit = svm(as.factor(y) ~ x1 + x2, dt, kernel = "linear", cost = 1)
svm.pred = predict(svm.fit, dt)
ggplot(data.table(x1=dt$x1, x2=dt$x2, pred = as.factor(svm.pred)), aes(x=x1,y=x2,col=pred)) + geom_point()

(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.nl.fit = svm(as.factor(y) ~ x1 + x2, dt, kernel = "polynomial", cost = 1, gamma=1)
svm.nl.pred = predict(svm.nl.fit, dt)
ggplot(data.table(x1=dt$x1, x2=dt$x2, pred = as.factor(svm.nl.pred)), aes(x=x1,y=x2,col=pred)) + geom_point()

(I) Comment on your results.

The logistic regression with non-interactions and SVM with a non-linear kernel failed to find a decision boundary. The SVM with a linear kernel did a good job of a decision boundary in this instance.

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

data("cars")
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(789)
linear.tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100, 1000)))
summary(linear.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.07923077 0.04919099
## 2 1e-01 0.04339744 0.02974011
## 3 1e+00 0.01025641 0.01324097
## 4 5e+00 0.01532051 0.01318724
## 5 1e+01 0.01532051 0.01318724
## 6 1e+02 0.03051282 0.01586155
## 7 1e+03 0.03051282 0.01586155

The tuning process used a 10-fold cross validation sampling method with sthe upplied seven values for cost. The results indicate that the lowest cross-validation error rate is obtained when cost=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.

set.seed(789)
poly.tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), degree = c(1,10,100,1000)))
summary(poly.tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##   100      1
## 
## - best performance: 0.02294872 
## 
## - Detailed performance results:
##     cost degree      error dispersion
## 1  1e-02      1 0.56397436 0.05244480
## 2  1e-01      1 0.19929487 0.09755506
## 3  1e+00      1 0.08179487 0.04823119
## 4  5e+00      1 0.07410256 0.04448059
## 5  1e+01      1 0.06384615 0.04408467
## 6  1e+02      1 0.02294872 0.01453243
## 7  1e-02     10 0.56397436 0.05244480
## 8  1e-01     10 0.56397436 0.05244480
## 9  1e+00     10 0.56397436 0.05244480
## 10 5e+00     10 0.56397436 0.05244480
## 11 1e+01     10 0.56397436 0.05244480
## 12 1e+02     10 0.56397436 0.05244480
## 13 1e-02    100 0.56397436 0.05244480
## 14 1e-01    100 0.56397436 0.05244480
## 15 1e+00    100 0.56397436 0.05244480
## 16 5e+00    100 0.56397436 0.05244480
## 17 1e+01    100 0.56397436 0.05244480
## 18 1e+02    100 0.56397436 0.05244480
## 19 1e-02   1000 0.56397436 0.05244480
## 20 1e-01   1000 0.56397436 0.05244480
## 21 1e+00   1000 0.56397436 0.05244480
## 22 5e+00   1000 0.56397436 0.05244480
## 23 1e+01   1000 0.56397436 0.05244480
## 24 1e+02   1000 0.56397436 0.05244480

For an SVM with a polynomial kernel, the results indicate that the lowest cross-validation error rate is obtained when cost=100 and degree=1.

set.seed(789)
radial.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(radial.tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##   100  0.01
## 
## - best performance: 0.01025641 
## 
## - Detailed performance results:
##     cost gamma      error dispersion
## 1  1e-02 1e-02 0.56397436 0.05244480
## 2  1e-01 1e-02 0.08685897 0.04408679
## 3  1e+00 1e-02 0.07410256 0.04448059
## 4  5e+00 1e-02 0.04852564 0.03517544
## 5  1e+01 1e-02 0.02294872 0.01890223
## 6  1e+02 1e-02 0.01025641 0.01324097
## 7  1e-02 1e-01 0.18897436 0.08325374
## 8  1e-01 1e-01 0.08179487 0.04972273
## 9  1e+00 1e-01 0.05878205 0.03841171
## 10 5e+00 1e-01 0.03333333 0.02432521
## 11 1e+01 1e-01 0.03070513 0.02357884
## 12 1e+02 1e-01 0.02820513 0.02821808
## 13 1e-02 1e+00 0.56397436 0.05244480
## 14 1e-01 1e+00 0.56397436 0.05244480
## 15 1e+00 1e+00 0.05884615 0.04993403
## 16 5e+00 1e+00 0.06653846 0.05017483
## 17 1e+01 1e+00 0.06653846 0.05017483
## 18 1e+02 1e+00 0.06653846 0.05017483
## 19 1e-02 5e+00 0.56397436 0.05244480
## 20 1e-01 5e+00 0.56397436 0.05244480
## 21 1e+00 5e+00 0.49782051 0.07284739
## 22 5e+00 5e+00 0.49275641 0.08232241
## 23 1e+01 5e+00 0.49275641 0.08232241
## 24 1e+02 5e+00 0.49275641 0.08232241
## 25 1e-02 1e+01 0.56397436 0.05244480
## 26 1e-01 1e+01 0.56397436 0.05244480
## 27 1e+00 1e+01 0.53089744 0.06910984
## 28 5e+00 1e+01 0.52583333 0.07181652
## 29 1e+01 1e+01 0.52583333 0.07181652
## 30 1e+02 1e+01 0.52583333 0.07181652
## 31 1e-02 1e+02 0.56397436 0.05244480
## 32 1e-01 1e+02 0.56397436 0.05244480
## 33 1e+00 1e+02 0.56397436 0.05244480
## 34 5e+00 1e+02 0.56397436 0.05244480
## 35 1e+01 1e+02 0.56397436 0.05244480
## 36 1e+02 1e+02 0.56397436 0.05244480

For an SVM with a radial kernel, the results indicate that the lowest cross-validation error rate is obtained when cost=100 and gamma=0.01.

(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 = 1)
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)

## Exercise 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.

data("OJ")
set.seed(80)

OJ.split = initial_split(OJ, prop = .748)
OJ.train = training(OJ.split)
OJ.test = testing (OJ.split)

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

OJ.svc = svm(Purchase ~ ., data = OJ.train, kernel = "linear", cost=0.01)
summary(OJ.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:  430
## 
##  ( 215 215 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

The result suggest that the SVM C-classification was used with a linear kernel, and that there are 430 support vectors with 215 in each class.

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

OJ.pred = predict(OJ.svc, OJ.train)
OJ.cm =table(OJ.train$Purchase, OJ.pred)
(1-sum(diag(OJ.cm))/sum(OJ.cm))
## [1] 0.1625

The test error rate is 0.1625.

OJ.pred2 = predict(OJ.svc, OJ.test)
OJ.cm2 =table(OJ.test$Purchase, OJ.pred2)
(1-sum(diag(OJ.cm2))/sum(OJ.cm2))
## [1] 0.2074074

The test error rate is 0.2074074.

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

set.seed(789)
OJ.tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 10)))
summary(OJ.tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##    10
## 
## - best performance: 0.1625 
## 
## - Detailed performance results:
##    cost  error dispersion
## 1  0.01 0.1725 0.04632314
## 2  0.10 0.1725 0.05197489
## 3  1.00 0.1650 0.04851976
## 4 10.00 0.1625 0.04639804

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

OJ.bm.pred = predict(OJ.tune.out$best.model, OJ.train)
OJ.bm.cm =table(OJ.train$Purchase, OJ.bm.pred)
(1-sum(diag(OJ.bm.cm))/sum(OJ.bm.cm))
## [1] 0.155

The test error rate is .155.

OJ.bm.pred2 = predict(OJ.tune.out$best.model, OJ.test)
OJ.bm.cm2 =table(OJ.test$Purchase, OJ.bm.pred2)
(1-sum(diag(OJ.bm.cm2))/sum(OJ.bm.cm2))
## [1] 0.2

The test error rate is 0.2.

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

OJ.radial.svc = svm(Purchase ~ .,data = OJ.train, kernel = 'radial')
summary(OJ.radial.svc)
## 
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "radial")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  1 
## 
## Number of Support Vectors:  367
## 
##  ( 187 180 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
OJ.radial.pred = predict(OJ.radial.svc, OJ.train)
OJ.radial.cm =table(OJ.train$Purchase, OJ.radial.pred)
(1-sum(diag(OJ.radial.cm))/sum(OJ.radial.cm))
## [1] 0.14375
OJ.radial.pred2 = predict(OJ.radial.svc, OJ.test)
OJ.radial.cm2 =table(OJ.test$Purchase, OJ.radial.pred2)
(1-sum(diag(OJ.radial.cm2))/sum(OJ.radial.cm2))
## [1] 0.1740741
set.seed(789)
OJ.radial.tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 10, 100), gamma = c(0.01, 0.1, 1, 10, 100)))
summary(OJ.radial.tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##     1  0.01
## 
## - best performance: 0.1675 
## 
## - Detailed performance results:
##     cost gamma   error dispersion
## 1  1e-02 1e-02 0.39375 0.05111602
## 2  1e-01 1e-02 0.19375 0.06187184
## 3  1e+00 1e-02 0.16750 0.03917553
## 4  1e+01 1e-02 0.17625 0.05318012
## 5  1e+02 1e-02 0.17375 0.05152197
## 6  1e-02 1e-01 0.39375 0.05111602
## 7  1e-01 1e-01 0.18625 0.04427267
## 8  1e+00 1e-01 0.18375 0.05684103
## 9  1e+01 1e-01 0.19500 0.06540472
## 10 1e+02 1e-01 0.22000 0.07317217
## 11 1e-02 1e+00 0.39375 0.05111602
## 12 1e-01 1e+00 0.32250 0.04706674
## 13 1e+00 1e+00 0.23250 0.07100469
## 14 1e+01 1e+00 0.25125 0.07602311
## 15 1e+02 1e+00 0.25625 0.06647107
## 16 1e-02 1e+01 0.39375 0.05111602
## 17 1e-01 1e+01 0.39375 0.05111602
## 18 1e+00 1e+01 0.26500 0.07163759
## 19 1e+01 1e+01 0.26500 0.07402139
## 20 1e+02 1e+01 0.26875 0.06802012
## 21 1e-02 1e+02 0.39375 0.05111602
## 22 1e-01 1e+02 0.39375 0.05111602
## 23 1e+00 1e+02 0.30875 0.05864500
## 24 1e+01 1e+02 0.30125 0.05935124
## 25 1e+02 1e+02 0.30125 0.06276333
OJ.radial.bm.pred = predict(OJ.radial.tune.out$best.model, OJ.train)
OJ.radial.bm.cm =table(OJ.train$Purchase, OJ.radial.bm.pred)
(1-sum(diag(OJ.radial.bm.cm))/sum(OJ.radial.bm.cm))
## [1] 0.155
OJ.radial.bm.pred2 = predict(OJ.tune.out$best.model, OJ.test)
OJ.radial.bm.cm2 =table(OJ.test$Purchase, OJ.radial.bm.pred2)
(1-sum(diag(OJ.radial.bm.cm2))/sum(OJ.radial.bm.cm2))
## [1] 0.2

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

OJ.poly.svc = svm(Purchase ~ .,data = OJ.train, kernel = 'polynomial', degree=2)
summary(OJ.poly.svc)
## 
## 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:  450
## 
##  ( 229 221 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
OJ.poly.pred = predict(OJ.poly.svc, OJ.train)
OJ.poly.cm =table(OJ.train$Purchase, OJ.poly.pred)
(1-sum(diag(OJ.poly.cm))/sum(OJ.poly.cm))
## [1] 0.17
OJ.poly.pred2 = predict(OJ.poly.svc, OJ.test)
OJ.poly.cm2 =table(OJ.test$Purchase, OJ.poly.pred2)
(1-sum(diag(OJ.poly.cm2))/sum(OJ.poly.cm2))
## [1] 0.2074074
set.seed(789)
OJ.poly.tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 10, 100), degree = c(1,10,100,1000)))
summary(OJ.poly.tune.out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost degree
##     1      1
## 
## - best performance: 0.17625 
## 
## - Detailed performance results:
##     cost degree   error dispersion
## 1  1e-02      1 0.39375 0.05111602
## 2  1e-01      1 0.18500 0.04518481
## 3  1e+00      1 0.17625 0.05447030
## 4  1e+01      1 0.18375 0.05981743
## 5  1e+02      1 0.20000 0.06561673
## 6  1e-02     10 0.39375 0.05111602
## 7  1e-01     10 0.18500 0.04518481
## 8  1e+00     10 0.17625 0.05447030
## 9  1e+01     10 0.18375 0.05981743
## 10 1e+02     10 0.20000 0.06561673
## 11 1e-02    100 0.39375 0.05111602
## 12 1e-01    100 0.18500 0.04518481
## 13 1e+00    100 0.17625 0.05447030
## 14 1e+01    100 0.18375 0.05981743
## 15 1e+02    100 0.20000 0.06561673
## 16 1e-02   1000 0.39375 0.05111602
## 17 1e-01   1000 0.18500 0.04518481
## 18 1e+00   1000 0.17625 0.05447030
## 19 1e+01   1000 0.18375 0.05981743
## 20 1e+02   1000 0.20000 0.06561673
OJ.poly.bm.pred = predict(OJ.poly.tune.out$best.model, OJ.train)
OJ.poly.bm.cm =table(OJ.train$Purchase, OJ.poly.bm.pred)
(1-sum(diag(OJ.poly.bm.cm))/sum(OJ.poly.bm.cm))
## [1] 0.14375
OJ.poly.bm.pred2 = predict(OJ.poly.tune.out$best.model, OJ.test)
OJ.poly.bm.cm2 =table(OJ.test$Purchase, OJ.poly.bm.pred2)
(1-sum(diag(OJ.poly.bm.cm2))/sum(OJ.poly.bm.cm2))
## [1] 0.1740741

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

Of the three models, the one that gave the best results on the data was the polynomial kernel SVM model that was tuned to use cost=1 and degree=1.