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:
set.seed(5)
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.
plot(x1[y == 0], x2[y == 0], col = "red", xlab = "X1", ylab = "X2", pch = 25)
points(x1[y == 1], x2[y == 1], col = "blue", pch = 1)
(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
data=data.frame(x1 = x1, x2 = x2, y=as.factor(y))
set.seed(5)
glm.fit=glm(y ~., data=data, family = binomial)
summary(glm.fit)
##
## Call:
## glm(formula = y ~ ., family = binomial, data = data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.200 -1.161 -1.131 1.190 1.223
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.03150 0.08949 -0.352 0.725
## x1 -0.06176 0.30506 -0.202 0.840
## x2 -0.11509 0.31086 -0.370 0.711
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.02 on 499 degrees of freedom
## Residual deviance: 692.85 on 497 degrees of freedom
## AIC: 698.85
##
## 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.
set.seed(5)
train <- sample(250, 250)
data.train <- data[train, ]
data.test <- data[-train, ]
set.seed(5)
glm.fit=glm(y ~., data.train, family = binomial)
summary(glm.fit)
##
## Call:
## glm(formula = y ~ ., family = binomial, data = data.train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.273 -1.153 -1.075 1.181 1.270
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.01515 0.12672 -0.120 0.905
## x1 -0.09581 0.42911 -0.223 0.823
## x2 -0.39855 0.43970 -0.906 0.365
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 346.56 on 249 degrees of freedom
## Residual deviance: 345.72 on 247 degrees of freedom
## AIC: 351.72
##
## Number of Fisher Scoring iterations: 3
glm.prob = predict(glm.fit, data, type = "response")
glm.pred = ifelse(glm.prob > 0.5, 1, 0)
data.pos = data[glm.pred == 1, ]
data.neg = data[glm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "red", xlab = "X1", ylab = "X2", pch = 25)
points(data.neg$x1, data.neg$x2, col = "blue", pch = 1)
(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).
set.seed(5)
glm.poly = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = data, family = binomial)
(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.
set.seed(5)
glm.poly = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = data.train, family = binomial)
lm.prob = predict(glm.poly, 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 = "red", xlab = "X1", ylab = "X2", pch = 25)
points(data.neg$x1, data.neg$x2, col = "blue", 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)
svmfit=svm(y~., data=data, kernel ="linear", cost=1e5)
plot(svmfit, data.train)
ypred=predict(svmfit,data.train)
table(predict=ypred, truth=data.train$y )
## truth
## predict 0 1
## 0 61 55
## 1 65 69
(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.
set.seed(5)
svmfit=svm(y~., data=data, kernel ="radial", gamma=1, cost=1)
plot(svmfit, data.train)
ypred=predict(svmfit,data.train)
table(predict=ypred, truth=data.train$y )
## truth
## predict 0 1
## 0 126 10
## 1 0 114
(i) Comment on your results.
Based on the results of the plots, non-linear models should be performed as it captured the outcome variable better than linear.
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)
#create new variable
mpg.med = median(Auto$mpg)
mpg_med = ifelse(Auto$mpg > mpg.med, 1, 0)
Auto$mpg_med = as.factor(mpg_med)
(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.
The cost = 0.1 results in the lowest cross-validation error rate of 0.0102
set.seed(5)
linear.svm=tune(svm,mpg_med~.,data=Auto,kernel ="linear",ranges=list(cost=c(0.001, 0.01, 0.1, 1,5,10,100)))
summary(linear.svm)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.01019231
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-03 0.09698718 0.03980793
## 2 1e-02 0.07391026 0.02208631
## 3 1e-01 0.04576923 0.02585417
## 4 1e+00 0.01019231 0.01786828
## 5 5e+00 0.01782051 0.02088734
## 6 1e+01 0.02294872 0.01871043
## 7 1e+02 0.03576923 0.03002696
(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.
The cost = 10 results in the lowest cross-validation error rate of 0.5738
set.seed(5)
poly.svm = tune(svm, mpg_med ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1, 1, 5, 10), degree = c(2, 3, 4)))
summary(poly.svm)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 10 2
##
## - best performance: 0.5738462
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.5841026 0.04075521
## 2 1.0 2 0.5841026 0.04075521
## 3 5.0 2 0.5841026 0.04075521
## 4 10.0 2 0.5738462 0.03762359
## 5 0.1 3 0.5841026 0.04075521
## 6 1.0 3 0.5841026 0.04075521
## 7 5.0 3 0.5841026 0.04075521
## 8 10.0 3 0.5841026 0.04075521
## 9 0.1 4 0.5841026 0.04075521
## 10 1.0 4 0.5841026 0.04075521
## 11 5.0 4 0.5841026 0.04075521
## 12 10.0 4 0.5841026 0.04075521
The cost = 10 results in the lowest cross-validation error rate of 0.0509
set.seed(5)
radial.svm = tune(svm, mpg_med ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.1, 1, 5, 10), degree = c(2, 3, 4)))
summary(radial.svm)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 10 2
##
## - best performance: 0.05089744
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.09955128 0.03728256
## 2 1.0 2 0.07647436 0.02060620
## 3 5.0 2 0.06371795 0.02456466
## 4 10.0 2 0.05089744 0.02357836
## 5 0.1 3 0.09955128 0.03728256
## 6 1.0 3 0.07647436 0.02060620
## 7 5.0 3 0.06371795 0.02456466
## 8 10.0 3 0.05089744 0.02357836
## 9 0.1 4 0.09955128 0.03728256
## 10 1.0 4 0.07647436 0.02060620
## 11 5.0 4 0.06371795 0.02456466
## 12 10.0 4 0.05089744 0.02357836
(d) Make some plots to back up your assertions in (b) and (c).
svm.linear = svm(mpg_med ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly = svm(mpg_med ~ ., data = Auto, kernel = "polynomial", cost = 10,
degree = 2)
svm.radial = svm(mpg_med ~ ., data = Auto, kernel = "radial", cost = 10, gamma = 0.01)
plotpairs = function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpg_med", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}
plotpairs(svm.linear)
plotpairs(svm.poly)
plotpairs(svm.radial)
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.
library(ISLR)
attach(OJ)
set.seed(5)
inTrain = sample(dim(OJ)[1], 800)
train = OJ[inTrain, ]
test = OJ[-inTrain, ]
(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.
There are 2 levels of species and fitted 441 support vectors using a linear kernel, 219 are CH and 222 are MM.
set.seed(5)
svm.linear = svm(Purchase ~ ., kernel = "linear", data = train, cost = 0.01)
summary(svm.linear)
##
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "linear", cost = 0.01)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 0.01
##
## Number of Support Vectors: 441
##
## ( 219 222 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
(c) What are the training and test error rates?
The training error rate is 16.63% and the test error rate is 16.67%
train.pred = predict(svm.linear, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 431 59
## MM 74 236
(74 + 59)/800
## [1] 0.16625
test.pred = predict(svm.linear, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 145 18
## MM 27 80
(27 + 18)/270
## [1] 0.1666667
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(5)
tune.out = tune(svm, Purchase ~ ., data = 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
## 10
##
## - best performance: 0.16625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17625 0.05382908
## 2 0.01778279 0.17500 0.04750731
## 3 0.03162278 0.17375 0.04945888
## 4 0.05623413 0.17375 0.04767147
## 5 0.10000000 0.17375 0.04348132
## 6 0.17782794 0.17250 0.04199868
## 7 0.31622777 0.17375 0.04730589
## 8 0.56234133 0.17250 0.04923018
## 9 1.00000000 0.16750 0.04456581
## 10 1.77827941 0.16750 0.04495368
## 11 3.16227766 0.17000 0.04758034
## 12 5.62341325 0.17250 0.04241004
## 13 10.00000000 0.16625 0.03955042
(e) Compute the training and test error rates using this new value for cost.
The training error rate is 16.12% and the test error rate is 17.40%
svm.linear = svm(Purchase ~ ., kernel = "linear", data = train, cost = tune.out$best.parameters$cost)
train.pred = predict(svm.linear, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 435 55
## MM 74 236
(74 + 55)/800
## [1] 0.16125
test.pred = predict(svm.linear, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 145 18
## MM 29 78
(29 + 18)/270
## [1] 0.1740741
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma
There are 2 levels of species and fitted 374 support vectors using a radial kernel, 183 are CH and 191 are MM.
set.seed(5)
svm.radial = svm(Purchase ~ ., data = train, kernel = "radial")
summary(svm.radial)
##
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 374
##
## ( 183 191 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The training error rate is 15% and the test error rate is 17.03%
train.pred = predict(svm.radial, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 447 43
## MM 77 233
(77 + 43)/800
## [1] 0.15
test.pred = predict(svm.radial, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 147 16
## MM 30 77
(30 + 16)/270
## [1] 0.1703704
set.seed(5)
tune.out = tune(svm, Purchase ~ ., data = 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
## 3.162278
##
## - best performance: 0.16625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.38750 0.04677072
## 2 0.01778279 0.38750 0.04677072
## 3 0.03162278 0.34625 0.06209592
## 4 0.05623413 0.20875 0.04332131
## 5 0.10000000 0.18875 0.04348132
## 6 0.17782794 0.18500 0.04518481
## 7 0.31622777 0.18125 0.03738408
## 8 0.56234133 0.17500 0.03004626
## 9 1.00000000 0.17375 0.02791978
## 10 1.77827941 0.17625 0.03087272
## 11 3.16227766 0.16625 0.03007514
## 12 5.62341325 0.16875 0.03186887
## 13 10.00000000 0.18125 0.03186887
The training error rate is 14.38% and the test error rate is 17.41%
svm.radial = svm(Purchase ~ ., data = train, kernel = "radial", cost = tune.out$best.parameters$cost)
train.pred = predict(svm.radial, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 452 38
## MM 77 233
(77 + 38)/800
## [1] 0.14375
test.pred = predict(svm.radial, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 148 15
## MM 32 75
(32 + 15)/270
## [1] 0.1740741
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
There are 2 levels of species and fitted 439 support vectors using a radial kernel, 216 are CH and 223 are MM.
set.seed(5)
svm.poly = svm(Purchase ~ ., data = train, kernel = "poly", degree = 2)
summary(svm.poly)
##
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "poly", degree = 2)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 1
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 439
##
## ( 216 223 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The training error rate is 20.13% and the test error rate is 20.74%
train.pred = predict(svm.poly, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 455 35
## MM 106 204
(106 + 55)/800
## [1] 0.20125
test.pred = predict(svm.poly, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 151 12
## MM 44 63
(44 + 12)/270
## [1] 0.2074074
set.seed(5)
tune.out = tune(svm, Purchase ~ ., data = train, kernel = "poly", 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
## 10
##
## - best performance: 0.175
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.36625 0.05205833
## 2 0.01778279 0.35375 0.05744865
## 3 0.03162278 0.34750 0.05645795
## 4 0.05623413 0.32250 0.06061032
## 5 0.10000000 0.30875 0.05070681
## 6 0.17782794 0.25250 0.05857094
## 7 0.31622777 0.20500 0.03689324
## 8 0.56234133 0.20250 0.03809710
## 9 1.00000000 0.20250 0.04199868
## 10 1.77827941 0.19625 0.03682259
## 11 3.16227766 0.19375 0.03596391
## 12 5.62341325 0.18375 0.03387579
## 13 10.00000000 0.17500 0.03280837
The training error rate is 14.13% and the test error rate is 16.67%
svm.poly = svm(Purchase ~ ., data = train, kernel = "poly", degree = 2, cost = tune.out$best.parameters$cost)
train.pred = predict(svm.poly, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 452 38
## MM 75 235
(75 + 38)/ 800
## [1] 0.14125
test.pred = predict(svm.poly, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 149 14
## MM 31 76
(31 + 14)/270
## [1] 0.1666667
(h) Overall, which approach seems to give the best results on this data?
Based on the results listed below, the best approach is a tuned polynomial.
LINEAR Untuned, The training error rate is 16.63% and the test error rate is 16.67% Tuned, The training error rate is 16.12% and the test error rate is 17.40%
RADIAL Untuned, The training error rate is 15% and the test error rate is 17.03% Tuned, The training error rate is 14.38% and the test error rate is 17.41%
POLY Untuned, The training error rate is 20.13% and the test error rate is 20.74% Tuned, The training error rate is 14.13% and the test error rate is 16.67%