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(500)
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 yaxis.
plot(x1[y==0], x2[y==0], col="red", xlab="X1",ylab="X2",)
points(x1[y==1], x2[y==1], col="blue",)
(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.318 -1.163 1.065 1.163 1.285
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.03163 0.08968 0.353 0.724
## x1 -0.14360 0.29982 -0.479 0.632
## x2 0.46827 0.31376 1.492 0.136
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.02 on 499 degrees of freedom
## Residual deviance: 690.53 on 497 degrees of freedom
## AIC: 696.53
##
## 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)
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 = "red", xlab = "X1", ylab = "X2")
points(data_neg$x1, data_neg$x2, col = "blue")
(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).
lm_fit2 <- glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1*x2) + log(x2), data = data, family = binomial)
summary(lm_fit2)
##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2) + log(x2),
## family = binomial, data = data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -9.395e-04 -2.000e-08 2.000e-08 2.000e-08 9.244e-04
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 8.396e+01 5.224e+04 0.002 0.999
## poly(x1, 2)1 -4.436e+03 2.524e+05 -0.018 0.986
## poly(x1, 2)2 3.050e+04 1.259e+06 0.024 0.981
## poly(x2, 2)1 1.352e+03 9.597e+05 0.001 0.999
## poly(x2, 2)2 -2.912e+04 1.266e+06 -0.023 0.982
## I(x1 * x2) 1.545e+03 1.310e+05 0.012 0.991
## log(x2) -9.079e+00 8.248e+03 -0.001 0.999
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 3.4219e+02 on 247 degrees of freedom
## Residual deviance: 2.0332e-06 on 241 degrees of freedom
## (252 observations deleted due to missingness)
## AIC: 14
##
## 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_prob2 <- predict(lm_fit2, data, type = "response")
lm_pred2 <- ifelse(lm_prob2 > 0.5, 1, 0)
data_pos2 <- data[lm_pred2 == 1, ]
data_neg2 <- data[lm_pred2 == 0, ]
plot(data_pos2$x1, data_pos2$x2, col = "red", xlab = "X1", ylab = "X2")
points(data_neg2$x1, data_neg2$x2, col = "blue")
(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)
svm_fit3 <- svm(as.factor(y) ~ x1 + x2, kernel = "linear", cost=0.4, scale=FALSE)
svm_pred3 <- predict(svm_fit3, data)
data_pos3 <- data[svm_pred3 == 1, ]
data_neg3 <- data[svm_pred3 == 0, ]
plot(data_pos3$x1, data_pos3$x2, col = "red", xlab = "X1", ylab = "X2")
points(data_neg3$x1, data_neg3$x2, col = "blue")
(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_fit4 <- svm(as.factor(y) ~ x1 + x2, data, gamma = 1)
svm_pred4 <- predict(svm_fit4, data)
data_pos4 <- data[svm_pred4 == 1, ]
data_neg4 <- data[svm_pred4 == 0, ]
plot(data_pos4$x1, data_pos4$x2, col = "red", xlab = "X1", ylab = "X2")
points(data_neg4$x1, data_neg4$x2, col = "blue")
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(ISLR2)
library(e1071)
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.
mpg01 <- ifelse(Auto$mpg > median(Auto$mpg),1,0)
Auto$mpg01 <- as.factor(mpg01)
(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. Note you will need to fit the classifier without the gas mileage variable to produce sensible results.
set.seed(100)
tune_linear <-tune(svm, mpg01 ~ ., data=Auto[,-1], kernel='linear', ranges = list(cost=c(0.01,.1, 1, 10, 100)))
summary(tune_linear)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.01
##
## - best performance: 0.08929487
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.08929487 0.04382379
## 2 1e-01 0.09442308 0.04354788
## 3 1e+00 0.09185897 0.02451228
## 4 1e+01 0.09955128 0.03291438
## 5 1e+02 0.13532051 0.05686046
The lowest CV error was at 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(12)
tune_poly <- tune(svm, mpg01 ~ ., data = Auto[,-1], kernel = "polynomial", ranges = list(cost = c(0.1, 1, 5, 10), degree = c(2, 3, 4)))
summary(tune_poly)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 10 2
##
## - best performance: 0.535641
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.5536538 0.05054135
## 2 1.0 2 0.5536538 0.05054135
## 3 5.0 2 0.5536538 0.05054135
## 4 10.0 2 0.5356410 0.05557790
## 5 0.1 3 0.5536538 0.05054135
## 6 1.0 3 0.5536538 0.05054135
## 7 5.0 3 0.5536538 0.05054135
## 8 10.0 3 0.5536538 0.05054135
## 9 0.1 4 0.5536538 0.05054135
## 10 1.0 4 0.5536538 0.05054135
## 11 5.0 4 0.5536538 0.05054135
## 12 10.0 4 0.5536538 0.05054135
After using SVMs with a polynomial basis kernel, the data shows that a cost=10 and degree=2 gave the lowest CV error.
set.seed(12)
tune_rad <- tune(svm, mpg01 ~ ., data = Auto[,-1], kernel = "radial", ranges = list(cost = c(0.1, 1, 5, 10), degree = c(2, 3, 4), gamma=c(0.01,0.1,10,25,100)))
summary(tune_rad)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree gamma
## 5 2 0.1
##
## - best performance: 0.07378205
##
## - Detailed performance results:
## cost degree gamma error dispersion
## 1 0.1 2 0.01 0.11467949 0.03818090
## 2 1.0 2 0.01 0.08916667 0.04943472
## 3 5.0 2 0.01 0.09929487 0.05256797
## 4 10.0 2 0.01 0.09423077 0.05225309
## 5 0.1 3 0.01 0.11467949 0.03818090
## 6 1.0 3 0.01 0.08916667 0.04943472
## 7 5.0 3 0.01 0.09929487 0.05256797
## 8 10.0 3 0.01 0.09423077 0.05225309
## 9 0.1 4 0.01 0.11467949 0.03818090
## 10 1.0 4 0.01 0.08916667 0.04943472
## 11 5.0 4 0.01 0.09929487 0.05256797
## 12 10.0 4 0.01 0.09423077 0.05225309
## 13 0.1 2 0.10 0.09173077 0.05085151
## 14 1.0 2 0.10 0.09416667 0.04752480
## 15 5.0 2 0.10 0.07378205 0.04803317
## 16 10.0 2 0.10 0.07378205 0.04953068
## 17 0.1 3 0.10 0.09173077 0.05085151
## 18 1.0 3 0.10 0.09416667 0.04752480
## 19 5.0 3 0.10 0.07378205 0.04803317
## 20 10.0 3 0.10 0.07378205 0.04953068
## 21 0.1 4 0.10 0.09173077 0.05085151
## 22 1.0 4 0.10 0.09416667 0.04752480
## 23 5.0 4 0.10 0.07378205 0.04803317
## 24 10.0 4 0.10 0.07378205 0.04953068
## 25 0.1 2 10.00 0.55365385 0.05054135
## 26 1.0 2 10.00 0.50269231 0.06127436
## 27 5.0 2 10.00 0.49506410 0.06718518
## 28 10.0 2 10.00 0.49506410 0.06718518
## 29 0.1 3 10.00 0.55365385 0.05054135
## 30 1.0 3 10.00 0.50269231 0.06127436
## 31 5.0 3 10.00 0.49506410 0.06718518
## 32 10.0 3 10.00 0.49506410 0.06718518
## 33 0.1 4 10.00 0.55365385 0.05054135
## 34 1.0 4 10.00 0.50269231 0.06127436
## 35 5.0 4 10.00 0.49506410 0.06718518
## 36 10.0 4 10.00 0.49506410 0.06718518
## 37 0.1 2 25.00 0.55365385 0.05054135
## 38 1.0 2 25.00 0.52820513 0.05784327
## 39 5.0 2 25.00 0.51544872 0.05612663
## 40 10.0 2 25.00 0.51544872 0.05612663
## 41 0.1 3 25.00 0.55365385 0.05054135
## 42 1.0 3 25.00 0.52820513 0.05784327
## 43 5.0 3 25.00 0.51544872 0.05612663
## 44 10.0 3 25.00 0.51544872 0.05612663
## 45 0.1 4 25.00 0.55365385 0.05054135
## 46 1.0 4 25.00 0.52820513 0.05784327
## 47 5.0 4 25.00 0.51544872 0.05612663
## 48 10.0 4 25.00 0.51544872 0.05612663
## 49 0.1 2 100.00 0.55365385 0.05054135
## 50 1.0 2 100.00 0.55365385 0.05054135
## 51 5.0 2 100.00 0.55365385 0.05054135
## 52 10.0 2 100.00 0.55365385 0.05054135
## 53 0.1 3 100.00 0.55365385 0.05054135
## 54 1.0 3 100.00 0.55365385 0.05054135
## 55 5.0 3 100.00 0.55365385 0.05054135
## 56 10.0 3 100.00 0.55365385 0.05054135
## 57 0.1 4 100.00 0.55365385 0.05054135
## 58 1.0 4 100.00 0.55365385 0.05054135
## 59 5.0 4 100.00 0.55365385 0.05054135
## 60 10.0 4 100.00 0.55365385 0.05054135
After using SVMs with a radial basis kernel, the data shows that a cost=5, degree=2, and a gamma=0.10 gave the lowest CV error.
(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(mpg01 ~ ., data = Auto[,-1], kernel = "linear", cost = 1)
svm_poly <- svm(mpg01 ~ ., data = Auto[,-1], kernel = "polynomial", cost = 100,
degree=2)
svm_radial <- svm(mpg01 ~ ., data = Auto[,-1], kernel = "radial", cost = 100, gamma = 0.01)
plotpairs <- function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpg01", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}
plotpairs(svm_linear)
plotpairs(svm_poly)
plotpairs(svm_radial)
detach(Auto)
This problem involves the OJ data set which is part of the ISLR2 package.
library(ISLR2)
attach(OJ)
set.seed(800)
(a) Create a training set containing a random sample of 800 observations., and a test set containing the remaining observations.
set.seed(2)
intrain <- sample(dim(OJ)[1], 800)
OJ_train <- OJ[intrain, ]
OJ_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.
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: 426
##
## ( 212 214 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The SVM has 426 support vectors with 2 classes being Citrus Hill and Minute Maid.
(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 430 60
## MM 73 237
mean(train_pred != OJ_train$Purchase)
## [1] 0.16625
The training error rate is 16.625%
test_pred <- predict(svm_linear, OJ_test)
table(OJ_test$Purchase, test_pred)
## test_pred
## CH MM
## CH 144 19
## MM 33 74
mean(test_pred != OJ_test$Purchase)
## [1] 0.1925926
The test error rate is 19.259%.
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(5)
tune_linear <- tune(svm, Purchase~., data=OJ_train, kernel='linear', ranges=list(cost=10^seq(-2,1,by=0.25)))
summary(tune_linear)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 3.162278
##
## - best performance: 0.16
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17125 0.02638523
## 2 0.01778279 0.17125 0.02949223
## 3 0.03162278 0.16750 0.02648375
## 4 0.05623413 0.16750 0.02140872
## 5 0.10000000 0.16625 0.02285978
## 6 0.17782794 0.16875 0.02585349
## 7 0.31622777 0.16750 0.02443813
## 8 0.56234133 0.16625 0.02128673
## 9 1.00000000 0.16625 0.02285978
## 10 1.77827941 0.16500 0.02266912
## 11 3.16227766 0.16000 0.02188988
## 12 5.62341325 0.16500 0.02486072
## 13 10.00000000 0.16375 0.02598744
The cost that gave the lowest error was at c=10.
(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_linear$best.parameters$cost)
train_predlinear <- predict(svm_linear, OJ_train)
table(OJ_train$Purchase, train_predlinear)
## train_predlinear
## CH MM
## CH 433 57
## MM 71 239
mean(train_predlinear != OJ_train$Purchase)
## [1] 0.16
test_predlinear <- predict(svm_linear, OJ_test)
table(OJ_test$Purchase, test_predlinear)
## test_predlinear
## CH MM
## CH 143 20
## MM 30 77
mean(test_predlinear != OJ_test$Purchase)
## [1] 0.1851852
The training error rate is 16% and the test error rate is 18.52%.
(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=OJ_train)
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: 355
##
## ( 175 180 )
##
##
## 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 449 41
## MM 63 247
mean(train.pred != OJ_train$Purchase)
## [1] 0.13
test.pred <- predict(svm_radial, OJ_test)
table(OJ_test$Purchase, test.pred)
## test.pred
## CH MM
## CH 143 20
## MM 33 74
mean(test.pred != OJ_test$Purchase)
## [1] 0.1962963
The training error rate was 13% and the test error rate is 19.63%.
set.seed(755)
tune_radial <- tune(svm, Purchase ~ ., data = OJ_train, kernel = "radial", ranges = list(cost = 10^seq(-2,
1, by = 0.25)))
summary(tune_radial)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 3.162278
##
## - best performance: 0.1675
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.38750 0.04448783
## 2 0.01778279 0.38750 0.04448783
## 3 0.03162278 0.35000 0.05432669
## 4 0.05623413 0.19250 0.02838231
## 5 0.10000000 0.17625 0.02598744
## 6 0.17782794 0.17375 0.03251602
## 7 0.31622777 0.16875 0.03498512
## 8 0.56234133 0.17000 0.03238227
## 9 1.00000000 0.17250 0.03476109
## 10 1.77827941 0.17250 0.03809710
## 11 3.16227766 0.16750 0.03545341
## 12 5.62341325 0.16750 0.03343734
## 13 10.00000000 0.17750 0.03106892
svm_radial <- svm(Purchase ~ ., data = OJ_train, kernel = "radial", cost = tune_radial$best.parameters$cost)
train_predrad <- predict(svm_radial, OJ_train)
table(OJ_train$Purchase, train_predrad)
## train_predrad
## CH MM
## CH 453 37
## MM 65 245
mean(train_predrad != OJ_train$Purchase)
## [1] 0.1275
test_predrad <- predict(svm_radial, OJ_test)
table(OJ_test$Purchase, test_predrad)
## test_predrad
## CH MM
## CH 142 21
## MM 32 75
mean(test_predrad != OJ_test$Purchase)
## [1] 0.1962963
The training error rate was 12.75% and the test error rate is 19.63%.
(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)
summary(svm_poly)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ_train, kernel = "polynomial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 1
## degree: 3
## coef.0: 0
##
## Number of Support Vectors: 408
##
## ( 203 205 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train.predpoly <- predict(svm_poly, OJ_train)
table(OJ_train$Purchase, train.predpoly)
## train.predpoly
## CH MM
## CH 457 33
## MM 93 217
mean(train.predpoly != OJ_train$Purchase)
## [1] 0.1575
test.predpoly <- predict(svm_poly, OJ_test)
table(OJ_test$Purchase, test.predpoly)
## test.predpoly
## CH MM
## CH 146 17
## MM 38 69
mean(test.predpoly != OJ_test$Purchase)
## [1] 0.2037037
The training error rate was 15.75% and the test error rate is 20.37%.
set.seed(755)
tune_poly <- tune(svm, Purchase ~ ., data = OJ_train, kernel = "polynomial", ranges = list(cost = 10^seq(-2,
1, by = 0.25)))
summary(tune_poly)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.17875
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.36750 0.04972145
## 2 0.01778279 0.36750 0.05041494
## 3 0.03162278 0.33375 0.05070681
## 4 0.05623413 0.31750 0.05565269
## 5 0.10000000 0.29250 0.06015027
## 6 0.17782794 0.23500 0.04923018
## 7 0.31622777 0.20625 0.04535738
## 8 0.56234133 0.19625 0.03175973
## 9 1.00000000 0.18875 0.02664713
## 10 1.77827941 0.18125 0.02301117
## 11 3.16227766 0.18875 0.01904855
## 12 5.62341325 0.19000 0.02188988
## 13 10.00000000 0.17875 0.03230175
svm_poly <- svm(Purchase ~ ., data = OJ_train, kernel = "polynomial", cost = tune_radial$best.parameters$cost)
train_predpoly <- predict(svm_poly, OJ_train)
table(OJ_train$Purchase, train_predpoly)
## train_predpoly
## CH MM
## CH 453 37
## MM 77 233
mean(train_predpoly != OJ_train$Purchase)
## [1] 0.1425
test_predpoly <- predict(svm_poly, OJ_test)
table(OJ_test$Purchase, test_predpoly)
## test_predpoly
## CH MM
## CH 146 17
## MM 34 73
mean(test_predpoly != OJ_test$Purchase)
## [1] 0.1888889
The training error rate was 14.25% and the test error rate is 18.89%.
(h) Overall, which approach seems to give the best results on this data?
The SVM with a radial kernel gave the best results on this data.
detach(OJ)