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:
set.seed(1)
x1 = runif(500) -.5
x2 = runif(500)-.5
y = 1 * (x1^2 - x2^2 > 0)
- 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 = (4-y), pch = (7-y), xlab = "x1", ylab = "x2")
- Fit a logistic regression model to the data, using X1 and X2 as predictors.
log.fit = glm(y ~ x1 + x2, family = binomial)
summary(log.fit)
##
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.179 -1.139 -1.112 1.206 1.257
##
## 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
df=data.frame(x1 = x1, x2 = x2, y = as.factor(y))
logreg=glm(y~.,data=df, family='binomial')
- 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.
probs <- predict(log.fit, df, type = "response")
preds <- ifelse(probs > 0.5,1,0)
ggplot(data = df, mapping = aes(x1, x2))+
geom_point(data = df, mapping = aes(colour = preds))
- Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors.
nlf <- data.frame(x1, x2, x1sq = x1^2, x2sq = x2^2, x1x2 = x1*x2, log_x2 = log(x2), sqrt_x1 = sqrt(abs(x1)))
log.fit <- glm(y ~., nlf, family = "binomial")
summary(log.fit)
##
## Call:
## glm(formula = y ~ ., family = "binomial", data = nlf)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.847e-04 -2.100e-08 -2.100e-08 2.100e-08 2.808e-04
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -334.29 555325.21 -0.001 1.000
## x1 323.12 226513.64 0.001 0.999
## x2 -495.35 1366332.92 0.000 1.000
## x1sq 3590.71 1169539.15 0.003 0.998
## x2sq -3230.89 1483373.57 -0.002 0.998
## x1x2 -862.83 683186.93 -0.001 0.999
## log_x2 -66.07 132207.10 0.000 1.000
## sqrt_x1 639.41 479936.73 0.001 0.999
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 3.4497e+02 on 249 degrees of freedom
## Residual deviance: 2.4489e-07 on 242 degrees of freedom
## (250 observations deleted due to missingness)
## AIC: 16
##
## 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.
# Obtain predicted class labels for each training observation
y_pred <- predict(log.fit, type = "response")
# Convert predicted probabilities to class labels
y_pred_class <- ifelse(y_pred > 0.5, 1, 0)
# Plot observations, colored according to predicted class labels
plot(x1, x2, col = ifelse(y_pred_class == 1, "yellow", "blue"), pch = 20, xlab = "x1", ylab = "x2")
- 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.matrix(cbind(x1, x2)), y)
y_pred <- predict(svm.fit, as.matrix(cbind(x1, x2)))
plot(x1, x2, col = ifelse(y_pred == 0, "blue", "red"), pch = 20, xlab = "x1", ylab = "x2")
- 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.fit2=svm(y~., data=df, kernel ="radial", gamma=1)
plot(svm.fit2, df)
> (i) Comment on your results.
SVM Linear failed to output any tangible result, most likely due to the distribution of the data points being non-linear.
SVM non-linear model (radial) was able to yield results that resemble the data.
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.
medauto = median(Auto$mpg)
med = ifelse(Auto$mpg > medauto, 1,0)
Auto$mpglevel = as.factor(med)
- 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
Best performance: 0.01025641 from cross-validation error rate, cost = 1
- 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)
grid <- c(0.1, 1, 5, 10)
form <- mpg ~.
poly = tune.svm(form, data = Auto, kernel = "polynomial", cost = grid, gamma = grid)
best.poly <- poly$best.model
summary(best.poly)
##
## Call:
## best.svm(x = form, data = Auto, gamma = grid, cost = grid, kernel = "polynomial")
##
##
## Parameters:
## SVM-Type: eps-regression
## SVM-Kernel: polynomial
## cost: 1
## degree: 3
## gamma: 0.1
## coef.0: 0
## epsilon: 0.1
##
##
## Number of Support Vectors: 264
Kernel = polynomial yields best cost at 1, degree = 3, gamma = 0.1, epsilon = 0.1
set.seed(1)
grid <- c(0.1, 1, 5, 10)
form <- mpg ~.
radial = tune.svm(form, data = Auto, kernel = "radial", cost = grid, gamma = grid)
best.radial <- radial$best.model
summary(best.radial)
##
## Call:
## best.svm(x = form, data = Auto, gamma = grid, cost = grid, kernel = "radial")
##
##
## Parameters:
## SVM-Type: eps-regression
## SVM-Kernel: radial
## cost: 5
## gamma: 0.1
## epsilon: 0.1
##
##
## Number of Support Vectors: 275
Kernel = radial yields best cost at 5 with gamma = 0.1, and epsilon = 0.1
- Make some plots to back up your assertions in (b) and (c).
svm.linear = svm(mpglevel ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 1, degree = 3, gamma = .1, epsilon = .1)
svm.radial = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 5, gamma = .1, epsilon = .1)
plotpairs = function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpglevel", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}
# Linear kernel
plotpairs(svm.linear)
plotpairs(svm.poly)
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)
Default = as.data.frame(OJ)
Default$id <- 1:nrow(Default)
train <- Default %>% dplyr::sample_frac(0.7476635514)
test <- dplyr::anti_join(Default, train, by = 'id')
dim(train)
## [1] 800 19
- 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.
ojsvm.linear = svm(Purchase~., kernel = "linear", data = train, cost = .01)
summary(ojsvm.linear)
##
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "linear", cost = 0.01)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 0.01
##
## Number of Support Vectors: 433
##
## ( 218 215 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
OJ SVM model with kernel = linear, cost = .01 results in 433 support
vectors with 218 to CH and 215 to MM. Response variable is
Purchase.
- What are the training and test error rates?
train_pred = predict(ojsvm.linear, train)
table(train$Purchase, train_pred)
## train_pred
## CH MM
## CH 422 63
## MM 76 239
(63+76)/800
## [1] 0.17375
testpred = predict(ojsvm.linear, test)
table(test$Purchase, testpred)
## testpred
## CH MM
## CH 151 17
## MM 35 67
(17+35)/nrow(test)
## [1] 0.1925926
Training set error = .17 Test set error = .19
- Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(1)
cost.grid <- c(0.01,0.1,1,10)
OJ.tune <- tune.svm(Purchase ~ ., data = train, kernel = "linear", cost = cost.grid)
summary(OJ.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.1
##
## - best performance: 0.17375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.17500 0.03435921
## 2 0.10 0.17375 0.02972676
## 3 1.00 0.17500 0.02500000
## 4 10.00 0.18125 0.03019037
The tune prompt returns the lowest error rate as .17375 with a cost of .1
- Compute the training and test error rates using this new value for cost.
svm.1= svm(Purchase ~ ., kernel = "linear", data = train, cost = 0.1)
pred.train1 = predict(svm.1, train)
table(train$Purchase, pred.train1)
## pred.train1
## CH MM
## CH 424 61
## MM 71 244
(61+71)/(424+244+61+71)
## [1] 0.165
Training error = .165
test.pred1 = predict(svm.1, test)
(t<-table(test$Purchase, test.pred1))
## test.pred1
## CH MM
## CH 154 14
## MM 31 71
(14+31)/(154+71+14+31)
## [1] 0.1666667
Test error = .167
- Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
set.seed(1)
svm_radial = svm(Purchase ~ ., data = train, kernel = "radial", cost=0.1)
pred_train_radial = predict(svm_radial, train)
table(train$Purchase, pred_train_radial)
## pred_train_radial
## CH MM
## CH 430 55
## MM 86 229
(55+86)/(430+229+55+86)
## [1] 0.17625
Training error = .17625
pred_test_radial = predict(svm_radial, test)
table(test$Purchase, pred_test_radial)
## pred_test_radial
## CH MM
## CH 149 19
## MM 39 63
(19+39)/nrow(test)
## [1] 0.2148148
Test error = .2148148
svm.rad = svm(Purchase ~ ., data = train, kernel = "radial", cost = 1)
pred.train3 = predict(svm.rad, train)
table(train$Purchase, pred.train3)
## pred.train3
## CH MM
## CH 439 46
## MM 71 244
(46+71)/(439+244+46+71)
## [1] 0.14625
- Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
set.seed(1)
svm.poly = svm(Purchase ~ ., data = train, kernel = "poly", degree = 2)
summary(svm.poly)
##
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "poly", degree = 2)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 1
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 445
##
## ( 226 219 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
SVM with kernel = poly and degree = 2 returns a cost of 1 with 445 support vectors and 226 CH, 219 MM
train.pred = predict(svm.poly, train)
table(train$Purchase, train.pred)
## train.pred
## CH MM
## CH 451 34
## MM 110 205
(34+110)/(451+205+34+110)
## [1] 0.18
Training error = .18
test.pred = predict(svm.poly, test)
table(test$Purchase, test.pred)
## test.pred
## CH MM
## CH 152 16
## MM 45 57
(152+57)/(152+57+16+45)
## [1] 0.7740741
Test Error = .7740741