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.
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 \(X_1\) on the x-axis, and \(X_2\) on the y-axis.
plot(x1,x2,col=ifelse(y,'red','blue'))
c. Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.
library(glmnet)
## Warning: package 'glmnet' was built under R version 4.0.4
## Loading required package: Matrix
## Loaded glmnet 4.1-1
glm.fit= glm(y ~ x1 + x2, family = "binomial")
glm.fit
##
## Call: glm(formula = y ~ x1 + x2, family = "binomial")
##
## Coefficients:
## (Intercept) x1 x2
## -0.05177 0.34107 0.29905
##
## Degrees of Freedom: 499 Total (i.e. Null); 497 Residual
## Null Deviance: 692.9
## Residual Deviance: 690.7 AIC: 696.7
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)
glm.pred = predict(glm.fit, data, type = "response")
preds = rep(0, 500)
preds[preds > 0.52] = 1
plot(x1,x2,col=ifelse(preds>0,'red','blue'))
e. Now fit a logistic regression model to the data using non-linear functions of \(X_1\) and \(X_2\) as predictors (e.g. \(X_2^1\) , \(X_1 \times X_2\), \(log(X_2)\), and so forth).
glm.fit=glm(y~poly(x1,2)+poly(x2,2) ,family='binomial', data=data.frame(x1,x2,y))
## 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 parts a-e until you come up with an example in which the predicted class labels are obviously non-linear.
probs = predict(glm.fit, data, type = "response")
preds = rep(0, 500)
preds[probs > 0.47] = 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = "red", pch = (1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = "blue", pch = (1))
g. Fit a support vector classifier to the data with \(X_1\) and \(X_2\) as predictors. Obtain a class prediction for each training observation. Plot the observations, colored according to the predicted class labels.
library(e1071)
## Warning: package 'e1071' was built under R version 4.0.5
data$y = as.factor(data$y)
svm_fit = svm(y ~ x1 + x2, data, kernel = "linear", cost = 0.01)
preds = predict(svm_fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = "red", pch = (1), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = "blue", pch = (1))
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.
data$y = as.factor(data$y)
svm_fit = svm(y ~ x1 + x2, data, kernel = "radial", gamma = 1)
preds = predict(svm_fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = "red", pch = (1), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = "blue", pch = (1))
i. Comment on your results.
The SVM models fit with a non-linear kernel performed better than those with a linear kernel when determining the non-linear boundaries. The SVM with linear kernels were not able to acknowledge the proper boundaries necessary. The best performing model was SVM using radial kernel. We only needed to tune gamma for an accurate model. Logistic regression worked accurately as well, however it required more input and tuning than the SVMs with a radial kernel.
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.
library(ISLR)
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)))
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
svm_linear=tune_out$best.model
The lowest cross-validation error is associated with cost= 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.
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
svm_poly=tune_out$best.model
The lowest cross-validation error is associated with cost= 100
and degree=2
.
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
svm_radial=tune_out$best.model
The lowest cross-validation error is associated with cost=100
and gamma=0.01
.
d. Make some plots to back up your assertions in b and c.
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(1)
train = sample(1: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 ~ ., 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: 435
##
## ( 219 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The support vector classifier created 435 support vectors to be split up into 2 classes. Of the support vectors, 219 were assigned to CH
and the other 216 went to 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) / (420 + 240 + 75 + 65)
## [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
The training error rate and test error rate are about 17.5% and 17.78%, respectively.
d. Use the tune()
function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(2)
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
## 1.778279
##
## - best performance: 0.1675
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17625 0.04059026
## 2 0.01778279 0.17625 0.04348132
## 3 0.03162278 0.17125 0.04604120
## 4 0.05623413 0.17000 0.04005205
## 5 0.10000000 0.17125 0.04168749
## 6 0.17782794 0.17000 0.04090979
## 7 0.31622777 0.17125 0.04411554
## 8 0.56234133 0.17125 0.04084609
## 9 1.00000000 0.17000 0.04090979
## 10 1.77827941 0.16750 0.03782269
## 11 3.16227766 0.16750 0.03782269
## 12 5.62341325 0.16750 0.03545341
## 13 10.00000000 0.17000 0.03736085
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 69 246
(69 + 62) / (423 + 246 + 69 + 62)
## [1] 0.16375
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) / (156 + 73 + 29 + 12)
## [1] 0.1518519
Both the training error and test error decreases when using best cost. The training error decreases to 16.38% and the test error decreases to 15.19%.
f. Repeat parts b through e using a support vector machine with a radial kernel. Use the default value for gamma
.
set.seed(2)
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) / (441 + 238 + 77 + 44)
## [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) / (151 + 69 + 33 + 17)
## [1] 0.1851852
The radial kernel SVM made 373 support vectors with 188 assigned to CH
and 185 to MM
. The model has a training error rate of 15.13% and a test error rate of 18.52%, performing worse than the linear kernel SVM model.
set.seed(2)
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: 1.778279
##
## Number of Support Vectors: 350
##
## ( 177 173 )
##
##
## 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 73 242
(73 + 44) / (441 + 242 + 73 + 44)
## [1] 0.14625
test_pred = predict(svm_radial, 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
Tuning the radial kernel SVM gave a training error rate of 14.63% and a test error rate of 17.78%. This is better than the untuned model, but not as good as the linear kernel SVM model.
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) / (449 + 205 + 110 + 36)
## [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) / (153 + 57 + 45 + 15)
## [1] 0.2222222
The poly kernel SVM model has 447 support vectors with 225 assigned to CH
and 222 assigned to MM
. The training error rate is 18.25% and the test error rate is 22.22%, making this the worst performing model so far.
set.seed(2)
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.18
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39000 0.03670453
## 2 0.01778279 0.37000 0.03395258
## 3 0.03162278 0.36375 0.03197764
## 4 0.05623413 0.34500 0.03291403
## 5 0.10000000 0.32125 0.03866254
## 6 0.17782794 0.24750 0.03322900
## 7 0.31622777 0.20250 0.04073969
## 8 0.56234133 0.20250 0.03670453
## 9 1.00000000 0.19625 0.03910900
## 10 1.77827941 0.19125 0.03586723
## 11 3.16227766 0.18000 0.04005205
## 12 5.62341325 0.18000 0.04133199
## 13 10.00000000 0.18125 0.03830162
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) / (451 + 225 + 90 + 34)
## [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) / (154 + 61 + 41 + 14)
## [1] 0.2037037
Tuning the poly kernel SVM provided a training error rate of 15.5% and a test error rate of 20.37%. This is better than the untuned model, but still underperforming compared to the other linear and radial kernel models.
h. Overall, which approach seems to give the best results on this data?
Overall, the SVM models with linear kernels performed the best, with the tuned linear kernel model having the lowest test error rate. This means that this model classifies the OJ data with the highest accuracy.