library(tidyverse)
library(openintro)
library(e1071)
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.
set.seed(2)
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 = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(x1[y == 1], x2[y == 1], col = "darkgrey", 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.271 -1.193 1.097 1.147 1.209
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.07138 0.08959 0.797 0.426
## x1 -0.03532 0.29825 -0.118 0.906
## x2 0.27548 0.30762 0.896 0.370
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.50 on 499 degrees of freedom
## Residual deviance: 691.67 on 497 degrees of freedom
## AIC: 697.67
##
## 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 = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkgrey", 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
summary(lm.fit)##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = binomial,
## data = data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.441e-03 -2.000e-08 2.000e-08 2.000e-08 1.455e-03
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 89.95 48695.53 0.002 0.999
## poly(x1, 2)1 203.19 1143572.92 0.000 1.000
## poly(x1, 2)2 32729.10 895641.74 0.037 0.971
## poly(x2, 2)1 540.94 1130136.06 0.000 1.000
## poly(x2, 2)2 -33281.76 1338007.08 -0.025 0.980
## I(x1 * x2) 198.04 578657.79 0.000 1.000
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9250e+02 on 499 degrees of freedom
## Residual deviance: 4.9969e-06 on 494 degrees of freedom
## AIC: 12
##
## 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.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 = "darkgrey", 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 = "darkgrey", 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 = 5)
points(data.neg$x1, data.neg$x2, col = "darkgrey", pch = 5)(i) Comment on your results.
When usng a logistic regression method or using a linear kernel, we get poor results in terms of finding the non-linear decision boundaries.So, if interested in finding non-linear decision boundaries the original logistic regression and the SVM with non-linear kernel were both good models.
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.
bivar <- ifelse(Auto$mpg > median(Auto$mpg), 1, 0)
Auto$mpglevel <- as.factor(bivar)(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(1)
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.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
This model uses a 10-fold cross-validation. The best parameters are cost of 1 with a performance of 0.01025641.
(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(21)
tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1,
1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out) ##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 10 2
##
## - best performance: 0.5435897
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.5587821 0.04538579
## 2 1.0 2 0.5587821 0.04538579
## 3 5.0 2 0.5587821 0.04538579
## 4 10.0 2 0.5435897 0.05611162
## 5 0.1 3 0.5587821 0.04538579
## 6 1.0 3 0.5587821 0.04538579
## 7 5.0 3 0.5587821 0.04538579
## 8 10.0 3 0.5587821 0.04538579
## 9 0.1 4 0.5587821 0.04538579
## 10 1.0 4 0.5587821 0.04538579
## 11 5.0 4 0.5587821 0.04538579
## 12 10.0 4 0.5587821 0.04538579
The best performance is 0.5435897 with the lowest cross-validation error obtained for degree=2 and cost=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
linear.svm <- svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
poly.svm <- svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 10,
degree = 2)
radial.svm = 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(linear.svm)plotpairs(poly.svm)plotpairs(radial.svm)This problem involves the OJ data set which is part of the ISLR2 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(dim(OJ)[1], 800)
train.oj <- OJ[train, ]
test.oj <- 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.
linear.svm <- svm(Purchase ~ ., data = train.oj, kernel = "linear", cost = 0.01)
summary(linear.svm)##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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
There are 435 support vectors created. 219 are level MM and 216 are level CH.
(c) What are the training and test error rates?
train.pred <- predict(linear.svm, train.oj)
table(train.oj$Purchase, train.pred)## train.pred
## CH MM
## CH 420 65
## MM 75 240
(65+75)/800## [1] 0.175
test.pred <- predict(linear.svm, test.oj)
table(test.oj$Purchase, test.pred)## test.pred
## CH MM
## CH 153 15
## MM 33 69
(15+33)/270## [1] 0.1777778
The training error rate is 0.175 (17.5%) and the test error rate is 0.1777778 (17.78%)
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(12)
tune.out <- tune(svm, Purchase ~ ., data = train.oj, 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
## 10
##
## - best performance: 0.17125
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17500 0.03118048
## 2 0.01778279 0.17500 0.02825971
## 3 0.03162278 0.17875 0.02638523
## 4 0.05623413 0.17500 0.03061862
## 5 0.10000000 0.17625 0.03408018
## 6 0.17782794 0.17125 0.02829041
## 7 0.31622777 0.17500 0.03061862
## 8 0.56234133 0.17500 0.03061862
## 9 1.00000000 0.17625 0.03087272
## 10 1.77827941 0.17375 0.03143004
## 11 3.16227766 0.17500 0.03280837
## 12 5.62341325 0.17250 0.03425801
## 13 10.00000000 0.17125 0.03175973
The optimal cost is 10, with the best performance at 0.17125.
(e) Compute the training and test error rates using this new value for cost.
linear.svm <- svm(Purchase ~ ., kernel = "linear", data = train.oj, cost = tune.out$best.parameter$cost)
train.pred <- predict(linear.svm, train.oj)
table(train.oj$Purchase, train.pred)## train.pred
## CH MM
## CH 423 62
## MM 69 246
(62+69)/800## [1] 0.16375
test.pred <- predict(linear.svm, test.oj)
table(test.oj$Purchase, test.pred)## test.pred
## CH MM
## CH 156 12
## MM 28 74
(12+28)/270## [1] 0.1481481
From tuning of svm, we see a decrease to a training error of 0.16375 (16.38%) and a decrease to a testing error of 0.1481481 (14.81%).
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
radial.svm <- svm(Purchase ~ ., kernel = "radial", data = train.oj)
summary(radial.svm)##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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
There are 373 support vectors; 188 belong to CH and 185 belong to MM.
train.pred <- predict(radial.svm, train.oj)
table(train.oj$Purchase, train.pred)## train.pred
## CH MM
## CH 441 44
## MM 77 238
(44+77)/800## [1] 0.15125
test.pred <- predict(radial.svm, test.oj)
table(test.oj$Purchase, test.pred)## test.pred
## CH MM
## CH 151 17
## MM 33 69
(17+33)/270## [1] 0.1851852
There is a training error of 0.15125 (15.13%) and a test error of 0.1851852 (18.52%).
set.seed(12)
tune.out <- tune(svm, Purchase ~ ., data = train.oj, 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.3162278
##
## - best performance: 0.17
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39375 0.05597929
## 2 0.01778279 0.39375 0.05597929
## 3 0.03162278 0.35000 0.07264832
## 4 0.05623413 0.19875 0.04656611
## 5 0.10000000 0.18750 0.04124790
## 6 0.17782794 0.18000 0.04257347
## 7 0.31622777 0.17000 0.03641962
## 8 0.56234133 0.17375 0.04619178
## 9 1.00000000 0.17125 0.05272110
## 10 1.77827941 0.18125 0.04093101
## 11 3.16227766 0.18750 0.04639804
## 12 5.62341325 0.18625 0.04581439
## 13 10.00000000 0.19250 0.04377975
The optimal cost is 0.3162278, with the best performance at 0.17.
radial.svm <- svm(Purchase ~ ., data = train.oj, kernel = "radial", cost = tune.out$best.parameters$cost)
train.pred <- predict(radial.svm, train.oj)
table(train.oj$Purchase, train.pred)## train.pred
## CH MM
## CH 436 49
## MM 78 237
(49+78)/800## [1] 0.15875
test.pred <- predict(radial.svm, test.oj)
table(test.oj$Purchase, test.pred)## test.pred
## CH MM
## CH 150 18
## MM 32 70
(18+32)/270## [1] 0.1851852
From tuning of svm, we see a slight increase to a training error of 0.15875 (15.88%) and the same testing error of 0.1851852 (18.52%).
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
set.seed(12)
poly.svm <- svm(Purchase ~ ., data = train.oj, kernel = "poly", degree = 2)
summary(poly.svm)##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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
There are 447 support vectors; 225 belong to CH and 222 belong to MM.
train.pred <- predict(poly.svm, train.oj)
table(train.oj$Purchase, train.pred)## train.pred
## CH MM
## CH 449 36
## MM 110 205
(36+110)/800## [1] 0.1825
test.pred <- predict(poly.svm, test.oj)
table(test.oj$Purchase, test.pred)## test.pred
## CH MM
## CH 153 15
## MM 45 57
(15+45)/270## [1] 0.2222222
There is a training error of 0.1825 (18.25%) and a test error of 0.2222222 (22.22%).
set.seed(12)
tune.out = tune(svm, Purchase ~ ., data = train.oj, kernel = "poly", 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.18375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.37125 0.06589396
## 2 0.01778279 0.37000 0.06645801
## 3 0.03162278 0.34625 0.06822400
## 4 0.05623413 0.33375 0.06771314
## 5 0.10000000 0.28875 0.06079622
## 6 0.17782794 0.23125 0.04379958
## 7 0.31622777 0.20250 0.03944053
## 8 0.56234133 0.18375 0.04251225
## 9 1.00000000 0.19375 0.03691676
## 10 1.77827941 0.19500 0.03641962
## 11 3.16227766 0.18875 0.04185375
## 12 5.62341325 0.19250 0.02958040
## 13 10.00000000 0.20000 0.02886751
The optimal cost is 0.5623413 , with the best performance at 0.18375.
poly.svm <- svm(Purchase ~ ., data = train.oj, kernel = "poly", degree = 2, cost = tune.out$best.parameters$cost)
train.pred <- predict(poly.svm, train.oj)
table(train.oj$Purchase, train.pred)## train.pred
## CH MM
## CH 447 38
## MM 111 204
(38+111)/800## [1] 0.18625
test.pred <- predict(poly.svm, test.oj)
table(test.oj$Purchase, test.pred)## test.pred
## CH MM
## CH 151 17
## MM 45 57
(17+45)/270## [1] 0.2296296
From tuning of svm, we see a slight increase to a training error of 0.18625 (18.63%) and also a slight increase to a testing error of 0.2296296 (22.96%).
(h) Overall, which approach seems to give the best results on this data?
The approach that seemed to give us the best results on the OJ data was the linear SVM approach because the training errors were the lowest of all tests at 16.38% and 14.87% for the training and testing errors respectively. …