(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.
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], col = "red", xlab = "X1", ylab = "X2")
points(x1[y == 1], x2[y == 1], )
(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.246 -1.177 1.119 1.166 1.217
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.02794 0.08973 0.311 0.755
## x1 0.03114 0.31078 0.100 0.920
## x2 0.23424 0.31031 0.755 0.450
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.08 on 499 degrees of freedom
## Residual deviance: 692.49 on 497 degrees of freedom
## AIC: 698.49
##
## 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.50, 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")
points(data.neg$x1, data.neg$x2, col = "red")
(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X2, X1 ×X2, log(X2),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 = 'blue', xlab = "X1", ylab = "X2")
points(data.neg$x1, data.neg$x2, col = 'green', xlab = "X1", ylab = "X2")
(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 = "red", 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 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 = "green", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)
(i) Comment on your results.
From these graphs we can see that the linear logistic regression and the SVM with a linear kernel had different decision boundaries. However, the non-linear logistic regression and the SVM using the non-linear SVM kernel had similar decision boundaries.
(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)
## Warning: package 'ISLR' was built under R version 4.0.5
gas.med = median(Auto$mpg)
bi_var = ifelse(Auto$mpg > gas.med, 1, 0)
Auto$mpgmed = as.factor(bi_var)
(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.
set.seed(7)
tune.out = tune(svm, mpgmed~., data = Auto, kernel = 'linear', ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100, 1000)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.01275641
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07403846 0.03704323
## 2 1e-01 0.05102564 0.03616632
## 3 1e+00 0.01275641 0.02488275
## 4 5e+00 0.02044872 0.03150887
## 5 1e+01 0.02557692 0.03626245
## 6 1e+02 0.03833333 0.04234954
## 7 1e+03 0.03833333 0.04234954
The cost values are 0.01, 0.1, 1, 5, 10, 100, and 1000.Our errors are approximately 0.07, 0.05, 0.01, 0.02, 0.03, 0.04, and 0.04. The cost value 1 had the lowest CV error at ~0.01.
(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(7)
tune.out = tune(svm, mpgmed ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1, 1, 5, 10, 100, 1000), degree = c(2, 3, 4)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 1000 3
##
## - best performance: 0.2552564
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-01 2 0.5585897 0.03870200
## 2 1e+00 2 0.5585897 0.03870200
## 3 5e+00 2 0.5585897 0.03870200
## 4 1e+01 2 0.5207051 0.09208784
## 5 1e+02 2 0.2986538 0.06466876
## 6 1e+03 2 0.2577564 0.06253675
## 7 1e-01 3 0.5585897 0.03870200
## 8 1e+00 3 0.5585897 0.03870200
## 9 5e+00 3 0.5585897 0.03870200
## 10 1e+01 3 0.5585897 0.03870200
## 11 1e+02 3 0.3394231 0.08591086
## 12 1e+03 3 0.2552564 0.06429373
## 13 1e-01 4 0.5585897 0.03870200
## 14 1e+00 4 0.5585897 0.03870200
## 15 5e+00 4 0.5585897 0.03870200
## 16 1e+01 4 0.5585897 0.03870200
## 17 1e+02 4 0.5585897 0.03870200
## 18 1e+03 4 0.5308974 0.08009874
For the SVM using the polynomial kernel, the best cost value is 1000 with a CV error of 0.255 and a degree of 3.
set.seed(7)
tune.out = tune(svm, mpgmed ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.1, 1, 5, 10, 100, 1000), gamma=c(0.5,1,2,3,4)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 1 0.5
##
## - best performance: 0.05358974
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-01 0.5 0.08429487 0.04194489
## 2 1e+00 0.5 0.05358974 0.04233056
## 3 5e+00 0.5 0.05365385 0.04422205
## 4 1e+01 0.5 0.05365385 0.04422205
## 5 1e+02 0.5 0.05365385 0.04422205
## 6 1e+03 0.5 0.05365385 0.04422205
## 7 1e-01 1.0 0.55858974 0.03870200
## 8 1e+00 1.0 0.06897436 0.04669593
## 9 5e+00 1.0 0.06897436 0.04669593
## 10 1e+01 1.0 0.06897436 0.04669593
## 11 1e+02 1.0 0.06897436 0.04669593
## 12 1e+03 1.0 0.06897436 0.04669593
## 13 1e-01 2.0 0.55858974 0.03870200
## 14 1e+00 2.0 0.12006410 0.06801323
## 15 5e+00 2.0 0.11237179 0.06593814
## 16 1e+01 2.0 0.11237179 0.06593814
## 17 1e+02 2.0 0.11237179 0.06593814
## 18 1e+03 2.0 0.11237179 0.06593814
## 19 1e-01 3.0 0.55858974 0.03870200
## 20 1e+00 3.0 0.39288462 0.16362233
## 21 5e+00 3.0 0.36737179 0.16715151
## 22 1e+01 3.0 0.36737179 0.16715151
## 23 1e+02 3.0 0.36737179 0.16715151
## 24 1e+03 3.0 0.36737179 0.16715151
## 25 1e-01 4.0 0.55858974 0.03870200
## 26 1e+00 4.0 0.48724359 0.05004057
## 27 5e+00 4.0 0.47185897 0.06659434
## 28 1e+01 4.0 0.47185897 0.06659434
## 29 1e+02 4.0 0.47185897 0.06659434
## 30 1e+03 4.0 0.47185897 0.06659434
For the SVM using a radial kernel, we get that the best cost value is 1 with a gamma of 0.5 and a CV error of ~0.05.
(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(mpgmed ~ ., data = Auto, kernel = "linear", cost = 1)
svm.poly = svm(mpgmed ~ ., data = Auto, kernel = "polynomial", cost = 1000,
degree = 3)
svm.radial = svm(mpgmed ~ ., data = Auto, kernel = "radial", cost = 1, gamma = 0.05)
plotpairs = function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpgmed", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}
plotpairs(svm.linear)
plotpairs(svm.poly)
plotpairs(svm.radial)
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(7)
train = sample(nrow(OJ), 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.
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: 438
##
## ( 218 220 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The support vector classifier has 438 support vectors out of the 800 observations. 218 of those vectors belong to level CH and the remaining 220 vectors belong to 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 424 60
## MM 76 240
(76+60)/(424+240+76+60)
## [1] 0.17
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 154 15
## MM 29 72
(29+15)/(154+72+29+15)
## [1] 0.162963
The training error rate is 17% the test error rate is ~16.3%
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(7)
OJ.tune = tune(svm, Purchase~., data = OJ.train, kernel = 'linear', ranges =list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(OJ.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 5
##
## - best performance: 0.1725
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.17750 0.03106892
## 2 0.10 0.17750 0.03270236
## 3 1.00 0.17625 0.02531057
## 4 5.00 0.17250 0.02486072
## 5 10.00 0.17375 0.02316157
The best cost value is 5 with a CV error of 0.1725
(e) Compute the training and test error rates using this new value for cost.
svm.linear = svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = OJ.tune$best.parameters$cost)
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 425 59
## MM 75 241
(75+59)/(425+241+75+59)
## [1] 0.1675
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 154 15
## MM 29 72
(29+15)/(154+72+29+15)
## [1] 0.162963
The training error rate lowered to 16.75% but the testing error rate remained the same at ~16.3%
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
set.seed(7)
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: 381
##
## ( 194 187 )
##
##
## 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 433 51
## MM 75 241
(75+51)/(433+241+75+51)
## [1] 0.1575
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 158 11
## MM 29 72
(29+11)/(158+72+29+11)
## [1] 0.1481481
The support vector classifier with a radial kernel has 381 support vectors. 194 of these vectors belong to level CH and the remaining 187 to MM. The training error rate is 15.75% and the test error rate is 14.81%.
set.seed(7)
OJ.tune = tune(svm, Purchase~., data = OJ.train, kernel = 'radial', ranges =list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(OJ.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.17375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39500 0.07197608
## 2 0.10 0.18750 0.04330127
## 3 1.00 0.17375 0.04730589
## 4 5.00 0.18500 0.04073969
## 5 10.00 0.18375 0.03682259
svm.radial = svm(Purchase ~ ., kernel = "radial", data = OJ.train, cost = OJ.tune$best.parameters$cost)
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 433 51
## MM 75 241
(75+51)/(433+241+75+51)
## [1] 0.1575
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 158 11
## MM 29 72
(29+11)/(158+72+29+11)
## [1] 0.1481481
Since we used already used the best cost value of 1 in the previous model the testing and training error rates remained the same.
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
set.seed(7)
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: 460
##
## ( 234 226 )
##
##
## 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 447 37
## MM 115 201
(115+37)/(447+201+115+37)
## [1] 0.19
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 162 7
## MM 39 62
(39+7)/(162+62+39+7)
## [1] 0.1703704
The polynomial kernel support vector classifier has 460 support vectors. 234 of the vectors belong to the CH level and the remaining 226 belong to MM. The training error rate is 19% and the testing error rate is ~17.04%
set.seed(7)
OJ.tune = tune(svm, Purchase~., data = OJ.train, kernel = 'polynomial', degree = 2, ranges =list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(OJ.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.17875
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39500 0.07197608
## 2 0.10 0.33000 0.05749396
## 3 1.00 0.20750 0.04684490
## 4 5.00 0.18375 0.04528076
## 5 10.00 0.17875 0.04411554
svm.poly = svm(Purchase ~ ., kernel = "polynomial", data = OJ.train, degree = 2,cost = OJ.tune$best.parameters$cost)
train.pred = predict(svm.poly, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 436 48
## MM 83 233
(83+48)/(436+233+83+48)
## [1] 0.16375
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 160 9
## MM 30 71
(30+9)/(160+71+30+9)
## [1] 0.1444444
After using the optimal cost value of 10 and degree value of 2 our training error rate is ~16.4% and the testing error rate is %14.4
(h) Overall, which approach seems to give the best results on this data?
Overall, the polynomial basis kernel gave the best testing error rate for this data set.