library(ISLR)
library(tidyverse)
library(plotly)
library(e1071)
library(ISLR)
library(caret)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(4)
x1=runif(500)-0.5
x2=runif(500)-0.5
y=1*(x1^2-x2^2 > 0)
df=data.frame(x1=x1, x2=x2, y=as.factor(y))Plot the observations, colored according to their class labels. Your plot should display \(X_1\) on the x-axis, and \(X_2\) on the yaxis.
plot(x1,x2,col = (4 - y), pch = (3 - y))Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.
glm.fit = glm(y~x1+x2, data=df, family = 'binomial')
summary(glm.fit)##
## Call:
## glm(formula = y ~ x1 + x2, family = "binomial", data = df)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.32247 -1.14039 -0.00147 1.16924 1.30059
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.016756 0.090201 0.186 0.8526
## x1 0.001849 0.305014 0.006 0.9952
## x2 0.636839 0.317138 2.008 0.0446 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.15 on 499 degrees of freedom
## Residual deviance: 689.08 on 497 degrees of freedom
## AIC: 695.08
##
## Number of Fisher Scoring iterations: 3
Comments: None of the 2 variables are significante, therefore are not good predictors.
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.
glm.probs = predict(glm.fit, df, type = 'response')
glm.preds = rep(0,500)
glm.preds[glm.probs>0.5] = 1
table(preds=glm.preds, truth=df$y)## truth
## preds 0 1
## 0 144 113
## 1 106 137
plot(x1,x2,col=4-glm.preds, pch = 3-glm.preds)Comments: First one thing to notice is that depending on the seed, is weather the model is good at predicting 1 or 0. The second thing to notice is that the decision boundary is indeed linear. I also tried different boundaries, and the linear decision boundary stayed linear.
Now fit a logistic regression model to the data using non-linear functions of \(X_1\) and \(X_2\) as predictors (e.g. \(X^2_1\), \(X_1 × X_2\), \(log(X_2)\), and so forth).
glm.fit2 = glm(y ~ x1 + x2+ I(x1^2) + I(x2^2) + I(x1 * x2), data = df, family = binomial)## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm.fit2)##
## Call:
## glm(formula = y ~ x1 + x2 + I(x1^2) + I(x2^2) + I(x1 * x2), family = binomial,
## data = df)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -0.006433 0.000000 0.000000 0.000000 0.006689
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 8.162e+00 1.361e+02 0.060 0.952
## x1 4.018e+02 2.339e+04 0.017 0.986
## x2 5.833e+02 2.121e+04 0.028 0.978
## I(x1^2) 1.033e+05 1.171e+06 0.088 0.930
## I(x2^2) -1.046e+05 1.258e+06 -0.083 0.934
## I(x1 * x2) -3.524e+03 1.382e+05 -0.025 0.980
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9315e+02 on 499 degrees of freedom
## Residual deviance: 8.8597e-05 on 494 degrees of freedom
## AIC: 12
##
## Number of Fisher Scoring iterations: 25
Comments: Again, none of the variables are significant again.
set.seed(123)
df = data.frame(x1 = x1, x2 = x2, y = y)
glm.probs2 = predict(glm.fit2, df, type = 'response')
glm.preds2 = rep(0,500)
glm.preds2 = as_factor(ifelse(glm.probs2 > 0.55, 1, 0))
table(preds=glm.preds2, truth=df$y)## truth
## preds 0 1
## 0 250 0
## 1 0 250
Comments: We can see that the quadratic transformation led to a perfect separation.
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.
plot(df[glm.preds2 == 1, ]$x1, df[glm.preds2 == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(df[glm.preds2 == 0, ]$x1, df[glm.preds2 == 0, ]$x2, col = (4 - 0), pch = (3 - 0))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.
df$y = as.factor(df$y)
svm.fit = svm(y ~ x1 + x2, df, kernel = "linear", cost = 0.01)
preds = predict(svm.fit, df)
plot(df[preds == 0, ]$x1, df[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(df[preds == 1, ]$x1, df[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))Comments: This support vector classifier (even with low cost) classifies all points to a single class.
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.
df$y = as.factor(df$y)
svmnl.fit = svm(y ~ x1 + x2, df, kernel = "radial", gamma = 1)
preds = predict(svmnl.fit, df)
plot(df[preds == 0, ]$x1, df[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(df[preds == 1, ]$x1, df[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))Comments: Here again, the non-linear decision boundary is surprisingly very similar to the true decision boundary.
Comment on your results.
Comments: We can see that the SVM method with a non-linear kernel and logistic regression with interactions terms are equally powerful when predicting non-linear decision boundaries. But, in the other hand, SVM with linear kernel and logistic regression without interaction term have little accuracy when predicting non.linear decision boundaries.
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.
Auto = AutoCreate 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.
mpglevel = median(Auto$mpg)
Auto$mpglevel = as_factor(ifelse(Auto$mpg > mpglevel,1,0))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(123)
tune.svm = tune(svm, mpglevel ~ . -mpg, data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100)))
tune.linear = tune.svm$best.model
summary(tune.svm)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.01
##
## - best performance: 0.08910256
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.08910256 0.03791275
## 2 1e-01 0.09403846 0.04842472
## 3 1e+00 0.09147436 0.05817937
## 4 5e+00 0.10423077 0.06425850
## 5 1e+01 0.10673077 0.06562804
## 6 1e+02 0.12724359 0.06371052
Comments: So far, the best cost is 0.01, with an error of 0.089.
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(123)
tune.svm = tune(svm, mpglevel ~ . -mpg, data = Auto, kernel = "radial", ranges = list(cost = c(0.1, 1, 5, 10), gamma = c(0.01, 0.1, 1, 5, 10, 100)))
tune.radial = tune.svm$best.model
summary(tune.svm)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 5 0.1
##
## - best performance: 0.07365385
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.1 1e-02 0.11211538 0.05486624
## 2 1.0 1e-02 0.08910256 0.03791275
## 3 5.0 1e-02 0.08397436 0.03933133
## 4 10.0 1e-02 0.09403846 0.04842472
## 5 0.1 1e-01 0.08910256 0.03979296
## 6 1.0 1e-01 0.08653846 0.03578151
## 7 5.0 1e-01 0.07365385 0.05975763
## 8 10.0 1e-01 0.07365385 0.05852240
## 9 0.1 1e+00 0.58173077 0.04740051
## 10 1.0 1e+00 0.08660256 0.04466420
## 11 5.0 1e+00 0.08916667 0.05328055
## 12 10.0 1e+00 0.08916667 0.05328055
## 13 0.1 5e+00 0.58173077 0.04740051
## 14 1.0 5e+00 0.51532051 0.06910961
## 15 5.0 5e+00 0.50769231 0.06675495
## 16 10.0 5e+00 0.50769231 0.06675495
## 17 0.1 1e+01 0.58173077 0.04740051
## 18 1.0 1e+01 0.53583333 0.07213142
## 19 5.0 1e+01 0.53333333 0.07201901
## 20 10.0 1e+01 0.53333333 0.07201901
## 21 0.1 1e+02 0.58173077 0.04740051
## 22 1.0 1e+02 0.58173077 0.04740051
## 23 5.0 1e+02 0.58173077 0.04740051
## 24 10.0 1e+02 0.58173077 0.04740051
Comments: We got the lowest error at Cost = 10.0 and gamma at 1.0
set.seed(123)
tune.svm = tune(svm, mpglevel ~ . -mpg, data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), degree = c(2, 3, 4)))
tune.polynomial = tune.svm$best.model
summary(tune.svm)##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 2
##
## - best performance: 0.3086538
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5817308 0.04740051
## 2 1e-01 2 0.5817308 0.04740051
## 3 1e+00 2 0.5817308 0.04740051
## 4 5e+00 2 0.5817308 0.04740051
## 5 1e+01 2 0.5714744 0.04575370
## 6 1e+02 2 0.3086538 0.10382736
## 7 1e-02 3 0.5817308 0.04740051
## 8 1e-01 3 0.5817308 0.04740051
## 9 1e+00 3 0.5817308 0.04740051
## 10 5e+00 3 0.5817308 0.04740051
## 11 1e+01 3 0.5817308 0.04740051
## 12 1e+02 3 0.4159615 0.12008716
## 13 1e-02 4 0.5817308 0.04740051
## 14 1e-01 4 0.5817308 0.04740051
## 15 1e+00 4 0.5817308 0.04740051
## 16 5e+00 4 0.5817308 0.04740051
## 17 1e+01 4 0.5817308 0.04740051
## 18 1e+02 4 0.5817308 0.04740051
Comments: We got the lowest error at Cost = 100.0 and degree 2.0
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, x_1∼x_4) $
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","name","mpglevel")]){
plot(fit,Auto,as.formula(paste("mpg~",name,sep="")))
}
}
plotpairs(svm_linear)This problem involves the OJ data set which is part of the ISLR package.
Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(1)
train = sample(nrow(OJ), 800)
OJ.train = OJ[train, ]
OJ.test = OJ[-train, ]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: 435
##
## ( 219 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
Comments: The model classifier created 432 support vectors out of 800 observations (train), and from those 219 are from the CH juice and 219 correspond to the MM juice.
What are the training and test error rates?
#Train error
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)## train.pred
## CH MM
## CH 420 65
## MM 75 240
(75+65) / (420+65+75+240) ## [1] 0.175
# Test Error
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)## test.pred
## CH MM
## CH 153 15
## MM 33 69
(33+15) / (153+33+15+69)## [1] 0.1777778
Comments: Train error rate is 0.175 (17.5%), while test error rate is 17.8%, which is higher than the train error.
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.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.16875
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17625 0.02853482
## 2 0.01778279 0.17625 0.03143004
## 3 0.03162278 0.17125 0.02829041
## 4 0.05623413 0.17625 0.02853482
## 5 0.10000000 0.17250 0.03162278
## 6 0.17782794 0.17125 0.02829041
## 7 0.31622777 0.17125 0.02889757
## 8 0.56234133 0.17125 0.02703521
## 9 1.00000000 0.17500 0.02946278
## 10 1.77827941 0.17375 0.02729087
## 11 3.16227766 0.16875 0.03019037
## 12 5.62341325 0.17375 0.03304563
## 13 10.00000000 0.17375 0.03197764
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.parameter$cost)# Train error
train.pred = predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)## train.pred
## CH MM
## CH 423 62
## MM 70 245
(70 + 62) / (423 + 245 + 70 + 62)## [1] 0.165
# Test Error
test.pred = predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)## test.pred
## CH MM
## CH 156 12
## MM 29 73
(29 + 12) / (156 + 73 + 29 + 12)## [1] 0.1518519
Comments: Train error rate is 16.5%, while test error rate is 15.18%, in this case the test error rate is lower than the train error rate.
Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
svm.radial = svm(Purchase ~ ., kernel = "radial", data = OJ.train)
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
train.pred = predict(svm.radial, OJ.train)
table(OJ.train$Purchase, train.pred)## train.pred
## CH MM
## CH 441 44
## MM 77 238
(77 + 44) / (438 + 238 + 77 + 44)## [1] 0.1518193
test.pred = predict(svm.radial, OJ.test)
table(OJ.test$Purchase, test.pred)## test.pred
## CH MM
## CH 151 17
## MM 33 69
(33 + 17) / (151 + 69 + 33 + 17)## [1] 0.1851852
Comments: Train error rate is 15.18%, while test error rate is 18.52%, in this case the train error rate is lower than the test error rate.
Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
set.seed(2)
tune.out = tune(svm, Purchase ~ ., data = OJ.train, kernel = "polynomial", degree = 2, 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.18
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39000 0.03670453
## 2 0.01778279 0.37000 0.03395258
## 3 0.03162278 0.36375 0.03197764
## 4 0.05623413 0.34500 0.03291403
## 5 0.10000000 0.32125 0.03866254
## 6 0.17782794 0.24750 0.03322900
## 7 0.31622777 0.20250 0.04073969
## 8 0.56234133 0.20250 0.03670453
## 9 1.00000000 0.19625 0.03910900
## 10 1.77827941 0.19125 0.03586723
## 11 3.16227766 0.18000 0.04005205
## 12 5.62341325 0.18000 0.04133199
## 13 10.00000000 0.18125 0.03830162
svm.poly = svm(Purchase ~ ., kernel = "polynomial", degree = 2, data = OJ.train, cost = tune.out$best.parameter$cost)
summary(svm.poly)##
## Call:
## svm(formula = Purchase ~ ., data = OJ.train, kernel = "polynomial",
## degree = 2, cost = tune.out$best.parameter$cost)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 3.162278
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 385
##
## ( 197 188 )
##
##
## 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 451 34
## MM 90 225
(90 + 34) / (451 + 225 + 90 + 34)## [1] 0.155
test.pred = predict(svm.poly, OJ.test)
table(OJ.test$Purchase, test.pred)## test.pred
## CH MM
## CH 154 14
## MM 41 61
(41 + 14)/(41 + 14 + 154 + 61)## [1] 0.2037037
Overall, which approach seems to give the best results on this data?
Comments: I tried different seeds, and it really much relies on which seed you are using, but in general both the Radial and the Linear did a very good performance.