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.
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 = "red", xlab = "X1", ylab = "X2", pch = "+")
points(x1[y == 1], x2[y == 1], col = "blue", 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.212 -1.154 -1.108 1.199 1.255
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.05574 0.08952 -0.623 0.534
## x1 0.14512 0.31186 0.465 0.642
## x2 0.13885 0.30588 0.454 0.650
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.76 on 499 degrees of freedom
## Residual deviance: 692.34 on 497 degrees of freedom
## AIC: 698.34
##
## 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,x2,y)
lm.probs=predict(lm.fit,data,type='response')
lm.pred=rep(0, 500)
lm.pred[lm.probs >0.5]=1
plot(data[lm.pred == 1, ]$x1, data[lm.pred == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[lm.pred == 0, ]$x1, data[lm.pred == 0, ]$x2, col = (4 - 0), pch = (3 - 0))
(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.fit2=glm(y~poly(x1,2)+poly(x2,2),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.probs2=predict(lm.fit2,data,type='response')
lm.pred2=rep(0, 500)
lm.pred2[lm.probs2 >0.5]=1
plot(data[lm.pred2 == 1, ]$x1, data[lm.pred2 == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[lm.pred2 == 0, ]$x1, data[lm.pred2 == 0, ]$x2, col = (4 - 0), pch = (3 - 0))
(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)
## Warning: package 'e1071' was built under R version 3.6.3
data2=data
data2$y=as.factor(data2$y)
svm.fit=svm(y~x1+x2,data=data2,kernel="linear")
svm.pred=predict(svm.fit,data2)
plot(data2[svm.pred == 0, ]$x1, data2[svm.pred == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data2[svm.pred == 1, ]$x1, data2[svm.pred == 1, ]$x2, col = (4 - 1), pch = (3 - 1))
(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.
svm2=svm(y~x1+x2,data=data2,kernel="radial")
svm.pred2=predict(svm2,data)
plot(data[svm.pred2 == 0, ]$x1, data[svm.pred2 == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[svm.pred2 == 1, ]$x1, data[svm.pred2 == 1, ]$x2, col = (4 - 1), pch = (3 - 1))
(i) Comment on your results. As expected, both the linear regression and the svm with linear kernel were not accurate at predicting the non-linear relationship between the predictors and response.
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(ISLR)
## Warning: package 'ISLR' was built under R version 3.6.3
library(e1071)
summary(Auto)
## mpg cylinders displacement horsepower
## Min. : 9.00 Min. :3.000 Min. : 68.0 Min. : 46.0
## 1st Qu.:17.00 1st Qu.:4.000 1st Qu.:105.0 1st Qu.: 75.0
## Median :22.75 Median :4.000 Median :151.0 Median : 93.5
## Mean :23.45 Mean :5.472 Mean :194.4 Mean :104.5
## 3rd Qu.:29.00 3rd Qu.:8.000 3rd Qu.:275.8 3rd Qu.:126.0
## Max. :46.60 Max. :8.000 Max. :455.0 Max. :230.0
##
## weight acceleration year origin
## Min. :1613 Min. : 8.00 Min. :70.00 Min. :1.000
## 1st Qu.:2225 1st Qu.:13.78 1st Qu.:73.00 1st Qu.:1.000
## Median :2804 Median :15.50 Median :76.00 Median :1.000
## Mean :2978 Mean :15.54 Mean :75.98 Mean :1.577
## 3rd Qu.:3615 3rd Qu.:17.02 3rd Qu.:79.00 3rd Qu.:2.000
## Max. :5140 Max. :24.80 Max. :82.00 Max. :3.000
##
## name
## amc matador : 5
## ford pinto : 5
## toyota corolla : 5
## amc gremlin : 4
## amc hornet : 4
## chevrolet chevette: 4
## (Other) :365
mpgbin= as.factor(ifelse(Auto$mpg > median(Auto$mpg),1, 0))
Auto=data.frame(Auto,mpgbin)
summary(Auto)
## mpg cylinders displacement horsepower
## Min. : 9.00 Min. :3.000 Min. : 68.0 Min. : 46.0
## 1st Qu.:17.00 1st Qu.:4.000 1st Qu.:105.0 1st Qu.: 75.0
## Median :22.75 Median :4.000 Median :151.0 Median : 93.5
## Mean :23.45 Mean :5.472 Mean :194.4 Mean :104.5
## 3rd Qu.:29.00 3rd Qu.:8.000 3rd Qu.:275.8 3rd Qu.:126.0
## Max. :46.60 Max. :8.000 Max. :455.0 Max. :230.0
##
## weight acceleration year origin
## Min. :1613 Min. : 8.00 Min. :70.00 Min. :1.000
## 1st Qu.:2225 1st Qu.:13.78 1st Qu.:73.00 1st Qu.:1.000
## Median :2804 Median :15.50 Median :76.00 Median :1.000
## Mean :2978 Mean :15.54 Mean :75.98 Mean :1.577
## 3rd Qu.:3615 3rd Qu.:17.02 3rd Qu.:79.00 3rd Qu.:2.000
## Max. :5140 Max. :24.80 Max. :82.00 Max. :3.000
##
## name mpgbin
## amc matador : 5 0:196
## ford pinto : 5 1:196
## toyota corolla : 5
## amc gremlin : 4
## amc hornet : 4
## chevrolet chevette: 4
## (Other) :365
(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. Cost of 1 provides the best error.
set.seed(1)
tune.out<-tune(svm,mpgbin~.,data=Auto,kernel='linear',ranges=list(cost=c(0.01, 0.1, 1, 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
bestmod =tune.out$best.model
summary (bestmod )
##
## Call:
## best.tune(method = svm, train.x = mpgbin ~ ., data = Auto, ranges = list(cost = c(0.01,
## 0.1, 1, 10, 100)), kernel = "linear")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 1
##
## Number of Support Vectors: 56
##
## ( 26 30 )
##
##
## Number of Classes: 2
##
## Levels:
## 0 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. For the radial svm, a cost of 100 and gamma of 0.01 are the best models. For the polynomial svm a cost of 100 and degree 2 is the best model.
Radial
tune.radial=tune(svm, mpgbin ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), gamma = c(0.01, 0.1, 1, 5, 10, 100)))
summary(tune.radial)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 100 0.01
##
## - best performance: 0.01019231
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-02 1e-02 0.60192308 0.06346118
## 2 1e-01 1e-02 0.08653846 0.06488131
## 3 1e+00 1e-02 0.07134615 0.04769894
## 4 5e+00 1e-02 0.04846154 0.03905899
## 5 1e+01 1e-02 0.02294872 0.02534336
## 6 1e+02 1e-02 0.01019231 0.01786828
## 7 1e-02 1e-01 0.23974359 0.06938360
## 8 1e-01 1e-01 0.07891026 0.05147085
## 9 1e+00 1e-01 0.05096154 0.03995812
## 10 5e+00 1e-01 0.02301282 0.03069264
## 11 1e+01 1e-01 0.02294872 0.02807826
## 12 1e+02 1e-01 0.03064103 0.02651089
## 13 1e-02 1e+00 0.60192308 0.06346118
## 14 1e-01 1e+00 0.60192308 0.06346118
## 15 1e+00 1e+00 0.06365385 0.04845299
## 16 5e+00 1e+00 0.06121795 0.04387918
## 17 1e+01 1e+00 0.06121795 0.04387918
## 18 1e+02 1e+00 0.06121795 0.04387918
## 19 1e-02 5e+00 0.60192308 0.06346118
## 20 1e-01 5e+00 0.60192308 0.06346118
## 21 1e+00 5e+00 0.52814103 0.08413728
## 22 5e+00 5e+00 0.52814103 0.08238251
## 23 1e+01 5e+00 0.52814103 0.08238251
## 24 1e+02 5e+00 0.52814103 0.08238251
## 25 1e-02 1e+01 0.60192308 0.06346118
## 26 1e-01 1e+01 0.60192308 0.06346118
## 27 1e+00 1e+01 0.55615385 0.07526477
## 28 5e+00 1e+01 0.55358974 0.07343728
## 29 1e+01 1e+01 0.55358974 0.07343728
## 30 1e+02 1e+01 0.55358974 0.07343728
## 31 1e-02 1e+02 0.60192308 0.06346118
## 32 1e-01 1e+02 0.60192308 0.06346118
## 33 1e+00 1e+02 0.60192308 0.06346118
## 34 5e+00 1e+02 0.60192308 0.06346118
## 35 1e+01 1e+02 0.60192308 0.06346118
## 36 1e+02 1e+02 0.60192308 0.06346118
Polynomial
tune.poly = tune(svm, mpgbin ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100), degree = c(2, 3, 4)))
summary(tune.poly)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 100 2
##
## - best performance: 0.3167308
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5946154 0.08083319
## 2 1e-01 2 0.5946154 0.08083319
## 3 1e+00 2 0.5946154 0.08083319
## 4 5e+00 2 0.5946154 0.08083319
## 5 1e+01 2 0.5638462 0.09189684
## 6 1e+02 2 0.3167308 0.06785219
## 7 1e-02 3 0.5946154 0.08083319
## 8 1e-01 3 0.5946154 0.08083319
## 9 1e+00 3 0.5946154 0.08083319
## 10 5e+00 3 0.5946154 0.08083319
## 11 1e+01 3 0.5946154 0.08083319
## 12 1e+02 3 0.3268590 0.11846184
## 13 1e-02 4 0.5946154 0.08083319
## 14 1e-01 4 0.5946154 0.08083319
## 15 1e+00 4 0.5946154 0.08083319
## 16 5e+00 4 0.5946154 0.08083319
## 17 1e+01 4 0.5946154 0.08083319
## 18 1e+02 4 0.5946154 0.08083319
(d) Make some plots to back up your assertions in (b) and (c). Found a nifty function to plot multiple plot.svm results
svm1= svm(mpgbin~., data=Auto, kernel="linear", cost = 1)
svm2 = svm(mpgbin~., data=Auto, kernel="radial", cost = 100, gamma = 0.01)
svm3 = svm(mpgbin~., data=Auto, kernel="polynomial", cost = 100, degree = 2)
plotpairs = function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpgbin", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}
plotpairs(svm1)
plotpairs(svm2)
plotpairs(svm3)
*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)
test = !train
train.oj=OJ[train,]
test.oj = 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. Out of the 435 support vectors there are 219 for Citrus Hill and 216 for Minute Maid
svm.fit = svm(Purchase ~., data=train.oj, kernel = 'linear',cost = 0.01)
summary(svm.fit)
##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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 training error rate is 17.5% and the test error rate is 17.7%
training.pred = predict(svm.fit, train.oj)
table(train.oj$Purchase, training.pred)
## training.pred
## CH MM
## CH 420 65
## MM 75 240
testing.pred = predict(svm.fit, test.oj)
table(test.oj$Purchase, testing.pred)
## testing.pred
## CH MM
## CH 153 15
## MM 33 69
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
tune.out = tune(svm, Purchase ~., data = train.oj, 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
## 10
##
## - best performance: 0.17125
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17375 0.03884174
## 2 0.01778279 0.17500 0.03996526
## 3 0.03162278 0.17750 0.03717451
## 4 0.05623413 0.18000 0.03073181
## 5 0.10000000 0.17875 0.03064696
## 6 0.17782794 0.17875 0.03537988
## 7 0.31622777 0.17875 0.03438447
## 8 0.56234133 0.17625 0.03197764
## 9 1.00000000 0.17500 0.03061862
## 10 1.77827941 0.17375 0.02972676
## 11 3.16227766 0.17250 0.03270236
## 12 5.62341325 0.17250 0.03322900
## 13 10.00000000 0.17125 0.03488573
(e) Compute the training and test error rates using this new value for cost. Using a cost = 10 the new training error rate is 16.4% and the new test error rate is 14.8% Interesting to note that the test error rate is lower than the training error.
svm.new = svm(Purchase~., data=train.oj, kernel = 'linear', cost = 10)
training.pred = predict(svm.new, train.oj)
table(train.oj$Purchase, training.pred)
## training.pred
## CH MM
## CH 423 62
## MM 69 246
testing.pred = predict(svm.new, test.oj)
table(test.oj$Purchase, testing.pred)
## testing.pred
## CH MM
## CH 156 12
## MM 28 74
(f) 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 = train.oj)
summary(svm.radial)
##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, 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
training.pred = predict(svm.radial, train.oj)
table(train.oj$Purchase, training.pred)
## training.pred
## CH MM
## CH 441 44
## MM 77 238
testing.pred = predict(svm.radial, test.oj)
table(test.oj$Purchase, testing.pred)
## testing.pred
## CH MM
## CH 151 17
## MM 33 69
tune.out = tune(svm, Purchase ~., data = train.oj, kernel = 'radial', ranges=list(cost=10^seq(-2,1,by = 0.25)))
svm.radial = svm(Purchase ~ ., data = train.oj, kernel = "radial", cost = tune.out$best.parameters$cost)
training.pred = predict(svm.radial, train.oj)
table(train.oj$Purchase, training.pred)
## training.pred
## CH MM
## CH 437 48
## MM 71 244
testing.pred = predict(svm.radial, test.oj)
table(test.oj$Purchase, testing.pred)
## testing.pred
## CH MM
## CH 150 18
## MM 30 72
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
svm.polynomial = svm(Purchase ~ ., kernel = "polynomial", data = train.oj, degree = 2)
summary(svm.polynomial)
##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, kernel = "polynomial",
## 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
training.pred = predict(svm.polynomial, train.oj)
table(train.oj$Purchase, training.pred)
## training.pred
## CH MM
## CH 449 36
## MM 110 205
testing.pred = predict(svm.polynomial, test.oj)
table(test.oj$Purchase, testing.pred)
## testing.pred
## CH MM
## CH 153 15
## MM 45 57
tune.out = tune(svm, Purchase ~., data = train.oj, kernel = 'polynomial', degree = 2, ranges=list(cost=10^seq(-2,1,by = 0.25)))
svm.radial = svm(Purchase ~ ., data = train.oj, kernel = "polynomial", degree = 2, cost = tune.out$best.parameters$cost)
training.pred = predict(svm.polynomial, train.oj)
table(train.oj$Purchase, training.pred)
## training.pred
## CH MM
## CH 449 36
## MM 110 205
testing.pred = predict(svm.polynomial, test.oj)
table(test.oj$Purchase, testing.pred)
## testing.pred
## CH MM
## CH 153 15
## MM 45 57
(h) Overall, which approach seems to give the best results on this data? Linear Results - 16..4% training and 14.8% test Radial Results - 14.9% training and 17.8% test Poly Results - 18.3training and 22.2% test The best test error rate is from the linear svm model.