library(ISLR)
library(e1071)
library(glm2)
library(knitr)
#library(ggplot2)
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:
x1=runif (500) -0.5
x2=runif (500) -0.5
y=1( x12-x22 > 0)
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,x2,col=ifelse(y,'red','blue'))
(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
glm.fit=glm(y~. ,family='binomial', data=data.frame(x1,x2,y))
glm.fit
##
## Call: glm(formula = y ~ ., family = "binomial", data = data.frame(x1,
## x2, y))
##
## Coefficients:
## (Intercept) x1 x2
## -0.0356 0.1687 -0.2531
##
## Degrees of Freedom: 499 Total (i.e. Null); 497 Residual
## Null Deviance: 692.9
## Residual Deviance: 691.9 AIC: 697.9
(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.
glm.pred=predict(glm.fit,data.frame(x1,x2))
plot(x1,x2,col=ifelse(glm.pred>0,'red','blue'),pch=ifelse(as.integer(glm.pred>0) == y,1,4))
(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).
glm.fit=glm(y~poly(x1,2)+poly(x2,2) ,family='binomial', data=data.frame(x1,x2,y))
(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.pred=predict(glm.fit,data.frame(x1,x2)) # returns the log-odds.
plot(x1,x2,col=ifelse(glm.pred>0,'red','blue'),pch=ifelse(as.integer(glm.pred>0) == y,1,4))
(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(y~.,data=data.frame(x1,x2,y=as.factor(y)),kernel='linear')
svm.pred=predict(svm.fit,data.frame(x1,x2),type='response')
plot(x1,x2,col=ifelse(svm.pred!=0,'red','blue'),pch=ifelse(svm.pred == y,1,4))
(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.fit=svm(y~.,data=data.frame(x1,x2,y=as.factor(y)),kernel='polynomial',degree=2)
svm.pred=predict(svm.fit,data.frame(x1,x2),type='response')
plot(x1,x2,col=ifelse(svm.pred!=0,'red','blue'),pch=ifelse(svm.pred == y,1,4))
(i) Comment on your results.
On the plots we have circles as correct and crosses as incorrect. From the plots can see that the polynomial logit model from part (e) and (f), works better than the SVM model.
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.
var <- ifelse(Auto$mpg > median(Auto$mpg), 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
The best parameter is 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.
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.3060897
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.6019231 0.06346118
## 2 1e-01 2 0.6019231 0.06346118
## 3 1e+00 2 0.6019231 0.06346118
## 4 5e+00 2 0.6019231 0.06346118
## 5 1e+01 2 0.5841667 0.07806609
## 6 1e+02 2 0.3060897 0.07318010
## 7 1e-02 3 0.6019231 0.06346118
## 8 1e-01 3 0.6019231 0.06346118
## 9 1e+00 3 0.6019231 0.06346118
## 10 5e+00 3 0.6019231 0.06346118
## 11 1e+01 3 0.6019231 0.06346118
## 12 1e+02 3 0.3413462 0.14973473
## 13 1e-02 4 0.6019231 0.06346118
## 14 1e-01 4 0.6019231 0.06346118
## 15 1e+00 4 0.6019231 0.06346118
## 16 5e+00 4 0.6019231 0.06346118
## 17 1e+01 4 0.6019231 0.06346118
## 18 1e+02 4 0.6019231 0.06346118
tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), 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
## 10 0.01
##
## - best performance: 0.02044872
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-02 1e-02 0.59461538 0.08083319
## 2 1e-01 1e-02 0.08698718 0.04560056
## 3 1e+00 1e-02 0.07160256 0.03373099
## 4 5e+00 1e-02 0.05121795 0.02967002
## 5 1e+01 1e-02 0.02044872 0.01077927
## 6 1e+02 1e-02 0.02044872 0.02020886
## 7 1e-02 1e-01 0.22730769 0.10474192
## 8 1e-01 1e-01 0.07673077 0.03419344
## 9 1e+00 1e-01 0.05121795 0.03203768
## 10 5e+00 1e-01 0.02557692 0.01709522
## 11 1e+01 1e-01 0.02301282 0.02244393
## 12 1e+02 1e-01 0.03070513 0.03153205
## 13 1e-02 1e+00 0.59461538 0.08083319
## 14 1e-01 1e+00 0.59461538 0.08083319
## 15 1e+00 1e+00 0.06141026 0.03026776
## 16 5e+00 1e+00 0.06397436 0.02789391
## 17 1e+01 1e+00 0.06397436 0.02789391
## 18 1e+02 1e+00 0.06397436 0.02789391
## 19 1e-02 5e+00 0.59461538 0.08083319
## 20 1e-01 5e+00 0.59461538 0.08083319
## 21 1e+00 5e+00 0.52051282 0.09421163
## 22 5e+00 5e+00 0.51538462 0.10051415
## 23 1e+01 5e+00 0.51538462 0.10051415
## 24 1e+02 5e+00 0.51538462 0.10051415
## 25 1e-02 1e+01 0.59461538 0.08083319
## 26 1e-01 1e+01 0.59461538 0.08083319
## 27 1e+00 1e+01 0.55384615 0.09432787
## 28 5e+00 1e+01 0.54358974 0.09085645
## 29 1e+01 1e+01 0.54358974 0.09085645
## 30 1e+02 1e+01 0.54358974 0.09085645
## 31 1e-02 1e+02 0.59461538 0.08083319
## 32 1e-01 1e+02 0.59461538 0.08083319
## 33 1e+00 1e+02 0.59461538 0.08083319
## 34 5e+00 1e+02 0.59461538 0.08083319
## 35 1e+01 1e+02 0.59461538 0.08083319
## 36 1e+02 1e+02 0.59461538 0.08083319
The lowest cross validation error was gamma at .01 with a cost of 100.
(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 = 100, 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)
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)
train <- sample(nrow(OJ), 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.
svm.linear <- svm(Purchase ~ ., data = OJ.train, kernel = "linear", 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: 435
##
## ( 219 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
This created 435 support vectors out of 800 points. 219 of CH and 216 of 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 420 65
## MM 75 240
(75+65)/(75+65+420+240)
## [1] 0.175
test.pred <- predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 153 15
## MM 33 69
(33 + 15) / (153+69+33+15)
## [1] 0.1777778
Training error is 17.5% and test error is 17.778%
(d) Use the tune() function to select an optimal cost. Consider valuesin the range 0.01 to 10.
set.seed(1)
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
## 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
With this we can see that the best parameter for cost is .01
(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.parameter$cost)
train.pred <- predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 423 62
## MM 70 245
(70+62)/(70+62+423+245)
## [1] 0.165
test.pred <- predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 156 12
## MM 29 73
(29+12)/(29+12+156+73)
## [1] 0.1518519
With the new value we get a training error of 16.5% and a test error of 15.185%
(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: 373
##
## ( 188 185 )
##
##
## 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 441 44
## MM 77 238
(77+44)/(77+44+441+238)
## [1] 0.15125
test.pred <- predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 151 17
## MM 33 69
(33+17)/(33+17+151+69)
## [1] 0.1851852
set.seed(1)
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
## 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 = 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: 0.5623413
##
## Number of Support Vectors: 397
##
## ( 200 197 )
##
##
## 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 437 48
## MM 71 244
(71+48)/(71+48+437+244)
## [1] 0.14875
test.pred <- predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 150 18
## MM 30 72
(30+18)/(30+18+150+72)
## [1] 0.1777778
Tuning reduced the error slightly.
(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
##
## ( 225 222 )
##
##
## 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 449 36
## MM 110 205
(110+36)/(110+36+449+205)
## [1] 0.1825
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 153 15
## MM 45 57
(45+15)/(45+15+153+57)
## [1] 0.2222222
set.seed(1)
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
## 3.162278
##
## - best performance: 0.1775
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39125 0.04210189
## 2 0.01778279 0.37125 0.03537988
## 3 0.03162278 0.36500 0.03476109
## 4 0.05623413 0.33750 0.04714045
## 5 0.10000000 0.32125 0.05001736
## 6 0.17782794 0.24500 0.04758034
## 7 0.31622777 0.19875 0.03972562
## 8 0.56234133 0.20500 0.03961621
## 9 1.00000000 0.20250 0.04116363
## 10 1.77827941 0.18500 0.04199868
## 11 3.16227766 0.17750 0.03670453
## 12 5.62341325 0.18375 0.03064696
## 13 10.00000000 0.18125 0.02779513
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: 3.162278
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 385
##
## ( 197 188 )
##
##
## 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 451 34
## MM 90 225
(90+34)/(90+34+451+225)
## [1] 0.155
test.pred <- predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 154 14
## MM 41 61
(41+14)/(41+14+154+61)
## [1] 0.2037037
Once again tuning slightly reduced the error. From 18.25% to 15.5% for training, and 22.22% to 20.37% in the test.
(h) Overall, which approach seems to give the best results on this data?
Overall, the radial basis seemed to give the lowest error rate for both train and test.