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.
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 * (x1^2 - x2^2 > 0)’
set.seed(1)
x1 <- runif(500) - 0.5
x2 <- runif(500) - 0.5
y <- 1 * (x1^2 - x2^2 > 0)
head(data.frame(x1, x2, y))
table(y)
## y
## 0 1
## 261 239
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 = (y + 2), pch = 19,
xlab = "X1", ylab = "X2",main = "Class Labels")
legend("topright", legend = c("Class = 0", "Class = 1"), col = c(2, 3), pch = 19)
Fit a logistic regression model to the data, using X1 and X2 as predictors.
dat <- data.frame(x1 = x1, x2 = x2, y = y)
glm.fit <- glm(y ~ x1 + x2, data = dat, family = binomial)
summary(glm.fit)
##
## Call:
## glm(formula = y ~ x1 + x2, family = binomial, data = dat)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.087260 0.089579 -0.974 0.330
## x1 0.196199 0.316864 0.619 0.536
## x2 -0.002854 0.305712 -0.009 0.993
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.18 on 499 degrees of freedom
## Residual deviance: 691.79 on 497 degrees of freedom
## AIC: 697.79
##
## Number of Fisher Scoring iterations: 3
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.probs <- predict(glm.fit, dat, type = "response")
glm.pred <- ifelse(glm.probs > 0.5, 1, 0)
table(predicted = glm.pred, actual = y)
## actual
## predicted 0 1
## 0 258 212
## 1 3 27
plot(x1, x2, col = (glm.pred + 2), pch = 19,
xlab = "X1", ylab = "X2",main = "Logistic Regression (Linear)")
legend("topright", legend = c("pred = 0", "pred = 1"), col = c(2, 3), pch = 19)
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.fit2 <- glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = dat, family = binomial)
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm.fit2)
##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = binomial,
## data = dat)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -102.2 4302.0 -0.024 0.981
## poly(x1, 2)1 2715.3 141109.5 0.019 0.985
## poly(x1, 2)2 27218.5 842987.2 0.032 0.974
## poly(x2, 2)1 -279.7 97160.4 -0.003 0.998
## poly(x2, 2)2 -28693.0 875451.3 -0.033 0.974
## I(x1 * x2) -206.4 41802.8 -0.005 0.996
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9218e+02 on 499 degrees of freedom
## Residual deviance: 3.5810e-06 on 494 degrees of freedom
## AIC: 12
##
## Number of Fisher Scoring iterations: 25
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.probs2 <- predict(glm.fit2, dat, type = "response")
glm.pred2 <- ifelse(glm.probs2 > 0.5, 1, 0)
table(predicted = glm.pred2, actual = y)
## actual
## predicted 0 1
## 0 261 0
## 1 0 239
plot(x1, x2, col = (glm.pred2 + 2), pch = 19,
xlab = "X1", ylab = "X2", main = "Logistic Regression (Non-linear)")
legend("topright", legend = c("pred = 0", "pred = 1"), col = c(2, 3), pch = 19)
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.
library(caret)
## Warning: package 'caret' was built under R version 4.6.1
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.6.1
## Loading required package: lattice
data <- data.frame(x1 = x1, x2 = x2, y = as.factor(y))
train_control <- trainControl(method = "cv", number = 10)
svm_linear <- train(y~x1+x2, data = data, method = "svmLinear", trControl = train_control,
preProcess = c("center","scale"))
svm_linear_pred <- predict(svm_linear, data)
table(predicted = svm_linear_pred, actual = data$y)
## actual
## predicted 0 1
## 0 261 239
## 1 0 0
plot(x1, x2, col = (as.numeric(svm_linear_pred) + 1), pch = 19,
xlab = "X1", ylab = "X2", main = "SVM Classifier (Linear)")
legend("topright", legend = c("pred = 0", "pred = 1"), col = c(2, 3), pch = 19)
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.
train_control <- trainControl(method = "cv", number = 10)
svm_radial <- train(y~x1+x2, data = data, method = "svmRadial", trControl = train_control,
preProcess = c("center","scale"))
svm_radial_pred <- predict(svm_radial, data)
table(predicted = svm_radial_pred, actual = data$y)
## actual
## predicted 0 1
## 0 258 11
## 1 3 228
plot(x1, x2, col = (as.numeric(svm_radial_pred) + 1), pch = 19,
xlab = "X1", ylab = "X2", main = "SVM (Radial Kernel)")
legend("topright", legend = c("pred = 0", "pred = 1"), col = c(2, 3), pch = 19)
Comment on your results.
The logistic regression model performs poorly because the true decision boundary is quadratic instead of linear. Because of this, the model incorrectly classifies many observations and produces a linear decision boundary that does not separate the two classes. After adding quadratic terms, the logistic regression model is able to capture the non-linear relationship between the predictors.The linear support vector classifier performs similarly to the linear logistic regression model because it is also restricted to a linear decision boundary. Using a non-linear kernel allows the SVM to model the quadratic decision boundary much more effectively.
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.
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(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.6.1
Auto$mpg01 <- as.factor(ifelse(Auto$mpg > median(Auto$mpg), 1, 0))
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.
library(e1071)
## Warning: package 'e1071' was built under R version 4.6.1
##
## Attaching package: 'e1071'
## The following object is masked from 'package:ggplot2':
##
## element
set.seed(1)
tune.out <- tune(svm, mpg01 ~ . - mpg - name, data = Auto, kernel = "linear",
ranges = list(cost = c(0.001, 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.08435897
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-03 0.13525641 0.05661708
## 2 1e-02 0.08923077 0.04698309
## 3 1e-01 0.09185897 0.04393409
## 4 1e+00 0.08435897 0.03662670
## 5 5e+00 0.08948718 0.03898410
## 6 1e+01 0.08948718 0.03898410
## 7 1e+02 0.08692308 0.03887151
Small values of cost leads to more classification errors while larger values will classify the training data more accurately. Having a lower cross-validation error results in a more optimal model.
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.radial <- tune(svm, mpg01 ~ . - mpg - name, data = Auto, kernel = "radial",
ranges = list(cost = c(0.1, 1, 5, 10, 100),
gamma = c(0.01, 0.1, 1, 5, 10)))
summary(tune.radial)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 1 1
##
## - best performance: 0.06634615
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.1 0.01 0.11224359 0.03836937
## 2 1.0 0.01 0.08673077 0.04551036
## 3 5.0 0.01 0.08416667 0.04010502
## 4 10.0 0.01 0.08673077 0.04040897
## 5 100.0 0.01 0.08685897 0.03483004
## 6 0.1 0.10 0.08923077 0.04698309
## 7 1.0 0.10 0.08923077 0.04376306
## 8 5.0 0.10 0.07910256 0.03292568
## 9 10.0 0.10 0.08166667 0.04149504
## 10 100.0 0.10 0.08410256 0.03390616
## 11 0.1 1.00 0.08673077 0.04535158
## 12 1.0 1.00 0.06634615 0.03244101
## 13 5.0 1.00 0.08916667 0.02708952
## 14 10.0 1.00 0.08923077 0.02732003
## 15 100.0 1.00 0.10448718 0.04560852
## 16 0.1 5.00 0.54602564 0.05105434
## 17 1.0 5.00 0.09173077 0.03417795
## 18 5.0 5.00 0.09423077 0.04945093
## 19 10.0 5.00 0.09173077 0.04983028
## 20 100.0 5.00 0.09429487 0.05109336
## 21 0.1 10.00 0.55115385 0.04366593
## 22 1.0 10.00 0.12237179 0.04911598
## 23 5.0 10.00 0.12493590 0.04553082
## 24 10.0 10.00 0.12493590 0.04553082
## 25 100.0 10.00 0.12493590 0.04553082
set.seed(1)
tune.poly <- tune(svm, mpg01 ~ . - mpg - name, data = Auto, kernel = "polynomial",
ranges = list(cost = c(0.1, 1, 5, 10, 100),
degree = c(2, 3, 4)))
summary(tune.poly)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 3
##
## - best performance: 0.08423077
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.27846154 0.09486227
## 2 1.0 2 0.25307692 0.13751948
## 3 5.0 2 0.17621795 0.04945319
## 4 10.0 2 0.18647436 0.05598001
## 5 100.0 2 0.18128205 0.06251437
## 6 0.1 3 0.20192308 0.11347783
## 7 1.0 3 0.09448718 0.04180527
## 8 5.0 3 0.08429487 0.04016554
## 9 10.0 3 0.08435897 0.04544023
## 10 100.0 3 0.08423077 0.03636273
## 11 0.1 4 0.26564103 0.09977887
## 12 1.0 4 0.21205128 0.09560470
## 13 5.0 4 0.18371795 0.06175709
## 14 10.0 4 0.16589744 0.06962914
## 15 100.0 4 0.12756410 0.05208506
The radial kernel has a lower cross validation error that he linear kernel because of the relationship with the predictor variables. The polynomial kernel also improves performance over the linear classifier.
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.
dat <- Auto[, !(names(Auto) %in% c("mpg", "name"))]
svm.linear <- svm(mpg01 ~ ., data = dat, kernel = "linear", cost = 1)
svm.radial <- svm(mpg01 ~ ., data = dat, kernel = "radial", cost = 1, gamma = 1)
svm.poly <- svm(mpg01 ~ ., data = dat, kernel = "polynomial", cost = 100, degree = 3)
slc <- list(cylinders = mean(dat$cylinders), displacement = mean(dat$displacement),
acceleration = mean(dat$acceleration), year = mean(dat$year),
origin = mean(dat$origin))
plot(svm.linear, dat, horsepower ~ weight, slice = slc)
plot(svm.radial, dat, horsepower ~ weight, slice = slc)
plot(svm.poly, dat, horsepower ~ weight, slice = slc)
This problem involves the OJ data set which is part of the ISLR2 package.
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, ]
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
The support vector classifier was fit using a linear kernel with a cost of 0.01. The classifier allows more observations to fall within the margin which results in a smoother decision boundary.
What are the training and test error rates?
train.pred <- predict(svm.linear, OJ.train)
train.error <- mean(train.pred != OJ.train$Purchase)
test.pred <- predict(svm.linear, OJ.test)
test.error <- mean(test.pred != OJ.test$Purchase)
train.error
## [1] 0.175
test.error
## [1] 0.1777778
Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(1)
tune.linear <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(tune.linear)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.1
##
## - best performance: 0.1725
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.17625 0.02853482
## 2 0.10 0.17250 0.03162278
## 3 1.00 0.17500 0.02946278
## 4 5.00 0.17250 0.03162278
## 5 10.00 0.17375 0.03197764
best.linear <- tune.linear$best.model
Compute the training and test error rates using this new value for cost.
train.pred.best <- predict(best.linear, OJ.train)
train.error.best <- mean(train.pred.best != OJ.train$Purchase)
test.pred.best <- predict(best.linear, OJ.test)
test.error.best <- mean(test.pred.best != OJ.test$Purchase)
train.error.best
## [1] 0.165
test.error.best
## [1] 0.162963
Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
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: 373
##
## ( 188 185 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train.pred <- predict(svm.radial, OJ.train)
test.pred <- predict(svm.radial, OJ.test)
mean(train.pred != OJ.train$Purchase)
## [1] 0.15125
mean(test.pred != OJ.test$Purchase)
## [1] 0.1851852
set.seed(1)
tune.radial <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(tune.radial)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.17125
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39375 0.04007372
## 2 0.10 0.18625 0.02853482
## 3 1.00 0.17125 0.02128673
## 4 5.00 0.18000 0.02220485
## 5 10.00 0.18625 0.02853482
best.radial <- tune.radial$best.model
mean(predict(best.radial, OJ.train) != OJ.train$Purchase)
## [1] 0.15125
mean(predict(best.radial, OJ.test) != OJ.test$Purchase)
## [1] 0.1851852
Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
svm.poly <- svm(Purchase ~ ., data = OJ.train, kernel = "polynomial", 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
mean(predict(svm.poly, OJ.train) != OJ.train$Purchase)
## [1] 0.1825
mean(predict(svm.poly, OJ.test) != OJ.test$Purchase)
## [1] 0.2222222
set.seed(1)
tune.poly <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "polynomial", degree = 2, ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(tune.poly)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.18125
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39125 0.04210189
## 2 0.10 0.32125 0.05001736
## 3 1.00 0.20250 0.04116363
## 4 5.00 0.18250 0.03496029
## 5 10.00 0.18125 0.02779513
best.poly <- tune.poly$best.model
mean(predict(best.poly, OJ.train) != OJ.train$Purchase)
## [1] 0.15
mean(predict(best.poly, OJ.test) != OJ.test$Purchase)
## [1] 0.1888889
Overall, which approach seems to give the best results on this data?
The radial kernel has the best results as it can capture non-linear relationships without over fitting as much as the polynomial kernel. The linear classifier performs well but does not capture as much relationships as the radial kernel.