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:

\(> x_1=runif (500) -0.5\)

\(> x_2=runif (500) -0.5\)

\(> y=1 * (x_1^2-x_2^2 > 0)\)

set.seed(1)
x_1=runif (500) -0.5
x_2=runif (500) -0.5
y=1*(x_1^2-x_2^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(x_1, x_2, xlab = "X1", ylab = "X2", col = (y+1))

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

lm.fit = glm(y ~ x_1 + x_2, family = "binomial")
summary(lm.fit)
## 
## Call:
## glm(formula = y ~ x_1 + x_2, 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
## x_1          0.196199   0.316864   0.619    0.536
## x_2         -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

We can see that there are no statistically significant predictors.

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

data = data.frame(x1 = x_1, x2 = x_2, y = y)
lm.prob = predict(lm.fit, data, type = "response")
lm.pred = rep(0, 500)
lm.pred[lm.prob > 0.50] <- 1
plot(data[lm.pred == 1, ]$x1, data[lm.pred == 1, ]$x2, col = (2), pch = (2), xlab = "X1", ylab = "X2")
points(data[lm.pred == 0, ]$x1, data[lm.pred == 0, ]$x2, col = (1), pch = (1))

(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. \(X^2_1 , X_1 × X_2, log(X_2)\),and so forth).

lm.fit = glm(y ~ poly(x_1, 2) + poly(x_2, 2) + I(x_1 * x_2), family = "binomial")
summary(lm.fit)
## 
## Call:
## glm(formula = y ~ poly(x_1, 2) + poly(x_2, 2) + I(x_1 * x_2), 
##     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(x_1, 2)1   2715.3   141109.5   0.019    0.985
## poly(x_1, 2)2  27218.5   842987.2   0.032    0.974
## poly(x_2, 2)1   -279.7    97160.4  -0.003    0.998
## poly(x_2, 2)2 -28693.0   875451.3  -0.033    0.974
## I(x_1 * x_2)    -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

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

lm.prob = predict(lm.fit, data, type = "response")
lm.pred = rep(0, 500)
lm.pred[lm.prob > 0.5] <- 1
plot(data[lm.pred == 1, ]$x1, data[lm.pred == 1, ]$x2, col = (2), pch = (2 ), xlab = "X1", ylab = "X2")
points(data[lm.pred == 0, ]$x1, data[lm.pred == 0, ]$x2, col = (1), pch = (1))

(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)
data$y <- as.factor(data$y)
svm.fit <- svm(y ~ x1 + x2, data, kernel = "linear", cost = 0.01)
lm.pred <- predict(svm.fit, data)
plot(data[lm.pred == 0, ]$x1, data[lm.pred == 0, ]$x2, col = (2), pch = (2), xlab = "X1", ylab = "X2")
points(data[lm.pred == 1, ]$x1, data[lm.pred == 1, ]$x2, col = (1), pch = (1))

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

data$y <- as.factor(data$y)
svm.fit <- svm(y ~ x_1 + x_2, data, kernel = "radial", gamma = 1)
lm.pred <- predict(svm.fit, data)
plot(data[lm.pred == 0, ]$x1, data[lm.pred == 0, ]$x2, col = (2), pch = (2), xlab = "X1", ylab = "X2")
points(data[lm.pred == 1, ]$x1, data[lm.pred == 1, ]$x2, col = (1), pch = (1))

(i) Comment on your results.

SVM and logistic regression are good when they were used with interactions, while at noninteractions both SVM and logistic regression lacks power. Also it is important that we keep gamma in tune during. If gamma is given, maybe cross validation might be a good option to use.

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

(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)
var = ifelse(Auto$mpg > gas.med, 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.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

According to the summary, best performance is 0.01025641 at cost of 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(1)
tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "radial", 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.01282051 
## 
## - Detailed performance results:
##     cost degree      error dispersion
## 1  1e-02      2 0.55115385 0.04366593
## 2  1e-01      2 0.10724359 0.04652829
## 3  1e+00      2 0.07653846 0.03617137
## 4  5e+00      2 0.06384615 0.03266255
## 5  1e+01      2 0.05365385 0.02830539
## 6  1e+02      2 0.01282051 0.01813094
## 7  1e-02      3 0.55115385 0.04366593
## 8  1e-01      3 0.10724359 0.04652829
## 9  1e+00      3 0.07653846 0.03617137
## 10 5e+00      3 0.06384615 0.03266255
## 11 1e+01      3 0.05365385 0.02830539
## 12 1e+02      3 0.01282051 0.01813094
## 13 1e-02      4 0.55115385 0.04366593
## 14 1e-01      4 0.10724359 0.04652829
## 15 1e+00      4 0.07653846 0.03617137
## 16 5e+00      4 0.06384615 0.03266255
## 17 1e+01      4 0.05365385 0.02830539
## 18 1e+02      4 0.01282051 0.01813094
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

This time the best performance is at cost of 100 with degree of 2 for both radial and polynomial

(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 framecontaining your data, you can type

\(> plot(svmfit , dat , x1∼x4)\)

in order to plot just the first and fourth variables. However, youmust replace x1 and x4 with the correct variable names. To findout more, type ?plot.svm.

library(e1071)
svm.linear = svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 10, 
    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)

Problem 8

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

library(ISLR)
attach(OJ)

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

set.seed(1)
train <- sample(nrow(OJ), 800)
training.set <- OJ[train, ]
testing.set <- 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.

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

There are 435 number of support vectors which consists of 219 CH and 216 MM.

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

train.pred <- predict(svm.linear, training.set)
table(training.set$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 420  65
##   MM  75 240
test.pred <- predict(svm.linear, testing.set)
table(testing.set$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  33  69
(75 + 65)/(420+240+65+75)
## [1] 0.175
(15+33)/(153+15+33+69)
## [1] 0.1777778

We can see that training error rate is 17.5% while the testing error rate is 17.8%

(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 = training.set, 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
##  3.162278
## 
## - best performance: 0.16875 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.17625 0.02853482
## 2   0.01778279 0.17625 0.03143004
## 3   0.03162278 0.17125 0.02829041
## 4   0.05623413 0.17625 0.02853482
## 5   0.10000000 0.17250 0.03162278
## 6   0.17782794 0.17125 0.02829041
## 7   0.31622777 0.17125 0.02889757
## 8   0.56234133 0.17125 0.02703521
## 9   1.00000000 0.17500 0.02946278
## 10  1.77827941 0.17375 0.02729087
## 11  3.16227766 0.16875 0.03019037
## 12  5.62341325 0.17375 0.03304563
## 13 10.00000000 0.17375 0.03197764

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

svm.linear <- svm(Purchase ~ ., kernel = "linear", data = training.set, cost = tune.out$best.parameter$cost)
train.pred <- predict(svm.linear, training.set)
table(training.set$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 423  62
##   MM  70 245
(62 + 70)/(423 +62 +70 +245 )
## [1] 0.165
svm.linear <- svm(Purchase ~ ., kernel = "linear", data = training.set, cost = tune.out$best.parameter$cost)
test.pred <- predict(svm.linear, testing.set)
table(testing.set$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 156  12
##   MM  29  73
(29 + 12)/(156+12+29+73)
## [1] 0.1518519

Testing error for the new values are 16.5% for the training set, 15.2% for testing set

(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 ~ ., kernel = "radial", data = training.set)
summary(svm.radial)
## 
## Call:
## svm(formula = Purchase ~ ., data = training.set, 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, training.set)
table(training.set$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 441  44
##   MM  77 238
test.pred <- predict(svm.radial, testing.set)
table(testing.set$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 151  17
##   MM  33  69
(44+77)/(441+44+77+28)
## [1] 0.2050847
(17+33)/(151+17+33+69)
## [1] 0.1851852

We can see that error for training data has 20.5% while testing data has 18.5% when performed using radial kernel

set.seed(1)
tune.out <- tune(svm, Purchase ~ ., data = training.set, 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.5623413
## 
## - best performance: 0.16875 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.39375 0.04007372
## 2   0.01778279 0.39375 0.04007372
## 3   0.03162278 0.35750 0.05927806
## 4   0.05623413 0.19500 0.02443813
## 5   0.10000000 0.18625 0.02853482
## 6   0.17782794 0.18250 0.03291403
## 7   0.31622777 0.17875 0.03230175
## 8   0.56234133 0.16875 0.02651650
## 9   1.00000000 0.17125 0.02128673
## 10  1.77827941 0.17625 0.02079162
## 11  3.16227766 0.17750 0.02266912
## 12  5.62341325 0.18000 0.02220485
## 13 10.00000000 0.18625 0.02853482
svm.radial <- svm(Purchase ~ ., kernel = "radial", data = training.set, cost = tune.out$best.parameter$cost)
summary(svm.radial)
## 
## Call:
## svm(formula = Purchase ~ ., data = training.set, kernel = "radial", 
##     cost = tune.out$best.parameter$cost)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  0.5623413 
## 
## Number of Support Vectors:  397
## 
##  ( 200 197 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train.pred <- predict(svm.radial, training.set)
table(training.set$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 437  48
##   MM  71 244
test.pred <- predict(svm.radial, testing.set)
table(testing.set$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 150  18
##   MM  30  72
(71+48)/(437+ 48 +71+ 244)
## [1] 0.14875
(30+18)/(150+18+30+72)
## [1] 0.1777778

The error when tuned is 14.9% for training, 17.8% for testing

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

svm.poly <- svm(Purchase ~ ., kernel = "polynomial", data = training.set, degree = 2)
summary(svm.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = training.set, 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, training.set)
table(training.set$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 449  36
##   MM 110 205
test.pred <- predict(svm.poly, testing.set)
table(testing.set$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  45  57
(36+110)/(449+36+110+205)
## [1] 0.1825
(45+15)/(153+15+45+57)
## [1] 0.2222222

The test errors when performed polynomial with degree of 2 are 18.2% for training and 22.2% for testing.

set.seed(1)
tune.out <- tune(svm, Purchase ~ ., data = training.set, kernel = "polynomial", 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.185 
## 
## - Detailed performance results:
##           cost   error dispersion
## 1   0.01000000 0.37125 0.03537988
## 2   0.01778279 0.37125 0.03488573
## 3   0.03162278 0.34500 0.04377975
## 4   0.05623413 0.32750 0.04669642
## 5   0.10000000 0.28750 0.05068969
## 6   0.17782794 0.22625 0.03408018
## 7   0.31622777 0.19625 0.03438447
## 8   0.56234133 0.19125 0.03634805
## 9   1.00000000 0.18500 0.02415229
## 10  1.77827941 0.18875 0.02079162
## 11  3.16227766 0.19125 0.02503470
## 12  5.62341325 0.19000 0.03106892
## 13 10.00000000 0.19500 0.03184162
svm.poly <- svm(Purchase ~ ., kernel = "polynomial", data = training.set, degree = 2, cost = tune.out$best.parameter$cost)
summary(svm.poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = training.set, kernel = "polynomial", 
##     degree = 2, cost = tune.out$best.parameter$cost)
## 
## 
## 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, training.set)
table(training.set$Purchase, train.pred)
##     train.pred
##       CH  MM
##   CH 449  36
##   MM 110 205
test.pred <- predict(svm.poly, testing.set)
table(testing.set$Purchase, test.pred)
##     test.pred
##       CH  MM
##   CH 153  15
##   MM  45  57
(36+110)/(449+110+36+205)
## [1] 0.1825
(45+15)/(153+15+45+57)
## [1] 0.2222222

The testing errors after tuned are 18.3% for training, 22.2% for testing. One thing I can notice is that tuning does not have too much effect in this case.

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

It seems that linear regression has overall gives least amount of test errors out of all the methods.