library(tidyverse)
## -- Attaching packages -------------------------------------------------------------------------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.0 v purrr 0.3.4
## v tibble 3.0.1 v dplyr 0.8.5
## v tidyr 1.0.2 v stringr 1.4.0
## v readr 1.3.1 v forcats 0.5.0
## -- Conflicts ----------------------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(e1071)
## Warning: package 'e1071' was built under R version 4.0.2
library(LiblineaR)
library(plotly)
## Warning: package 'plotly' was built under R version 4.0.2
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
library(ISLR)
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)
set.seed(420)
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", pch = "+")
points(x1[y == 1], x2[y == 1], col = "blue", pch = 4)
(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.351 -1.211 1.043 1.125 1.228
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.13238 0.08992 1.472 0.141
## x1 -0.22061 0.30856 -0.715 0.475
## x2 -0.34307 0.32103 -1.069 0.285
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 691.10 on 499 degrees of freedom
## Residual deviance: 689.36 on 497 degrees of freedom
## AIC: 695.36
##
## Number of Fisher Scoring iterations: 3
We see from the output above that both x1 and x2 are not significant predictors of y.
(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 = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 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).
lm.fit = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = data, 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.
lm.prob = predict(lm.fit, 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 = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 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(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.1)
svm.pred = predict(svm.fit, data)
data.pos = data[svm.pred == 1, ]
data.neg = data[svm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 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(as.factor(y) ~ x1 + x2, data, gamma = 1)
svm.pred = predict(svm.fit, data)
data.pos = data[svm.pred == 1, ]
data.neg = data[svm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
(i) Comment on your results.
From the exercise we see that the logistic regression with non interactions and the support vector model with linear kernels fail to find the decision boundary, while the SVM with non-linear kernels are able to find this non-linear boundry.
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.
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.
set.seed(1234)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = 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
## 1
##
## - best performance: 0.01525641
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07391026 0.04070168
## 2 1e-01 0.04583333 0.03106348
## 3 1e+00 0.01525641 0.01784872
## 4 5e+00 0.02038462 0.02019157
## 5 1e+01 0.02807692 0.03071101
## 6 1e+02 0.03833333 0.03260322
svm_linear<-tune.out$best.model
svm_linear
##
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, ranges = list(cost = c(0.01,
## 0.1, 1, 5, 10, 100)), kernel = "linear")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 1
##
## Number of Support Vectors: 56
the best parameter where cost = 1 gives us the lowect cross-validation error.
(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.out1 = tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1,
1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out1)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 10 2
##
## - best performance: 0.5433333
##
## - 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.5433333 0.07502112
## 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
svm_poly<-tune.out1$best.model
svm_poly
##
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, ranges = list(cost = c(0.1,
## 1, 5, 10), degree = c(2, 3, 4)), kernel = "polynomial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 10
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 392
The cross-validation error is minimized at cost = 10 and degree = 2 for the polynomial basis.
set.seed(420)
tune.out2 = 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.out2)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 10 0.01
##
## - best performance: 0.02807692
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.1 1e-02 0.08653846 0.03974589
## 2 1.0 1e-02 0.07128205 0.03920204
## 3 5.0 1e-02 0.05339744 0.04044963
## 4 10.0 1e-02 0.02807692 0.03071101
## 5 0.1 1e-01 0.07641026 0.03577232
## 6 1.0 1e-01 0.05596154 0.03738529
## 7 5.0 1e-01 0.03057692 0.02345770
## 8 10.0 1e-01 0.03051282 0.02878864
## 9 0.1 1e+00 0.52897436 0.13817529
## 10 1.0 1e+00 0.06365385 0.02977693
## 11 5.0 1e+00 0.05858974 0.02675671
## 12 10.0 1e+00 0.05858974 0.02675671
## 13 0.1 5e+00 0.55397436 0.06548495
## 14 1.0 5e+00 0.49288462 0.08700043
## 15 5.0 5e+00 0.49288462 0.08700043
## 16 10.0 5e+00 0.49288462 0.08700043
## 17 0.1 1e+01 0.56397436 0.04320447
## 18 1.0 1e+01 0.51820513 0.07841339
## 19 5.0 1e+01 0.51307692 0.07382607
## 20 10.0 1e+01 0.51307692 0.07382607
## 21 0.1 1e+02 0.56397436 0.04320447
## 22 1.0 1e+02 0.56397436 0.04320447
## 23 5.0 1e+02 0.56397436 0.04320447
## 24 10.0 1e+02 0.56397436 0.04320447
svm_radial<-tune.out2$best.model
svm_radial
##
## Call:
## best.tune(method = svm, train.x = mpglevel ~ ., data = Auto, ranges = list(cost = c(0.1,
## 1, 5, 10), gamma = c(0.01, 0.1, 1, 5, 10, 100)), kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 10
##
## Number of Support Vectors: 79
With the radial basis kernal, the lowest cross-validation error is at a cost = 10 and gamma = .01
(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.
set.seed(9004)
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.
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: 442
##
## ( 222 220 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The support vector classifier in this fitted model results in 428 support vectors created out of the 800 observations, where 222 belong to CH level and 220 belong to the MM level.
(c) What are the training and test error rates?
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)# training error
## train.pred
## CH MM
## CH 432 51
## MM 80 237
((80+51)/(432+51+80+237)) #training error
## [1] 0.16375
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 146 24
## MM 22 78
((22+24)/(146+24+22+78))#test error
## [1] 0.1703704
The test error actually is lower then the training error which is surprising to me
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(1563)
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.16625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17000 0.03827895
## 2 0.01778279 0.17250 0.03425801
## 3 0.03162278 0.16875 0.03919768
## 4 0.05623413 0.16875 0.03294039
## 5 0.10000000 0.16875 0.03875224
## 6 0.17782794 0.17125 0.03955042
## 7 0.31622777 0.16875 0.03875224
## 8 0.56234133 0.17000 0.03641962
## 9 1.00000000 0.17000 0.03961621
## 10 1.77827941 0.17000 0.03827895
## 11 3.16227766 0.16625 0.03910900
## 12 5.62341325 0.16875 0.03738408
## 13 10.00000000 0.16625 0.03955042
best<-tune.out$best.parameters$cost
best
## [1] 3.162278
(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 428 55
## MM 74 243
(74+55)/(428 + 55 + 74 + 243)
## [1] 0.16125
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 146 24
## MM 20 80
(20+24)/(146+24+20+80)
## [1] 0.162963
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
set.seed(420)
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: 371
##
## ( 188 183 )
##
##
## 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 42
## MM 74 243
(74+42)/(441+42+74+243)
## [1] 0.145
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 148 22
## MM 27 73
(27+22)/(148+22+27+73)
## [1] 0.1814815
set.seed(800)
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.1778279
##
## - best performance: 0.17125
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39625 0.04332131
## 2 0.01778279 0.39625 0.04332131
## 3 0.03162278 0.34625 0.04788949
## 4 0.05623413 0.19750 0.04158325
## 5 0.10000000 0.17750 0.04556741
## 6 0.17782794 0.17125 0.04860913
## 7 0.31622777 0.17250 0.03855011
## 8 0.56234133 0.17375 0.03884174
## 9 1.00000000 0.17875 0.04291869
## 10 1.77827941 0.18375 0.03998698
## 11 3.16227766 0.18750 0.04526159
## 12 5.62341325 0.19750 0.04116363
## 13 10.00000000 0.19750 0.05163978
svm.radial = svm(Purchase ~ ., data = OJ.train, kernel = "radial", cost = tune.out$best.parameters$cost)
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 439 44
## MM 82 235
(82+44)/(439+44+82+235)
## [1] 0.1575
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 145 25
## MM 30 70
(30+25)/(30+25+70+145)
## [1] 0.2037037
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
set.seed(8000)
svm.poly = svm(Purchase ~ ., data = OJ.train, kernel = "poly", degree = 2)
summary(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: 456
##
## ( 232 224 )
##
##
## 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 33
## MM 111 206
(111+33)/(450+33+111+206)
## [1] 0.18
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 149 21
## MM 34 66
(34+21)/(149+21+34+66)
## [1] 0.2037037
set.seed(300)
tune.out = tune(svm, Purchase ~ ., data = OJ.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.1725
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39750 0.06713378
## 2 0.01778279 0.37500 0.06152010
## 3 0.03162278 0.36375 0.06908379
## 4 0.05623413 0.34125 0.08037456
## 5 0.10000000 0.30625 0.07027970
## 6 0.17782794 0.24500 0.05749396
## 7 0.31622777 0.20500 0.04571956
## 8 0.56234133 0.20000 0.04894725
## 9 1.00000000 0.19500 0.04721405
## 10 1.77827941 0.18750 0.03435921
## 11 3.16227766 0.18000 0.04048319
## 12 5.62341325 0.17625 0.03557562
## 13 10.00000000 0.17250 0.04116363
svm.poly = svm(Purchase ~ ., data = OJ.train, kernel = "poly", degree = 2, cost = tune.out$best.parameters$cost)
train.pred = predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 447 36
## MM 85 232
(85+36)/(447+36+85+232)
## [1] 0.15125
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 148 22
## MM 28 72
(28+22)/(148+22+28+72)
## [1] 0.1851852
(h) Overall, which approach seems to give the best results on this data?
The radial basis kernel approach gave the best results as it pertains to the test error.