Chapter 09 (page 368): 5, 7, 8
library(readr)
library(glmnet)
## Loading required package: Matrix
## Loaded glmnet 4.1-2
library(MASS)
library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
library(tree)
library(rpart)
library(caret)
library(e1071)
library(ISLR)
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.
(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. For instance, you can do this as follows:
> x1=runif(500)-0.5 > x2=runif(500)-0.5 > y=1*(x12-x22
set.seed(1)
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 y- axis.
plot(x1[y == 0], x2[y == 0], xlab = "x1", ylab = "x2", col = c("red"))
points(x1[y == 1], x2[y == 1], col = "blue")
(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
glm.fit = glm(y ~ x1 + x2, family = "binomial")
summary(glm.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
(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)
prob.glm = predict(glm.fit, data, type = "response")
preds.glm = ifelse(prob.glm > .50, 1, 0)
pos = data[preds.glm == 1, ]
neg = data[preds.glm == 0, ]
plot(pos$x1, pos$x2, col = "red", xlab = "X1", ylab = "X2")
points(neg$x1, neg$x2, col = "blue")
(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X12, X1 ×X2, log(X2), and so forth).
nl.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
(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.
prob.glm = predict(nl.fit, data, type = "response")
preds.glm = ifelse(prob.glm > .50, 1, 0)
pos = data[preds.glm == 1, ]
neg = data[preds.glm == 0, ]
plot(pos$x1, pos$x2, col = "red", xlab = "X1", ylab = "X2")
points(neg$x1, neg$x2, col = "blue")
(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.
data$y <- as.factor(data$y)
svm.fit <- svm(y ~ x1 + x2, data, kernel = "linear", cost = .01)
preds <- predict(svm.fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = "blue", xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = "red")
(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 = "red", xlab = "X1", ylab = "X2")
points(data.neg$x1, data.neg$x2, col = "blue")
(i) Comment on your results.
The SVM non-linear model and logistic regression with non-linear functions of the predictors reflect clear division lines between the observations, but the two linear models did not.
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.
(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.
median(Auto$mpg)
## [1] 22.75
high = ifelse(Auto$mpg > 22.75, 1, 0)
Auto$mpglevel = as.factor(high)
(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.
The lowest error is with a cost of 1.
set.seed(1)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1.0, 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 1e+01 0.02051282 0.02648194
## 5 1e+02 0.03076923 0.03151981
(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.
For the SVM with radial, the lowest error is with cost of 100 and gamma of 0.01
set.seed(1)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1.0, 10, 100), gamma = c(0.01, 0.1, 1.0, 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 1e+01 1e-02 0.02557692 0.02093679
## 5 1e+02 1e-02 0.01282051 0.01813094
## 6 1e-02 1e-01 0.21711538 0.09865227
## 7 1e-01 1e-01 0.07903846 0.03874545
## 8 1e+00 1e-01 0.05371795 0.03525162
## 9 1e+01 1e-01 0.03076923 0.03375798
## 10 1e+02 1e-01 0.03583333 0.02759051
## 11 1e-02 1e+00 0.55115385 0.04366593
## 12 1e-01 1e+00 0.55115385 0.04366593
## 13 1e+00 1e+00 0.06384615 0.04375618
## 14 1e+01 1e+00 0.05884615 0.04020934
## 15 1e+02 1e+00 0.05884615 0.04020934
## 16 1e-02 1e+01 0.55115385 0.04366593
## 17 1e-01 1e+01 0.55115385 0.04366593
## 18 1e+00 1e+01 0.51794872 0.05063697
## 19 1e+01 1e+01 0.51794872 0.04917316
## 20 1e+02 1e+01 0.51794872 0.04917316
## 21 1e-02 1e+02 0.55115385 0.04366593
## 22 1e-01 1e+02 0.55115385 0.04366593
## 23 1e+00 1e+02 0.55115385 0.04366593
## 24 1e+01 1e+02 0.55115385 0.04366593
## 25 1e+02 1e+02 0.55115385 0.04366593
Polynomial
For the SVM with polynomial, the lowest error is with cost of 100 and degree of 2
set.seed(1)
tune.out = tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1.0, 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 1e+01 2 0.5130128 0.08963366
## 5 1e+02 2 0.3013462 0.09961961
## 6 1e-02 3 0.5511538 0.04366593
## 7 1e-01 3 0.5511538 0.04366593
## 8 1e+00 3 0.5511538 0.04366593
## 9 1e+01 3 0.5511538 0.04366593
## 10 1e+02 3 0.3446154 0.09821588
## 11 1e-02 4 0.5511538 0.04366593
## 12 1e-01 4 0.5511538 0.04366593
## 13 1e+00 4 0.5511538 0.04366593
## 14 1e+01 4 0.5511538 0.04366593
## 15 1e+02 4 0.5511538 0.04366593
(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.radial = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 100, gamma = 0.01)
svm.poly = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 100, degree = 2)
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.radial)
8. 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)
OJtrain = OJ[train, ]
OJtest = 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.
The svm created 435 support vectors, with two classes (CH and MM). 219 are CH and 216 are MM.
svmlinOJ = svm(Purchase ~ ., data = OJtrain, kernel = "linear", cost = 0.01)
summary(svmlinOJ)
##
## Call:
## svm(formula = Purchase ~ ., data = OJtrain, 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
(c) What are the training and test error rates?
The Train error is 17.50%, and the Test error is 17.78%
train.pred = predict(svmlinOJ, OJtrain)
table(OJtrain$Purchase, train.pred)
## train.pred
## CH MM
## CH 420 65
## MM 75 240
Train error rate is 17.50%
1 - (420 + 240) / (420 + 240 + 65 + 75)
## [1] 0.175
test.pred = predict(svmlinOJ, OJtest)
table(OJtest$Purchase, test.pred)
## test.pred
## CH MM
## CH 153 15
## MM 33 69
Test error rate is 17.78%
1 - (153 + 69) / (153 + 69 + 15 + 33)
## [1] 0.1777778
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
The lowest error is with a cost of 10
set.seed(1)
tunesvm = tune(svm, Purchase ~ ., data = OJtrain, kernel = "linear", ranges = list(cost = c(0.01, 1, 10)))
summary(tunesvm)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.17375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.17625 0.02853482
## 2 1.00 0.17500 0.02946278
## 3 10.00 0.17375 0.03197764
(e) Compute the training and test error rates using this new value for cost.
The training error for the SVM with a cost of 10 is 16.375%. The test error for the SVM with a cost of 10 is 16.667%
svm10OJ = svm(Purchase ~ ., data = OJtrain, kernel = "linear", cost = 10)
train10pred = predict(svm10OJ, OJtrain)
table(OJtrain$Purchase, train10pred)
## train10pred
## CH MM
## CH 423 62
## MM 69 246
Training error
1 - (423 + 246) / 800
## [1] 0.16375
svm10OJ = svm(Purchase ~ ., data = OJtest, kernel = "linear", cost = 10)
test10pred = predict(svm10OJ, OJtest)
table(OJtest$Purchase, test10pred)
## test10pred
## CH MM
## CH 154 14
## MM 31 71
Test error
1 - (154 + 71) / 270
## [1] 0.1666667
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
Train error for default radial svm is 15.125%. Test error for default radial svm is 18.519%
svmradOJ = svm(Purchase ~ ., data = OJtrain, kernel = "radial")
trainpred = predict(svmradOJ, OJtrain)
table(OJtrain$Purchase, trainpred)
## trainpred
## CH MM
## CH 441 44
## MM 77 238
1 - (441 + 238) / 800
## [1] 0.15125
Test error
testpred = predict(svmradOJ, OJtest)
table(OJtest$Purchase, testpred)
## testpred
## CH MM
## CH 151 17
## MM 33 69
1 - (151 + 69) / 270
## [1] 0.1851852
set.seed(1)
tunesvm = tune(svm, Purchase ~ ., data = OJtrain, kernel = "radial", ranges = list(cost = c(0.01, 1, 10)))
summary(tunesvm)
##
## 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 1.00 0.17125 0.02128673
## 3 10.00 0.18625 0.02853482
svmradOJ = svm(Purchase ~ ., data = OJtrain, kernel = "radial", cost = 1)
trainpred = predict(svmradOJ, OJtrain)
table(OJtrain$Purchase, trainpred)
## trainpred
## CH MM
## CH 441 44
## MM 77 238
Tuned training error for radial svm is 15.125%
1 - (441 + 238) / 800
## [1] 0.15125
Tuned test error for radial svm is 18.519%
testpred = predict(svmradOJ, OJtest)
table(OJtest$Purchase, testpred)
## testpred
## CH MM
## CH 151 17
## MM 33 69
1 - (151 + 69) / 270
## [1] 0.1851852
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
svmpolyOJ = svm(Purchase ~ ., data = OJtrain, kernel = "polynomial", degree = 2)
trainpred = predict(svmpolyOJ, OJtrain)
table(OJtrain$Purchase, trainpred)
## trainpred
## CH MM
## CH 449 36
## MM 110 205
Train error for polynomial is 18.25%
1 - (449 + 205) / 800
## [1] 0.1825
Test error for polynomial is 18.89%
testpred = predict(svmpolyOJ, OJtest)
table(OJtest$Purchase, testpred)
## testpred
## CH MM
## CH 153 15
## MM 45 57
1 - (154 + 65) / 270
## [1] 0.1888889
Tuning polynomial
set.seed(1)
tunesvm = tune(svm, Purchase ~ ., data = OJtrain, kernel = "polynomial", degree = 2, ranges = list(cost = c(0.01, 1, 10)))
summary(tunesvm)
##
## 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 1.00 0.20250 0.04116363
## 3 10.00 0.18125 0.02779513
Tuned polynomial
svmpolyOJ = svm(Purchase ~ ., data = OJtrain, kernel = "polynomial", degree = 2, cost = 10)
trainpred = predict(svmpolyOJ, OJtrain)
table(OJtrain$Purchase, trainpred)
## trainpred
## CH MM
## CH 447 38
## MM 82 233
Train error for tuned polynomial ia 15.00%
1 - (447 + 233) / 800
## [1] 0.15
Test error for tuned polynomial 18.89%
testpred = predict(svmpolyOJ, OJtest)
table(OJtest$Purchase, testpred)
## testpred
## CH MM
## CH 154 14
## MM 37 65
1 - (154 + 65) / 270
## [1] 0.1888889
(h) Overall, which approach seems to give the best results on this data?
The linear tuned model with a cost of 10 had the lowest test error with 16.667%. The radial and polynomial approach both had similar error rates of close to 19%.