Question 5: 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.
library(e1071)
Part 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(5)
x1 <- runif(500) - 0.5
x2 <- runif(500) - 0.5
y <- 1 * (x1^2 - x2^2 > 0)
Part 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 = "darkgreen", xlab = "X1", ylab = "X2", pch = "+")
points(x1[y == 1], x2[y == 1], col = "gold", pch = 4)
Part c: Fit a logistic regression model to the data, using X1 and X2 as predictors.
lm.model <- glm(y ~ x1 + x2, family = binomial)
summary(lm.model)
##
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.200 -1.161 -1.131 1.190 1.223
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.03150 0.08949 -0.352 0.725
## x1 -0.06176 0.30506 -0.202 0.840
## x2 -0.11509 0.31086 -0.370 0.711
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.02 on 499 degrees of freedom
## Residual deviance: 692.85 on 497 degrees of freedom
## AIC: 698.85
##
## Number of Fisher Scoring iterations: 3
Part 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.model, data, type = "response")
lm.pred <- ifelse(lm.prob > 0.50, 1, 0)
data.pos <- data[lm.pred == 1, ]
data.neg <- data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "gold", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkgreen", pch = 4)
Part 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).
lm.model2 <- glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = data, family = binomial)
Part 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.model2, data, type = "response")
lm.pred2 <- ifelse(lm.prob2 > 0.50, 1, 0)
data.pos2 <- data[lm.pred2 == 1, ]
data.neg2 <- data[lm.pred2 == 0, ]
plot(data.pos2$x1, data.pos2$x2, col = "gold", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg2$x1, data.neg2$x2, col = "darkgreen", pch = 4)
Part 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.model <- svm(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.1)
svm.prob <- predict(svm.model, data)
svm.pred <- rep( 0, 500)
svm.pred[svm.prob > 0.5] <- 1
plot(x1, x2, col = svm.pred + 1, xlab = "X1", ylab = "X2", pch = 4)
Part 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.model2 <- svm(as.factor(y) ~ x1 + x2, data, gamma = 1)
svm.pred2 <- predict(svm.model2, data)
svm.pos2 <- data[svm.pred2 == 1, ]
svm.neg2 <- data[svm.pred2 == 0, ]
plot(svm.pos2$x1, svm.pos2$x2, col = "gold", xlab = "X1", ylab = "X2", pch = "+")
points(svm.neg2$x1, svm.neg2$x2, col = "darkgreen", pch = 4)
Part i: Comment on your results.
The experiment performed covers the idea of SVMs are important and powerful to use for finding non-linear models. Both, logistic regression with non-interactions and SVMs with linear kernels fail to find the decision boundary. Using cross-validation would be easier with the parameter of gamma.
Question 7: 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)
attach(Auto)
auto <- Auto
Part 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)
Part 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
A cost
of 1 seems to perform best.
Part 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(1)
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.3013462
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5511538 0.04366593
## 2 1e-01 2 0.5511538 0.04366593
## 3 1e+00 2 0.5511538 0.04366593
## 4 5e+00 2 0.5511538 0.04366593
## 5 1e+01 2 0.5130128 0.08963366
## 6 1e+02 2 0.3013462 0.09961961
## 7 1e-02 3 0.5511538 0.04366593
## 8 1e-01 3 0.5511538 0.04366593
## 9 1e+00 3 0.5511538 0.04366593
## 10 5e+00 3 0.5511538 0.04366593
## 11 1e+01 3 0.5511538 0.04366593
## 12 1e+02 3 0.3446154 0.09821588
## 13 1e-02 4 0.5511538 0.04366593
## 14 1e-01 4 0.5511538 0.04366593
## 15 1e+00 4 0.5511538 0.04366593
## 16 5e+00 4 0.5511538 0.04366593
## 17 1e+01 4 0.5511538 0.04366593
## 18 1e+02 4 0.5511538 0.04366593
For a polynomial kernel, the lowest cv error obtained for a degree
of 2 and cost
of 100.
set.seed(1)
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
## 100 0.01
##
## - best performance: 0.01282051
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-02 1e-02 0.55115385 0.04366593
## 2 1e-01 1e-02 0.08929487 0.04382379
## 3 1e+00 1e-02 0.07403846 0.03522110
## 4 5e+00 1e-02 0.04852564 0.03303346
## 5 1e+01 1e-02 0.02557692 0.02093679
## 6 1e+02 1e-02 0.01282051 0.01813094
## 7 1e-02 1e-01 0.21711538 0.09865227
## 8 1e-01 1e-01 0.07903846 0.03874545
## 9 1e+00 1e-01 0.05371795 0.03525162
## 10 5e+00 1e-01 0.02820513 0.03299190
## 11 1e+01 1e-01 0.03076923 0.03375798
## 12 1e+02 1e-01 0.03583333 0.02759051
## 13 1e-02 1e+00 0.55115385 0.04366593
## 14 1e-01 1e+00 0.55115385 0.04366593
## 15 1e+00 1e+00 0.06384615 0.04375618
## 16 5e+00 1e+00 0.05884615 0.04020934
## 17 1e+01 1e+00 0.05884615 0.04020934
## 18 1e+02 1e+00 0.05884615 0.04020934
## 19 1e-02 5e+00 0.55115385 0.04366593
## 20 1e-01 5e+00 0.55115385 0.04366593
## 21 1e+00 5e+00 0.49493590 0.04724924
## 22 5e+00 5e+00 0.48217949 0.05470903
## 23 1e+01 5e+00 0.48217949 0.05470903
## 24 1e+02 5e+00 0.48217949 0.05470903
## 25 1e-02 1e+01 0.55115385 0.04366593
## 26 1e-01 1e+01 0.55115385 0.04366593
## 27 1e+00 1e+01 0.51794872 0.05063697
## 28 5e+00 1e+01 0.51794872 0.04917316
## 29 1e+01 1e+01 0.51794872 0.04917316
## 30 1e+02 1e+01 0.51794872 0.04917316
## 31 1e-02 1e+02 0.55115385 0.04366593
## 32 1e-01 1e+02 0.55115385 0.04366593
## 33 1e+00 1e+02 0.55115385 0.04366593
## 34 5e+00 1e+02 0.55115385 0.04366593
## 35 1e+01 1e+02 0.55115385 0.04366593
## 36 1e+02 1e+02 0.55115385 0.04366593
For the radial kernel, the lowest cv error is obtained for a gamma
of 0.01 and a cost
of 100.
Part 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)
plotpairs(svm.poly)
plotpairs(svm.radial)
Question 8: This problem involves the OJ
data set which is part of the ISLR2 package.
attach(OJ)
Part 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, ]
Part 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 ~ ., data = OJ.train, kernel = "linear", 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
The support vector classifier creates 435 support vectors. 219 vectors belong to CH
, while the remaining 216 vectors belong to MM
.
Part c: What are the training and test error rates?
OJ.train.pred <- predict(OJ.svm.linear, OJ.train)
table(OJ.train$Purchase, OJ.train.pred)
## OJ.train.pred
## CH MM
## CH 420 65
## MM 75 240
mean(OJ.train.pred != OJ.train$Purchase)
## [1] 0.175
The training error rate is 0.175(17.5%).
OJ.test.pred <- predict(OJ.svm.linear, OJ.test)
table(OJ.test$Purchase, OJ.test.pred)
## OJ.test.pred
## CH MM
## CH 153 15
## MM 33 69
mean(OJ.test.pred != OJ.test$Purchase)
## [1] 0.1777778
The test error rate is 0.1777778(17.78%).
Part d: Use the tune()
function to select an optimal cost
. Consider values in the range 0.01 to 10.
OJ.tune <- tune(svm, Purchase ~ ., data = OJ.train, kernel = 'linear', ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
summary(OJ.tune)
##
## 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.17375 0.03884174
## 2 0.01778279 0.17500 0.03996526
## 3 0.03162278 0.17750 0.03717451
## 4 0.05623413 0.18000 0.03073181
## 5 0.10000000 0.17875 0.03064696
## 6 0.17782794 0.17875 0.03537988
## 7 0.31622777 0.17875 0.03438447
## 8 0.56234133 0.17625 0.03197764
## 9 1.00000000 0.17500 0.03061862
## 10 1.77827941 0.17375 0.02972676
## 11 3.16227766 0.17250 0.03270236
## 12 5.62341325 0.17250 0.03322900
## 13 10.00000000 0.17125 0.03488573
Part e: Compute the training and test error rates using this new value for cost
.
OJ.svm.linear2 <- svm(Purchase ~ ., data = OJ.train, kernel = "linear", cost = OJ.tune$best.parameters$cost)
OJ.train.pred2 <- predict(OJ.svm.linear2, OJ.train)
table(OJ.train$Purchase, OJ.train.pred2)
## OJ.train.pred2
## CH MM
## CH 423 62
## MM 69 246
linear.train <- mean(OJ.train.pred2 != OJ.train$Purchase)
linear.train
## [1] 0.16375
The training error has decreased with the use of the optimal cost to 0.16375(16.38%).
OJ.test.pred2 <- predict(OJ.svm.linear2, OJ.test)
table(OJ.test$Purchase, OJ.test.pred2)
## OJ.test.pred2
## CH MM
## CH 156 12
## MM 28 74
linear.test <- mean(OJ.test.pred2 != OJ.test$Purchase)
linear.test
## [1] 0.1481481
The test error rate decreased with the use of the optimal cost to 0.1481481(14.81%).
Part f: Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma
.
OJ.svm.radial <- svm(Purchase ~ ., data = OJ.train, kernel = "radial")
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
The radial basis kernel with default gamma creates 373 support vectors. 188 vectors belong to CH
, while the remaining 185 vectors belong to MM
.
OJ.train.pred3 <- predict(OJ.svm.radial, OJ.train)
table(OJ.train$Purchase, OJ.train.pred3)
## OJ.train.pred3
## CH MM
## CH 441 44
## MM 77 238
mean(OJ.train.pred3 != OJ.train$Purchase)
## [1] 0.15125
The training error for radial basis kernel is 0.15125(15.13%).
OJ.test.pred3 <- predict(OJ.svm.radial, OJ.test)
table(OJ.test$Purchase, OJ.test.pred3)
## OJ.test.pred3
## CH MM
## CH 151 17
## MM 33 69
mean(OJ.test.pred3 != OJ.test$Purchase)
## [1] 0.1851852
The test error for the radial basis kernel is 0.1851852(18.52%).
OJ.tune2 <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
summary(OJ.tune2)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.5623413
##
## - best performance: 0.17125
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39375 0.06568284
## 2 0.01778279 0.39375 0.06568284
## 3 0.03162278 0.35125 0.09137263
## 4 0.05623413 0.19500 0.05109903
## 5 0.10000000 0.18250 0.05470883
## 6 0.17782794 0.17625 0.04059026
## 7 0.31622777 0.17250 0.04518481
## 8 0.56234133 0.17125 0.04825065
## 9 1.00000000 0.17625 0.03793727
## 10 1.77827941 0.17750 0.03622844
## 11 3.16227766 0.18375 0.03866254
## 12 5.62341325 0.18250 0.04090979
## 13 10.00000000 0.18125 0.04340139
OJ.svm.radial2 <- svm(Purchase ~ ., data = OJ.train, kernel = "radial", cost = OJ.tune2$best.parameters$cost)
OJ.train.pred4 <- predict(OJ.svm.radial2, OJ.train)
table(OJ.train$Purchase, OJ.train.pred4)
## OJ.train.pred4
## CH MM
## CH 437 48
## MM 71 244
radial.train <- mean(OJ.train.pred4 != OJ.train$Purchase)
radial.train
## [1] 0.14875
The training error has decreased with the use of the optimal cost to 0.14875(14.88%).
OJ.test.pred4 <- predict(OJ.svm.radial2, OJ.test)
table(OJ.test$Purchase, OJ.test.pred4)
## OJ.test.pred4
## CH MM
## CH 150 18
## MM 30 72
radial.test <- mean(OJ.test.pred4 != OJ.test$Purchase)
radial.test
## [1] 0.1777778
The test error rate decreased with the use of the optimal cost to 0.1777778(17.78%).
Part g: Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2
.
OJ.svm.poly <- svm(Purchase ~ ., data = OJ.train, kernel = "polynomial", degree = 2)
summary(OJ.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
The polynomial kernel with 2 degrees creates 447 support vectors. 225 vectors belong to CH
, while the remaining 222 vectors belong to MM
.
OJ.train.pred5 <- predict(OJ.svm.poly, OJ.train)
table(OJ.train$Purchase, OJ.train.pred5)
## OJ.train.pred5
## CH MM
## CH 449 36
## MM 110 205
mean(OJ.train.pred5 != OJ.train$Purchase)
## [1] 0.1825
The training error for the polynomial kernels with two degrees is 0.1825(18.25%).
OJ.test.pred5 <- predict(OJ.svm.poly, OJ.test)
table(OJ.test$Purchase, OJ.test.pred5)
## OJ.test.pred5
## CH MM
## CH 153 15
## MM 45 57
mean(OJ.test.pred5 != OJ.test$Purchase)
## [1] 0.2222222
The test error for the polynomial kernels with two degrees is 0.2222222(22.22%).
OJ.tune3 <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "polynomial", degree = 2, range = list(cost = 10^seq(-2, 1, by = 0.25)))
summary(OJ.tune3)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 5.623413
##
## - best performance: 0.18375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39000 0.08287373
## 2 0.01778279 0.37125 0.07337357
## 3 0.03162278 0.36750 0.06269414
## 4 0.05623413 0.34625 0.05434266
## 5 0.10000000 0.32375 0.06730166
## 6 0.17782794 0.25250 0.07260051
## 7 0.31622777 0.20875 0.05894029
## 8 0.56234133 0.20625 0.05472469
## 9 1.00000000 0.20000 0.05137012
## 10 1.77827941 0.19500 0.05809475
## 11 3.16227766 0.18875 0.05816941
## 12 5.62341325 0.18375 0.04825065
## 13 10.00000000 0.18625 0.05185785
OJ.svm.poly2 <- svm(Purchase ~ ., data = OJ.train, kernel = "polynomial", degree = 2, cost = OJ.tune3$best.parameters$cost)
OJ.train.pred6 <- predict(OJ.svm.poly2, OJ.train)
table(OJ.train$Purchase, OJ.train.pred6)
## OJ.train.pred6
## CH MM
## CH 447 38
## MM 88 227
poly.train <- mean(OJ.train.pred6 != OJ.train$Purchase)
poly.train
## [1] 0.1575
The training error has decreased with the use of the optimal cost to 0.1575(15.75%).
OJ.test.pred6 <- predict(OJ.svm.poly2, OJ.test)
table(OJ.test$Purchase, OJ.test.pred6)
## OJ.test.pred6
## CH MM
## CH 154 14
## MM 36 66
poly.test <- mean(OJ.test.pred6 != OJ.test$Purchase)
poly.test
## [1] 0.1851852
The training error has decreased with the use of the optimal cost to 0.1851852(18.52%).
Part h: Overall, which approach seems to give the best results on this data?
df <- tibble('SVM Kernel' = c("Linear", "Radial", "Polynomial"),
'Training Error' = c(linear.train, radial.train, poly.train),
'Test Error' = c(linear.test, radial.test, poly.test))
df
## # A tibble: 3 x 3
## `SVM Kernel` `Training Error` `Test Error`
## <chr> <dbl> <dbl>
## 1 Linear 0.164 0.148
## 2 Radial 0.149 0.178
## 3 Polynomial 0.158 0.185
Overall, the radial basis kernel seems to be producing minimum misclassifications training error and linear basis kernel producing minimum misclassification test error.