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(100)
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, x2, xlab = "X1", ylab = "X2", col = (4 - y), pch = (3 - y))
(c) Fit a logistic regression model to the data, using \(X1\) and \(X2\) as predictors.
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.194 -1.154 -1.119 1.195 1.245
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.05600 0.08989 -0.623 0.533
## x1 -0.14615 0.32098 -0.455 0.649
## x2 0.06528 0.30338 0.215 0.830
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.76 on 499 degrees of freedom
## Residual deviance: 692.50 on 497 degrees of freedom
## AIC: 698.5
##
## 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.
data <- data.frame(x1 = x1, x2 = x2, y = y)
probs <- predict(lm.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.50] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0))
(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).
lr.nl <- glm(y ~ poly(x1, 2) + poly(x2, 2), data = data, family = 'binomial')
summary(lr.nl)
##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2), family = "binomial",
## data = data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.535e-03 -2.000e-08 -2.000e-08 2.000e-08 1.491e-03
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -217.3 6065.2 -0.036 0.971
## poly(x1, 2)1 3871.4 125969.8 0.031 0.975
## poly(x1, 2)2 33920.7 929001.2 0.037 0.971
## poly(x2, 2)1 -606.6 64636.1 -0.009 0.993
## poly(x2, 2)2 -35221.1 965075.4 -0.036 0.971
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9276e+02 on 499 degrees of freedom
## Residual deviance: 5.0915e-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.
probs <- predict(lr.nl, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.50] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0))
(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)
preds <- predict(svm.fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))
(h) Fit a SVM using a non-linear kernel 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.
data$y <- as.factor(data$y)
svmnl.fit <- svm(y ~ x1 + x2, data, kernel = "radial", gamma = 1)
preds <- predict(svmnl.fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))
(i) Comment on your results.
SVM with non-linear kernel and logistic regression with interaction terms are equally significant for finding non-linear decision boundaries.
SVM with linear kernel and logistic regression without any interaction term are not significant in finding non-linear decision boundaries.
SVM also requires some manual adjustments to gamma to find the right interaction terms when using logistic regression so cross-validation may be easier with the parameter of gamma.
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
gas.med = median(Auto$mpg)
new.var = ifelse(Auto$mpg > gas.med, 1, 0)
Auto$mpglevel = as.factor(new.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.
library(e1071)
set.seed(100)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01,
0.1, 1, 10, 100)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.01512821
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07391026 0.04398186
## 2 1e-01 0.05102564 0.03408666
## 3 1e+00 0.01512821 0.02421271
## 4 1e+01 0.02538462 0.02372507
## 5 1e+02 0.03564103 0.02125655
(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(100)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1, .1,
1, 10, 100), degree = c(2, 4, 6)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 2
##
## - best performance: 0.3012821
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.5485897 0.06532230
## 2 0.1 2 0.5485897 0.06532230
## 3 1.0 2 0.5485897 0.06532230
## 4 10.0 2 0.5539744 0.07981094
## 5 100.0 2 0.3012821 0.06251598
## 6 0.1 4 0.5485897 0.06532230
## 7 0.1 4 0.5485897 0.06532230
## 8 1.0 4 0.5485897 0.06532230
## 9 10.0 4 0.5485897 0.06532230
## 10 100.0 4 0.5485897 0.06532230
## 11 0.1 6 0.5485897 0.06532230
## 12 0.1 6 0.5485897 0.06532230
## 13 1.0 6 0.5485897 0.06532230
## 14 10.0 6 0.5485897 0.06532230
## 15 100.0 6 0.5485897 0.06532230
set.seed(100)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.1,
1, 5, 10), gamma = c(0.01, 0.1, 1, 5, 10, 100)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 5 0.1
##
## - best performance: 0.02032051
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.1 1e-02 0.08673077 0.04371113
## 2 1.0 1e-02 0.07391026 0.04398186
## 3 5.0 1e-02 0.04846154 0.02806915
## 4 10.0 1e-02 0.02544872 0.02662645
## 5 0.1 1e-01 0.07903846 0.04566860
## 6 1.0 1e-01 0.04589744 0.02894049
## 7 5.0 1e-01 0.02032051 0.01592719
## 8 10.0 1e-01 0.02032051 0.01592719
## 9 0.1 1e+00 0.51608974 0.15412796
## 10 1.0 1e+00 0.05365385 0.03722373
## 11 5.0 1e+00 0.04852564 0.03517544
## 12 10.0 1e+00 0.04852564 0.03517544
## 13 0.1 5e+00 0.54858974 0.06532230
## 14 1.0 5e+00 0.47948718 0.07716072
## 15 5.0 5e+00 0.47692308 0.07824190
## 16 10.0 5e+00 0.47692308 0.07824190
## 17 0.1 1e+01 0.55608974 0.05262769
## 18 1.0 1e+01 0.50237179 0.07356143
## 19 5.0 1e+01 0.49987179 0.07524572
## 20 10.0 1e+01 0.49987179 0.07524572
## 21 0.1 1e+02 0.55608974 0.05262769
## 22 1.0 1e+02 0.55608974 0.05262769
## 23 5.0 1e+02 0.55608974 0.05262769
## 24 10.0 1e+02 0.55608974 0.05262769
(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 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\).
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 = 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(svm.linear)
plotpairs(svm.poly)
plotpairs(svm.radial)
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(100)
train = sample(dim(OJ)[1], 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.
library(e1071)
svm.linear = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = 0.01)
summary(svm.linear)
##
## 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: 432
##
## ( 216 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
(c) What are the training and test error rates?
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 433 55
## MM 78 234
(433+234)/(433+55+78+234)
## [1] 0.83375
Training error rate is approximately 17%.
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 147 18
## MM 26 79
(147+79)/(147+18+26+79)
## [1] 0.837037
Testing error rate is approximately 16%.
(d) Use the \(tune()\) function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(100)
tune.out = tune(svm, Purchase ~ ., data = OJ.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
## 0.05623413
##
## - best performance: 0.16625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17500 0.04639804
## 2 0.01778279 0.17375 0.03972562
## 3 0.03162278 0.16875 0.04299952
## 4 0.05623413 0.16625 0.04411554
## 5 0.10000000 0.16875 0.03875224
## 6 0.17782794 0.16875 0.04007372
## 7 0.31622777 0.17375 0.03928617
## 8 0.56234133 0.17500 0.03908680
## 9 1.00000000 0.17375 0.04101575
## 10 1.77827941 0.17125 0.03230175
## 11 3.16227766 0.17375 0.03251602
## 12 5.62341325 0.17000 0.04005205
## 13 10.00000000 0.17000 0.03782269
(e) Compute the training and test error rates using this new value for cost.
svm.linear = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = tune.out$best.parameters$cost)
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 427 61
## MM 67 245
(427+61)/(427+61+67+245)
## [1] 0.61
Training error rate is approximately 39%.
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 141 24
## MM 25 80
(141+80)/(141+24+25+80)
## [1] 0.8185185
Testing error rate is approximately 19%.
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
set.seed(100)
svm.radial = svm(Purchase ~ ., data = OJ.train, kernel = "radial")
summary(svm.radial)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 368
##
## ( 187 181 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 448 40
## MM 69 243
(448+243)/(448+40+69+243)
## [1] 0.86375
Training error rate is approximately 14%.
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 147 18
## MM 32 73
(147+73)/(147+18+32+73)
## [1] 0.8148148
Testing error rate is approximately 19%.
set.seed(100)
tune.out = tune(svm, Purchase ~ ., data = OJ.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
## 1
##
## - best performance: 0.16
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39000 0.03809710
## 2 0.01778279 0.39000 0.03809710
## 3 0.03162278 0.33375 0.06562996
## 4 0.05623413 0.19125 0.04411554
## 5 0.10000000 0.18500 0.04440971
## 6 0.17782794 0.17875 0.03998698
## 7 0.31622777 0.17250 0.03670453
## 8 0.56234133 0.16250 0.03632416
## 9 1.00000000 0.16000 0.03216710
## 10 1.77827941 0.16125 0.03356689
## 11 3.16227766 0.17125 0.03729108
## 12 5.62341325 0.17000 0.03446012
## 13 10.00000000 0.17625 0.02791978
svm.radial <- svm(Purchase ~ ., kernel = "radial", data = OJ.train, cost = tune.out$best.parameter$cost)
summary(svm.radial)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "radial", cost = tune.out$best.parameter$cost)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 368
##
## ( 187 181 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train.pred <- predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 448 40
## MM 69 243
(448+243)/(448+243+40+69)
## [1] 0.86375
Training error rate is approximatly 14%.
test.pred <- predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 147 18
## MM 32 73
(147+73)/(18+32+73+147)
## [1] 0.8148148
Testing error rate is approximately 19% Tuning does not reduce the training and testing error rates.
(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 = OJ.train, degree = 2)
summary(svm.poly)
##
## 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: 447
##
## ( 228 219 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train.pred <- predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 458 30
## MM 105 207
(458+207)/(458+30+105+207)
## [1] 0.83125
Training error rate is approximately 17%.
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 152 13
## MM 45 60
(152+60)/(152+13+45+60)
## [1] 0.7851852
Testing error rate is approximately 21%.
set.seed(100)
tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "polynomial", 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.1775
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.38875 0.03972562
## 2 0.01778279 0.37375 0.04387878
## 3 0.03162278 0.35875 0.04752558
## 4 0.05623413 0.33500 0.05197489
## 5 0.10000000 0.31875 0.04686342
## 6 0.17782794 0.24875 0.04101575
## 7 0.31622777 0.21125 0.03197764
## 8 0.56234133 0.20250 0.03476109
## 9 1.00000000 0.19375 0.03019037
## 10 1.77827941 0.18500 0.03574602
## 11 3.16227766 0.18250 0.04174992
## 12 5.62341325 0.17875 0.03634805
## 13 10.00000000 0.17750 0.04031129
svm.poly <- svm(Purchase ~ ., kernel = "polynomial", degree = 2, data = OJ.train, cost = tune.out$best.parameter$cost)
summary(svm.poly)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "polynomial",
## degree = 2, cost = tune.out$best.parameter$cost)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 10
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 337
##
## ( 172 165 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train.pred <- predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 450 38
## MM 72 240
(450+240)/(450+240+38+72)
## [1] 0.8625
Training error rate is approximately 14%.
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 146 19
## MM 37 68
(146+68)/(19+37+146+68)
## [1] 0.7925926
Testing error rate is approximately 21%.
Tuning reduces Training error rate but Testing error rate is about the same.
(h) Overall, which approach seems to give the best results on this data ?
Radial basis kernel produces the minimum mis-classification error on both train and test data.