library(ISLR2)
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(ggplot2)
library(lattice)
(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 * ( x1 ^2 - x2 ^2 > 0)
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[y==0],x2[y==0], col="blue", xlab= "x1", ylab= "x2", pch = '+')
points(x1[y==1],x2[y==1], col="green", pch = 4)
(c) Fit a logistic regression model to the data, using X 1 and X
2 as predictors.
lr.fit= glm(y~ x1+x2, family = binomial)
summary(lr.fit)
##
## Call:
## glm(formula = y ~ x1 + x2, family = binomial)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.297 -1.212 1.072 1.132 1.226
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.08660 0.08968 0.966 0.334
## x1 -0.29732 0.31023 -0.958 0.338
## x2 -0.11405 0.30730 -0.371 0.711
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.18 on 499 degrees of freedom
## Residual deviance: 691.14 on 497 degrees of freedom
## AIC: 697.14
##
## 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(lr.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 = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
(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 21 , X 1 ×X 2
, log(X 2 ),and so forth).
lm.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.
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 = "green", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
(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)
svm.fit = svm(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.1)
plot(data.pos$x1,data.pos$x2,col = "orange", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "blue", pch = 4)
(h) Fit a SVM using a non-linear kernel to the data. Obtain a
classprediction for each training observation. Plot the observations,
colored according to the predicted class labels. (i) Comment on your
results.
svm.fit = svm(as.factor(y) ~ x1 + x2, data, gamma = 1)
plot(data.pos$x1, data.pos$x2, col = "green", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
#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.
library(ISLR2)
attach(Auto)
## The following object is masked from package:ggplot2:
##
## mpg
mpg.med = median(Auto$mpg)
above.below = ifelse(Auto$mpg > mpg.med, 1, 0)
mpglevel = as.factor(above.below)
(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.
library(e1071)
set.seed(12)
tune.out = tune(svm, mpg ~ ., 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
## 0.1
##
## - best performance: 11.85867
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 12.83584 4.954577
## 2 1e-01 11.85867 4.269184
## 3 1e+00 12.30706 3.171524
## 4 5e+00 13.02714 3.825037
## 5 1e+01 13.44875 4.060655
## 6 1e+02 14.59619 4.439880
(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(12)
tune.out = tune(svm, mpg ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1,
1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 10 2
##
## - best performance: 57.74487
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 61.62628 11.23107
## 2 1.0 2 60.90499 11.22059
## 3 5.0 2 58.89548 11.55725
## 4 10.0 2 57.74487 11.90850
## 5 0.1 3 61.67504 11.23179
## 6 1.0 3 61.37209 11.18713
## 7 5.0 3 60.04905 10.99319
## 8 10.0 3 58.44108 10.77738
## 9 0.1 4 61.70830 11.23679
## 10 1.0 4 61.70358 11.23658
## 11 5.0 4 61.68262 11.23565
## 12 10.0 4 61.65648 11.23452
(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.poly = svm(mpglevel ~ ., data = Auto, kernel = "polynomial", cost = 10,
degree = 2)
svm.radial = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 10, 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
## function(fit) {
## for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpglevel", "name"))]) {
## plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
## }
## }
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
library(ISLR2)
set.seed(1)
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: 435
##
## ( 219 216 )
##
##
## 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 420 65
## MM 75 240
1-((420+240)/800)
## [1] 0.175
the test error rate is 17.5%
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 153 15
## MM 33 69
1-((153+69)/270)
## [1] 0.1777778
test error rate is 17.778% (d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(1)
tune.out=tune(svm ,Purchase~.,data=OJ ,kernel ="linear",ranges=list(cost=c (0.001, 0.01, 0.1, 1,5,10) ))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.1626168
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-03 0.2373832 0.04561497
## 2 1e-02 0.1691589 0.04024604
## 3 1e-01 0.1663551 0.03984617
## 4 1e+00 0.1626168 0.03945456
## 5 5e+00 0.1654206 0.03917066
## 6 1e+01 0.1682243 0.03865942
(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 424 61
## MM 70 245
1-((424+245)/800)
## [1] 0.16375
training error rate is 16.375%
test.pred =predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 155 13
## MM 29 73
1-((155+73)/270)
## [1] 0.1555556
training error is 15.556% (f) 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 = 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
there are 373 support vectors.
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase,train.pred)
## train.pred
## CH MM
## CH 441 44
## MM 77 238
1-((441+238)/800)
## [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
1-((151+69)/270)
## [1] 0.1851852
set.seed(1)
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.5623413
##
## - best performance: 0.16875
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39375 0.04007372
## 2 0.01778279 0.39375 0.04007372
## 3 0.03162278 0.35750 0.05927806
## 4 0.05623413 0.19500 0.02443813
## 5 0.10000000 0.18625 0.02853482
## 6 0.17782794 0.18250 0.03291403
## 7 0.31622777 0.17875 0.03230175
## 8 0.56234133 0.16875 0.02651650
## 9 1.00000000 0.17125 0.02128673
## 10 1.77827941 0.17625 0.02079162
## 11 3.16227766 0.17750 0.02266912
## 12 5.62341325 0.18000 0.02220485
## 13 10.00000000 0.18625 0.02853482
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 437 48
## MM 71 244
1-((437+244)/800)
## [1] 0.14875
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 150 18
## MM 30 72
1-((150+72)/270)
## [1] 0.1777778
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
set.seed(47)
svm.poly = svm(Purchase ~ ., data = OJ.train, kernel = "poly", degree = 2)
summary(svm.poly)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "poly", 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
1-((446+216)/800)
## [1] 0.1725
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 153 15
## MM 45 57
1-((160+54)/270)
## [1] 0.2074074
set.seed(1)
tune.out = tune(svm, Purchase ~ ., data = OJ.train, kernel = "poly", 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
##
## - best performance: 0.185
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.37125 0.03537988
## 2 0.01778279 0.37125 0.03488573
## 3 0.03162278 0.34500 0.04377975
## 4 0.05623413 0.32750 0.04669642
## 5 0.10000000 0.28750 0.05068969
## 6 0.17782794 0.22625 0.03408018
## 7 0.31622777 0.19625 0.03438447
## 8 0.56234133 0.19125 0.03634805
## 9 1.00000000 0.18500 0.02415229
## 10 1.77827941 0.18875 0.02079162
## 11 3.16227766 0.19125 0.02503470
## 12 5.62341325 0.19000 0.03106892
## 13 10.00000000 0.19500 0.03184162
svm.poly = svm(Purchase ~ ., data = OJ.train, kernel = "poly", cost = tune.out$best.parameters$cost)
train.pred = predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 453 32
## MM 91 224
1-((454+215)/800)
## [1] 0.16375
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 155 13
## MM 47 55
1-((153+55)/270)
## [1] 0.2296296
(h) Overall, which approach seems to give the best results on this data? The radial kernel seems to give the lowest error rates.