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(123)
x1 <- runif (500) - 0.5
x2 <- runif (500) - 0.5
y=(1*(x1*x1 - x2*x2 > 0))
dataf<-data.frame(x1=x1,
x2=x2,
y=y)(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.
ggplot(data=dataf,mapping=aes(x=x1,y=x2,color=y))+
geom_point() +
theme(legend.position = "none")(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
glm.fit = glm(y~.,dataf, family = "binomial")
summary(glm.fit)##
## Call:
## glm(formula = y ~ ., family = "binomial", data = dataf)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.227 -1.200 1.133 1.157 1.188
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.04792 0.08949 0.535 0.592
## x1 -0.03999 0.31516 -0.127 0.899
## x2 0.11509 0.30829 0.373 0.709
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.86 on 499 degrees of freedom
## Residual deviance: 692.71 on 497 degrees of freedom
## AIC: 698.71
##
## Number of Fisher Scoring iterations: 3
(d) Apply this model to the training data in order to obtain a predictedclass label for each training observation. Plot the observations,colored according to the predicted class labels. The decision boundary should be linear.
glm.prob = predict(glm.fit, dataf, type = "response")
mean(dataf$y)## [1] 0.512
dataf$glm.y = as.factor(ifelse(glm.prob > 0.51, 1, 0))
ggplot(data=dataf,mapping=aes(x=x1,y=x2,color=glm.y))+
geom_point() +
theme(legend.position = "none")(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X21 , X1×X2, log(X2), and so forth).
glm.fit1 = glm(y~ poly(x1,2) + poly(x2,2), dataf, family = "binomial")## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
(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.
glm.prob1 = predict(glm.fit1, dataf, type = "response")
dataf$glm.y1 = as.factor(ifelse(glm.prob1 > 0.53, 1, 0))
ggplot(data=dataf,mapping=aes(x=x1,y=x2,color=glm.y1))+
geom_point() +
theme(legend.position = "none")(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, dataf, kernel = "linear", cost = 0.1)
dataf$svm.y = as_factor(predict(svm_fit, dataf))
ggplot(data=dataf,mapping=aes(x=x1,y=x2,color=svm.y))+
geom_point() +
theme_light() +
theme(legend.position = "none")(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_fit1 = svm(as.factor(y) ~ x1 + x2, dataf, kernel = "radial")
dataf$svm.y1 = as.factor(predict(svm_fit1, dataf))
ggplot(data=dataf,mapping=aes(x=x1,y=x2,color=svm.y1))+
geom_point() +
theme(legend.position = "none")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.
Auto <- tibble(Auto) %>% mutate(mpg_binary = as_factor(ifelse(mpg > median(mpg), 1, 0)))
Auto(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(123)
tune_svm = tune(svm, mpg_binary ~ . -mpg, data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 20)))
summary(tune_svm)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.01
##
## - best performance: 0.08910256
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.08910256 0.03791275
## 2 0.10 0.09403846 0.04842472
## 3 1.00 0.09147436 0.05817937
## 4 5.00 0.10423077 0.06425850
## 5 10.00 0.10673077 0.06562804
## 6 20.00 0.11942308 0.07388100
(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(123)
tune_svm1 = tune(svm, mpg_binary ~ . -mpg, data = Auto, kernel = "polynomial", ranges = list((cost = c(0.01, 0.1, 1, 5, 10)), degree = c(2,3,4,5)))
summary(tune_svm1)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## Var1 degree
## 0.01 2
##
## - best performance: 0.5817308
##
## - Detailed performance results:
## Var1 degree error dispersion
## 1 0.01 2 0.5817308 0.04740051
## 2 0.10 2 0.5817308 0.04740051
## 3 1.00 2 0.5817308 0.04740051
## 4 5.00 2 0.5817308 0.04740051
## 5 10.00 2 0.5817308 0.04740051
## 6 0.01 3 0.5817308 0.04740051
## 7 0.10 3 0.5817308 0.04740051
## 8 1.00 3 0.5817308 0.04740051
## 9 5.00 3 0.5817308 0.04740051
## 10 10.00 3 0.5817308 0.04740051
## 11 0.01 4 0.5817308 0.04740051
## 12 0.10 4 0.5817308 0.04740051
## 13 1.00 4 0.5817308 0.04740051
## 14 5.00 4 0.5817308 0.04740051
## 15 10.00 4 0.5817308 0.04740051
## 16 0.01 5 0.5817308 0.04740051
## 17 0.10 5 0.5817308 0.04740051
## 18 1.00 5 0.5817308 0.04740051
## 19 5.00 5 0.5817308 0.04740051
## 20 10.00 5 0.5817308 0.04740051
- The least cross validation error is achieved for cost = 0.1 and degree = 2.
set.seed(123)
tune_svm2 = tune(svm, mpg_binary ~ . -mpg, data = Auto, kernel = "radial", ranges = list((cost = c(0.01, 0.1, 1, 5, 10)), gamma = c(0.01, 0.1, 1, 5, 10)))
summary(tune_svm2)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## Var1 gamma
## 0.01 0.1
##
## - best performance: 0.08653846
##
## - Detailed performance results:
## Var1 gamma error dispersion
## 1 0.01 0.01 0.08910256 0.03791275
## 2 0.10 0.01 0.08910256 0.03791275
## 3 1.00 0.01 0.08910256 0.03791275
## 4 5.00 0.01 0.08910256 0.03791275
## 5 10.00 0.01 0.08910256 0.03791275
## 6 0.01 0.10 0.08653846 0.03578151
## 7 0.10 0.10 0.08653846 0.03578151
## 8 1.00 0.10 0.08653846 0.03578151
## 9 5.00 0.10 0.08653846 0.03578151
## 10 10.00 0.10 0.08653846 0.03578151
## 11 0.01 1.00 0.08660256 0.04466420
## 12 0.10 1.00 0.08660256 0.04466420
## 13 1.00 1.00 0.08660256 0.04466420
## 14 5.00 1.00 0.08660256 0.04466420
## 15 10.00 1.00 0.08660256 0.04466420
## 16 0.01 5.00 0.51532051 0.06910961
## 17 0.10 5.00 0.51532051 0.06910961
## 18 1.00 5.00 0.51532051 0.06910961
## 19 5.00 5.00 0.51532051 0.06910961
## 20 10.00 5.00 0.51532051 0.06910961
## 21 0.01 10.00 0.53583333 0.07213142
## 22 0.10 10.00 0.53583333 0.07213142
## 23 1.00 10.00 0.53583333 0.07213142
## 24 5.00 10.00 0.53583333 0.07213142
## 25 10.00 10.00 0.53583333 0.07213142
(d) Make some plots to back up your assertions in (b) and (c).
svm_linear = svm(mpg_binary ~ ., data = Auto, kernel = "linear", cost = 1)
svm_poly = svm(mpg_binary ~ ., data = Auto, kernel = "polynomial", cost = 100, degree = 2)
svm_radial = svm(mpg_binary ~ ., data = Auto, kernel = "radial", cost = 100, gamma = 0.01)
plotpairs<-function(fit){
for(name in names(Auto)[!(names(Auto)) %in% c("mpg","name","mpg_binary")]){
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.
set.seed(1)
ttrain = sample(nrow(OJ), 800)
OJ.train = OJ[ttrain,]
OJ.test = OJ[-ttrain,](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.
OJ.svm_linear = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = 0.01)
summary(OJ.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: 435
##
## ( 219 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
CH and remaining 216 belong to the class MM.(c) What are the training and test error rates?
pred_train = predict(OJ.svm_linear, OJ.train)
(train_table = table(OJ.train$Purchase, pred_train))## pred_train
## CH MM
## CH 420 65
## MM 75 240
(train_error=(train_table[2]+train_table[3])/nrow(OJ.train))## [1] 0.175
pred_test = predict(OJ.svm_linear, OJ.test)
(table_test = table(OJ.test$Purchase, pred_test))## pred_test
## CH MM
## CH 153 15
## MM 33 69
(test_error=(table_test[2]+table_test[3])/nrow(OJ.test))## [1] 0.1777778
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(123)
tune_OJ = tune(svm, Purchase ~ . , data = OJ.train, kernel = "linear", ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
summary(tune_OJ)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.05623413
##
## - best performance: 0.175
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.18125 0.04903584
## 2 0.01778279 0.18375 0.04450733
## 3 0.03162278 0.17750 0.04669642
## 4 0.05623413 0.17500 0.04370037
## 5 0.10000000 0.17875 0.04450733
## 6 0.17782794 0.17625 0.04427267
## 7 0.31622777 0.17625 0.04656611
## 8 0.56234133 0.17750 0.04479893
## 9 1.00000000 0.17750 0.04479893
## 10 1.77827941 0.17500 0.04208127
## 11 3.16227766 0.17625 0.04267529
## 12 5.62341325 0.17875 0.04450733
## 13 10.00000000 0.18000 0.04495368
best<-tune_OJ$best.parameters$costCompute the training and test error rates using this new value for cost.
set.seed(123)
OJ.svm_best = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = best)
pred_train_best = predict(OJ.svm_best, OJ.train)
(train_table_best = table(OJ.train$Purchase, pred_train_best))## pred_train_best
## CH MM
## CH 422 63
## MM 70 245
(train_error_best=(train_table_best[2]+train_table_best[3])/nrow(OJ.train))## [1] 0.16625
pred_test_best = predict(OJ.svm_best, OJ.test)
(test_table_best = table(OJ.test$Purchase, pred_test_best))## pred_test_best
## CH MM
## CH 154 14
## MM 31 71
(test_error_best=(test_table_best[2]+test_table_best[3])/nrow(OJ.test))## [1] 0.1666667
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
- 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.
OJ.svm_radial = svm(Purchase ~ ., kernel = "radial", data = OJ.train)
summary(OJ.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: 373
##
## ( 188 185 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
CH and remaining 185 belong to the class MM.- What are the training and test error rates?
pred_train_rad = predict(OJ.svm_radial, OJ.train)
(train_table_rad = table(OJ.train$Purchase, pred_train_rad))## pred_train_rad
## CH MM
## CH 441 44
## MM 77 238
(train_error=(train_table_rad[2]+train_table_rad[3])/nrow(OJ.train))## [1] 0.15125
pred_test_rad = predict(OJ.svm_radial, OJ.test)
(train_test_rad = table(OJ.test$Purchase, pred_test_rad))## pred_test_rad
## CH MM
## CH 151 17
## MM 33 69
(test_error_rad=(train_test_rad[2]+train_test_rad[3])/nrow(OJ.test))## [1] 0.1851852
- Use the tune() function to select an optimal cost. - Consider values in the range 0.01 to 10.
set.seed(123)
tune_OJ_rad = tune(svm, Purchase ~ . , data = OJ.train, kernel = "radial", ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
best_rad<-tune_OJ_rad$best.parameters$cost- Compute the training and test error rates using this new value for cost.
OJ.svm_best_rad = svm(Purchase ~ ., kernel = "radial", data = OJ.train, cost = best_rad)
pred_train_best_rad = predict(OJ.svm_best_rad, OJ.train)
train_table_best_rad = table(OJ.train$Purchase, pred_train_best_rad)
(train_error_best_rad=(train_table_best_rad[2]+train_table_best_rad[3])/nrow(OJ.train))## [1] 0.15125
pred_test_best_rad = predict(OJ.svm_best_rad, OJ.test)
test_table_best_rad = table(OJ.test$Purchase, pred_test_best_rad)
(test_error_best_rad=(test_table_best_rad[2]+test_table_best_rad[3])/nrow(OJ.test))## [1] 0.1851852
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
- Fit a support vector classifier to the training data, with Purchase as the response and the other variables as predictors. Use the summary() function to produce summary statistics, and describe the results obtained.
OJ.svm_poly = svm(Purchase ~ ., kernel = "poly", data = OJ.train, degree = 2)
summary(OJ.svm_poly)##
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, 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
CH and remaining 222 belong to the class MM.- What are the training and test error rates?
pred_train_poly = predict(OJ.svm_poly, OJ.train)
(train_table_poly = table(OJ.train$Purchase, pred_train_poly))## pred_train_poly
## CH MM
## CH 449 36
## MM 110 205
(train_error_poly=(train_table_poly[2]+train_table_poly[3])/nrow(OJ.train))## [1] 0.1825
pred_test_poly = predict(OJ.svm_poly, OJ.test)
(test_table_poly = table(OJ.test$Purchase, pred_test_poly))## pred_test_poly
## CH MM
## CH 153 15
## MM 45 57
(test_error_poly=(test_table_poly[2]+test_table_poly[3])/nrow(OJ.test))## [1] 0.2222222
- Use the tune() function to select an optimal cost.
set.seed(123)
tune_OJ_poly = tune(svm, Purchase ~ . , data = OJ.train, kernel = "poly", degree = 2, ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
best_poly<-tune_OJ_poly$best.parameters$cost- Compute the training and test error rates using this new value for cost.
OJ.svm_best_poly = svm(Purchase ~ ., kernel = "poly", data = OJ.train, degree = 2, cost = best_poly)
pred_train_best_poly = predict(OJ.svm_best_poly, OJ.train)
(train_table_best_poly = table(OJ.train$Purchase, pred_train_best_poly))## pred_train_best_poly
## CH MM
## CH 447 38
## MM 88 227
(train_error_best_poly=(train_table_best_poly[2]+train_table_best_poly[3])/nrow(OJ.train))## [1] 0.1575
pred_test_best_poly = predict(OJ.svm_best_poly, OJ.test)
(test_table_best_poly = table(OJ.test$Purchase, pred_test_best_poly))## pred_test_best_poly
## CH MM
## CH 154 14
## MM 36 66
(test_error_best_poly=(test_table_best_poly[2]+test_table_best_poly[3])/nrow(OJ.test))## [1] 0.1851852
(h) Overall, which approach seems to give the best results on this data?