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

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

  2. Plot the observations, colored according to their class labels. Your plot should display X1 on the x-axis, and X2 on the yaxis.

set.seed(2)
x1 <- runif(500) - 0.5
x2 <- runif(500) - 0.5
y <- 1 * (x1^2 - x2^2 > 0)

plot(x1[y == 0], x2[y == 0], col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(x1[y == 1], x2[y == 1], col = "darkgrey", pch = 4)

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

  1. 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.
lm.fit <- glm(y ~ x1 + x2, family = binomial)
summary(lm.fit)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -1.271  -1.193   1.097   1.147   1.209  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  0.07138    0.08959   0.797    0.426
## x1          -0.03532    0.29825  -0.118    0.906
## x2           0.27548    0.30762   0.896    0.370
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 692.50  on 499  degrees of freedom
## Residual deviance: 691.67  on 497  degrees of freedom
## AIC: 697.67
## 
## Number of Fisher Scoring iterations: 3
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", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkgrey", pch = 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).

  1. 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.
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
summary(lm.fit)
## 
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = binomial, 
##     data = data)
## 
## Deviance Residuals: 
##        Min          1Q      Median          3Q         Max  
## -1.441e-03  -2.000e-08   2.000e-08   2.000e-08   1.455e-03  
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)
## (Intercept)       89.95   48695.53   0.002    0.999
## poly(x1, 2)1     203.19 1143572.92   0.000    1.000
## poly(x1, 2)2   32729.10  895641.74   0.037    0.971
## poly(x2, 2)1     540.94 1130136.06   0.000    1.000
## poly(x2, 2)2  -33281.76 1338007.08  -0.025    0.980
## I(x1 * x2)       198.04  578657.79   0.000    1.000
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9250e+02  on 499  degrees of freedom
## Residual deviance: 4.9969e-06  on 494  degrees of freedom
## AIC: 12
## 
## Number of Fisher Scoring iterations: 25
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", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkgrey", pch = 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.

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", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkgrey", pch = 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(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", pch = 5)
points(data.neg$x1, data.neg$x2, col = "darkgrey", pch = 5)

(i) Comment on your results.

Using the logistic regression mehtod or the linear kernel, the results are poor in terms of finding the non-linear decision boundaries.If wanting to find non-linear decision boundaries the original logistic regression and the SVM with non-linear kernel were both good 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.

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

  2. 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. Note you will need to fit the classifier without the gas mileage variable to produce sensible results.

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

This model uses a 10 fold cross validation. Best parameters are at a cost of 1 and has a performance of 0.0102.

  1. 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(21)
tune.out <- tune(svm, mpglevel ~ ., 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: 0.5435897 
## 
## - Detailed performance results:
##    cost degree     error dispersion
## 1   0.1      2 0.5587821 0.04538579
## 2   1.0      2 0.5587821 0.04538579
## 3   5.0      2 0.5587821 0.04538579
## 4  10.0      2 0.5435897 0.05611162
## 5   0.1      3 0.5587821 0.04538579
## 6   1.0      3 0.5587821 0.04538579
## 7   5.0      3 0.5587821 0.04538579
## 8  10.0      3 0.5587821 0.04538579
## 9   0.1      4 0.5587821 0.04538579
## 10  1.0      4 0.5587821 0.04538579
## 11  5.0      4 0.5587821 0.04538579
## 12 10.0      4 0.5587821 0.04538579

The best performance is 0.5435897 that has the lowest cross validation error obtained for a degree of 2 and a cost of 100.

  1. 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.svm <- svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
poly.svm <- svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 10, 
    degree = 2)
radial.svm = 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 = "")))
    }
}
plotpairs(linear.svm)

Question 8

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

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

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

set.seed(1)
train <- sample(dim(OJ)[1], 800)
train.oj <- OJ[train, ]
test.oj <- OJ[-train, ]

linear.svm <- svm(Purchase ~ ., data = train.oj, kernel = "linear", cost = 0.01)
summary(linear.svm)
## 
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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

435 support vectors are created, where 219 are level Ch and 216 are level MM.

  1. What are the training and test error rates?
train.pred <- predict(linear.svm, train.oj)
table(train.oj$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 420  65
##   MM  75 240
(65+75)/800
## [1] 0.175
test.pred <- predict(linear.svm, test.oj)
table(test.oj$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  33  69
(15+33)/270
## [1] 0.1777778

The training error is 0.175 and the test error is 0.178.

  1. Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(12)
tune.out <- tune(svm, Purchase ~ ., data = train.oj, 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
##    10
## 
## - best performance: 0.17125 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.17500 0.03118048
## 2   0.01778279 0.17500 0.02825971
## 3   0.03162278 0.17875 0.02638523
## 4   0.05623413 0.17500 0.03061862
## 5   0.10000000 0.17625 0.03408018
## 6   0.17782794 0.17125 0.02829041
## 7   0.31622777 0.17500 0.03061862
## 8   0.56234133 0.17500 0.03061862
## 9   1.00000000 0.17625 0.03087272
## 10  1.77827941 0.17375 0.03143004
## 11  3.16227766 0.17500 0.03280837
## 12  5.62341325 0.17250 0.03425801
## 13 10.00000000 0.17125 0.03175973

There is an optimal cost of 10 with a best performance of 0.17125

  1. Compute the training and test error rates using this new value for cost.
linear.svm <- svm(Purchase ~ ., kernel = "linear", data = train.oj, cost = tune.out$best.parameter$cost)
train.pred <- predict(linear.svm, train.oj)
table(train.oj$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 423  62
##   MM  69 246
(62+69)/800
## [1] 0.16375
test.pred <- predict(linear.svm, test.oj)
table(test.oj$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 156  12
##   MM  28  74
(12+28)/270
## [1] 0.1481481

The tuning of svm caused a decrease in the training error rate to 0.164 and decrease in the test error rate to 0.148.

  1. Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
radial.svm <- svm(Purchase ~ ., kernel = "radial", data = train.oj)
summary(radial.svm)
## 
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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

373 support vectors, where 188 vectors are level CH and 185 are level MM.

train.pred <- predict(radial.svm, train.oj)
table(train.oj$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 441  44
##   MM  77 238
(44+77)/800
## [1] 0.15125
test.pred <- predict(radial.svm, test.oj)
table(test.oj$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 151  17
##   MM  33  69
(17+33)/270
## [1] 0.1851852

The training error rate is 0.151 and the test errror rate is 0.185.

set.seed(12)
tune.out <- tune(svm, Purchase ~ ., data = train.oj, 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
##  0.3162278
## 
## - best performance: 0.17 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39375 0.05597929
## 2   0.01778279 0.39375 0.05597929
## 3   0.03162278 0.35000 0.07264832
## 4   0.05623413 0.19875 0.04656611
## 5   0.10000000 0.18750 0.04124790
## 6   0.17782794 0.18000 0.04257347
## 7   0.31622777 0.17000 0.03641962
## 8   0.56234133 0.17375 0.04619178
## 9   1.00000000 0.17125 0.05272110
## 10  1.77827941 0.18125 0.04093101
## 11  3.16227766 0.18750 0.04639804
## 12  5.62341325 0.18625 0.04581439
## 13 10.00000000 0.19250 0.04377975

The optimal cost is 0.3162278 and the best performance is 0.17.

radial.svm <- svm(Purchase ~ ., data = train.oj, kernel = "radial", cost = tune.out$best.parameters$cost)
train.pred <- predict(radial.svm, train.oj)
table(train.oj$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 436  49
##   MM  78 237
(49+78)/800
## [1] 0.15875
test.pred <- predict(radial.svm, test.oj)
table(test.oj$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 150  18
##   MM  32  70
(18+32)/270
## [1] 0.1851852

From tuning the svm, the training error rate increase to 0.159 and the test error rate remained the same at 0.185.

  1. Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
set.seed(12)
poly.svm <- svm(Purchase ~ ., data = train.oj, kernel = "poly", degree = 2)
summary(poly.svm)
## 
## Call:
## svm(formula = Purchase ~ ., data = train.oj, kernel = "poly", 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

447 support vectors, where 222 are level CH and 225 are level MM.

train.pred <- predict(poly.svm, train.oj)
table(train.oj$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 449  36
##   MM 110 205
(36+110)/800
## [1] 0.1825
test.pred <- predict(poly.svm, test.oj)
table(test.oj$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  45  57
(15+45)/270
## [1] 0.2222222

The training error is 0.183 and the test error is 0.222.

set.seed(12)
tune.out = tune(svm, Purchase ~ ., data = train.oj, kernel = "poly", 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
##  0.5623413
## 
## - best performance: 0.18375 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.37125 0.06589396
## 2   0.01778279 0.37000 0.06645801
## 3   0.03162278 0.34625 0.06822400
## 4   0.05623413 0.33375 0.06771314
## 5   0.10000000 0.28875 0.06079622
## 6   0.17782794 0.23125 0.04379958
## 7   0.31622777 0.20250 0.03944053
## 8   0.56234133 0.18375 0.04251225
## 9   1.00000000 0.19375 0.03691676
## 10  1.77827941 0.19500 0.03641962
## 11  3.16227766 0.18875 0.04185375
## 12  5.62341325 0.19250 0.02958040
## 13 10.00000000 0.20000 0.02886751

The optimal cost is 0.5623413 and the best performance is 0.184.

poly.svm <- svm(Purchase ~ ., data = train.oj, kernel = "poly", degree = 2, cost = tune.out$best.parameters$cost)
train.pred <- predict(poly.svm, train.oj)
table(train.oj$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 447  38
##   MM 111 204
(38+111)/800
## [1] 0.18625
test.pred <- predict(poly.svm, test.oj)
table(test.oj$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 151  17
##   MM  45  57
(17+45)/270
## [1] 0.2296296

The tuning of the svm resulted in a training error rate that had a very slight increase to 0.186 and an increase in test error rate to 0.2296.

  1. Overall, which approach seems to give the best results on this data?

The linear SVM approach on the OJ data seemed to have given the best results since it produce lower training error rates and test error rates, 0.164 and 0.149.