(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(421)
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 yaxis.
plot(x1[y == 0], x2[y == 0], col = "purple", xlab = "X1", ylab = "X2", pch = "+")
points(x1[y == 1], x2[y == 1], col = "darkred", pch = 4)
(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
lm.fit = glm(y ~ x1 + x2, family = binomial)
summary(lm.fit)
##
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.278 -1.227 1.089 1.135 1.175
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.11999 0.08971 1.338 0.181
## x1 -0.16881 0.30854 -0.547 0.584
## x2 -0.08198 0.31476 -0.260 0.795
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 691.35 on 499 degrees of freedom
## Residual deviance: 690.99 on 497 degrees of freedom
## AIC: 696.99
##
## 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)
lm.prob = predict(lm.fit, data, type = "response")
lm.pred = ifelse(lm.prob > 0.52, 1, 0)
data.pos = data[lm.pred == 1, ]
data.neg = data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "purple", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkred", pch = 4)
(e) 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).
lm.fit = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), data = data, family = binomial)
(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.prob = predict(lm.fit, data, type = "response")
lm.pred = ifelse(lm.prob > 0.5, 1, 0)
data.pos = data[lm.pred == 1, ]
data.neg = data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "purple", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkred", pch = 4)
(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.
library(e1071)
svm.fit = svm(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.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 = "purple", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkred", pch = 4)
(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 = "purple", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "darkred", pch = 4)
(i) Comment on your results.
The experiment demonstrated the significance of using SVM to identify
nonlinear models. With the gamma parameter, cross validation would be
easy to use.
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)
library(e1071)
attach(Auto)
gas.med<-median(mpg)
mpg01<-ifelse(mpg> gas.med,1,0)
Auto$mpglevel<-as.factor(mpg01)
(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(100)
tune.auto<-tune(svm, mpglevel ~ ., data=Auto, kernel='linear', ranges = list(cost=c(0.01,.1, 1, 10, 100)))
summary(tune.auto)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.01512821
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07391026 0.04398186
## 2 1e-01 0.05102564 0.03408666
## 3 1e+00 0.01512821 0.02421271
## 4 1e+01 0.02538462 0.02372507
## 5 1e+02 0.03564103 0.02125655
The cross validation error is most minimized at 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(15)
auto.tune=tune(svm, mpglevel ~ ., data=Auto, kernel='polynomial', ranges = list(cost=c(0.01,.1, 1, 10, 100),degree= c(2,3,4,5)))
summary(auto.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 2
##
## - best performance: 0.2958333
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5458974 0.03582002
## 2 1e-01 2 0.5458974 0.03582002
## 3 1e+00 2 0.5458974 0.03582002
## 4 1e+01 2 0.5074359 0.06089646
## 5 1e+02 2 0.2958333 0.05351892
## 6 1e-02 3 0.5458974 0.03582002
## 7 1e-01 3 0.5458974 0.03582002
## 8 1e+00 3 0.5458974 0.03582002
## 9 1e+01 3 0.5458974 0.03582002
## 10 1e+02 3 0.3416026 0.08294367
## 11 1e-02 4 0.5458974 0.03582002
## 12 1e-01 4 0.5458974 0.03582002
## 13 1e+00 4 0.5458974 0.03582002
## 14 1e+01 4 0.5458974 0.03582002
## 15 1e+02 4 0.5458974 0.03582002
## 16 1e-02 5 0.5458974 0.03582002
## 17 1e-01 5 0.5458974 0.03582002
## 18 1e+00 5 0.5458974 0.03582002
## 19 1e+01 5 0.5458974 0.03582002
## 20 1e+02 5 0.5458974 0.03582002
auto.tuner=tune(svm, mpglevel ~ ., data=Auto, kernel='radial', ranges = list(cost=c(0.01,.1, 1, 10, 100),gamma= c(0.001,.01,.1,1,10)))
summary(auto.tuner)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 100 0.01
##
## - best performance: 0.01262821
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-02 1e-03 0.52403846 0.15933274
## 2 1e-01 1e-03 0.50352564 0.15808999
## 3 1e+00 1e-03 0.09410256 0.07444599
## 4 1e+01 1e-03 0.07371795 0.05504698
## 5 1e+02 1e-03 0.02794872 0.02216297
## 6 1e-02 1e-02 0.52153846 0.16674888
## 7 1e-01 1e-02 0.08897436 0.06845468
## 8 1e+00 1e-02 0.07115385 0.05414380
## 9 1e+01 1e-02 0.02794872 0.02524480
## 10 1e+02 1e-02 0.01262821 0.01778017
## 11 1e-02 1e-01 0.20166667 0.08964137
## 12 1e-01 1e-01 0.08134615 0.06266074
## 13 1e+00 1e-01 0.05076923 0.04450789
## 14 1e+01 1e-01 0.02544872 0.02689601
## 15 1e+02 1e-01 0.03314103 0.02424635
## 16 1e-02 1e+00 0.51903846 0.17420809
## 17 1e-01 1e+00 0.51903846 0.17420809
## 18 1e+00 1e+00 0.06115385 0.04029713
## 19 1e+01 1e+00 0.06371795 0.03456945
## 20 1e+02 1e+00 0.06371795 0.03456945
## 21 1e-02 1e+01 0.56403846 0.06078333
## 22 1e-01 1e+01 0.56403846 0.06078333
## 23 1e+00 1e+01 0.52583333 0.07372510
## 24 1e+01 1e+01 0.52076923 0.07579852
## 25 1e+02 1e+01 0.52076923 0.07579852
The lowest cross-validation error for SVM polynomial based kernel is obtained with cost =100 and degree =2
The lowest cross-validation error for SVM radial based kernel is obtained with cost = 100 and gamma=0.01
(d) 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 = 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)
detach(Auto)
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
library(ISLR2)
set.seed(9004)
train = sample(dim(OJ)[1], 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.
library(e1071)
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: 442
##
## ( 222 220 )
##
##
## Number of Classes: 2
##
## Levels:
## CH 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 432 51
## MM 80 237
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 146 24
## MM 22 78
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(1554)
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
## 3.162278
##
## - best performance: 0.1625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.16750 0.03395258
## 2 0.01778279 0.16875 0.02960973
## 3 0.03162278 0.16625 0.02638523
## 4 0.05623413 0.16875 0.03076005
## 5 0.10000000 0.16875 0.02901748
## 6 0.17782794 0.16750 0.02838231
## 7 0.31622777 0.17000 0.02898755
## 8 0.56234133 0.16875 0.02841288
## 9 1.00000000 0.16500 0.03106892
## 10 1.77827941 0.16500 0.03106892
## 11 3.16227766 0.16250 0.03118048
## 12 5.62341325 0.16375 0.02664713
## 13 10.00000000 0.16750 0.02581989
(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.parameters$cost)
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 428 55
## MM 74 243
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 146 24
## MM 20 80
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
set.seed(410)
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: 371
##
## ( 188 183 )
##
##
## 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 42
## MM 74 243
mean(train.pred != OJ.train$Purchase)
## [1] 0.145
The training error for radial basis kernel is 14.5%
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 148 22
## MM 27 73
mean(test.pred != OJ.test$Purchase)
## [1] 0.1814815
The test error for the radial basis kernel is 18.1%
set.seed(755)
tune.out = tune(svm, Purchase ~ ., data = OJ.train, kernel = "radial", 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
## 0.3162278
##
## - best performance: 0.1675
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39625 0.06615691
## 2 0.01778279 0.39625 0.06615691
## 3 0.03162278 0.35375 0.09754807
## 4 0.05623413 0.20000 0.04249183
## 5 0.10000000 0.17750 0.04073969
## 6 0.17782794 0.17125 0.03120831
## 7 0.31622777 0.16750 0.04216370
## 8 0.56234133 0.16750 0.03782269
## 9 1.00000000 0.17250 0.03670453
## 10 1.77827941 0.17750 0.03374743
## 11 3.16227766 0.18000 0.04005205
## 12 5.62341325 0.18000 0.03446012
## 13 10.00000000 0.18625 0.04427267
svm.radial = svm(Purchase ~ ., data = OJ.train, kernel = "radial", cost = tune.out$best.parameters$cost)
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 440 43
## MM 81 236
mean(train.pred != OJ.train$Purchase)
## [1] 0.155
The training error for radial basis kernel is 15.5%
test.pred<-predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 145 25
## MM 28 72
mean(test.pred != OJ.test$Purchase)
## [1] 0.1962963
The test error of radial basis kernel is 19.6%
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
svm.polyoj<-svm(Purchase~ ., kernel='polynomial', data=OJ.train, degree=2 )
summary(svm.polyoj)
##
## 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: 456
##
## ( 232 224 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The polynomial kernel with two degrees create 456 support vectors. 232 vectors belong to Citrus Hill, while 224 vectors belong to Minute Maid.
train.pred<-predict(svm.polyoj, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 450 33
## MM 111 206
mean(train.pred != OJ.train$Purchase)
## [1] 0.18
The training error for the polynomial kernels with two degrees is 18%
test.pred<-predict(svm.polyoj, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 149 21
## MM 34 66
mean(test.pred != OJ.test$Purchase)
## [1] 0.2037037
The test error for the polynomial kernels with two degrees is 20.3%
tunepoly.OJ<-tune(svm, Purchase ~ ., data=OJ.train, kernel='polynomial', degree=2, ranges=list(cost=10^seq(-2,1, by=.5)))
summary(tunepoly.OJ)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.175
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39375 0.04759858
## 2 0.03162278 0.36375 0.04980866
## 3 0.10000000 0.30750 0.05210833
## 4 0.31622777 0.20750 0.04297932
## 5 1.00000000 0.19250 0.04495368
## 6 3.16227766 0.17875 0.04168749
## 7 10.00000000 0.17500 0.03061862
The tuning selected cost=10 as the most optimal.
newsvm.polyoj<-svm(Purchase ~ ., kernel='polynomial', data=OJ.train, degree=2, cost=tune.out$best.parameters$cost)
train.pred<-predict(newsvm.polyoj, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 453 30
## MM 127 190
mean(train.pred != OJ.train$Purchase)
## [1] 0.19625
The training error for the polynomial kernel with the most optimal cost is 19.6%
test.pred<-predict(newsvm.polyoj, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 149 21
## MM 38 62
mean(test.pred != OJ.test$Purchase)
## [1] 0.2185185
The test error for the polynomial kernel with the most optimal cost is 21.8%
Overall, which approach seems to give the best results on
this data?
Overall it seems to be that radial basis kernel with default gamma has
the best result on this data. This led to lowest misclassification rate
for both training and test data set.