(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)\)
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.2
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.0 ✔ stringr 1.4.1
## ✔ readr 2.1.3 ✔ forcats 0.5.2
## Warning: package 'readr' was built under R version 4.2.2
## Warning: package 'forcats' was built under R version 4.2.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(e1071)
set.seed(5)
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],xlab='x1',ylab='x2',col='navy',pch='$')
points(x1[y==1],x2[y==1],col='darkgreen',pch='#')
(c) Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.
df=data.frame(x1=x1,x2=x2,y=y)
glm.fit=glm(y~.,data=df,family=binomial)
summary(glm.fit)
##
## Call:
## glm(formula = y ~ ., family = binomial, data = df)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.200 -1.161 -1.131 1.190 1.223
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.03150 0.08949 -0.352 0.725
## x1 -0.06176 0.30506 -0.202 0.840
## x2 -0.11509 0.31086 -0.370 0.711
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 693.02 on 499 degrees of freedom
## Residual deviance: 692.85 on 497 degrees of freedom
## AIC: 698.85
##
## Number of Fisher Scoring iterations: 3
It appears that neither predictor are statistically significant predictors for y.
(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.
glm.prob=predict(glm.fit,newdata=df,type='response')
glm.pred=ifelse(glm.prob>0.5,1,0)
data.p=df[glm.pred==1,]
data.n=df[glm.pred==0,]
plot(data.p$x1,data.p$x2,col='navy',xlab='x1',ylab='x2',pch='$')
points(data.n$x1,data.n$x2,col='darkgreen',pch='#')
(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_2^1\) , \(X_1×X_2\), \(log(X_2)\), and so forth).
glm.fit2=glm(y~x1+x2+x1^2+x2^3+I(x1*x2),data=df,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.
glm.prob2=predict(glm.fit2,df,type='response')
glm.pred2=ifelse(glm.prob2>0.5,1,0)
data.p2=df[glm.pred2==1,]
data.n2=df[glm.pred2==0,]
plot(data.p2$x1,data.p2$x2,col='navy',xlab='x1',ylab='x2',pch='$')
points(data.n2$x1,data.n2$x2,col='darkgreen',pch='#')
This model has a non-linear boundary but is different from the original model.
(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.
non.fit=svm(as.factor(y)~x1+x2,data=df,gamma=1)
non.fit.pred=predict(non.fit,newdata=df)
data.p=df[non.fit.pred==1,]
data.n=df[non.fit.pred==0,]
plot(data.p$x1,data.p$x2,col='navy',xlab='x1',ylab='x2',pch='$')
points(data.n$x1,data.n$x2,col='darkgreen',pch='#')
This is similar to the plot created in part (b).
(i) Comment on your results.
The SVM with the non-linear kernel was able to find the non-linear decision boundary, but the logistic regression was not able to do it, even with non-linear terms in it.
(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)
attach(Auto)
## The following object is masked from package:ggplot2:
##
## mpg
gas.median=median(mpg)
mpg01=ifelse(mpg>gas.median,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(5)
tune.out=tune(svm,mpglevel~.,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.01019231
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07391026 0.02208631
## 2 1e-01 0.04576923 0.02585417
## 3 1e+00 0.01019231 0.01786828
## 4 1e+01 0.02294872 0.01871043
## 5 1e+02 0.03576923 0.03002696
The CV 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.
#Polynomial Kernel
set.seed(5)
tune.poly=tune(svm,mpglevel~.,data=Auto,kernel='polynomial',ranges=list(cost=c(0.01,0.1,1,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.3091667
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5841026 0.04075521
## 2 1e-01 2 0.5841026 0.04075521
## 3 1e+00 2 0.5841026 0.04075521
## 4 1e+01 2 0.5738462 0.03762359
## 5 1e+02 2 0.3091667 0.08547332
## 6 1e-02 3 0.5841026 0.04075521
## 7 1e-01 3 0.5841026 0.04075521
## 8 1e+00 3 0.5841026 0.04075521
## 9 1e+01 3 0.5841026 0.04075521
## 10 1e+02 3 0.3324359 0.13300152
## 11 1e-02 4 0.5841026 0.04075521
## 12 1e-01 4 0.5841026 0.04075521
## 13 1e+00 4 0.5841026 0.04075521
## 14 1e+01 4 0.5841026 0.04075521
## 15 1e+02 4 0.5841026 0.04075521
The lowest CV error obtained with the polynomial kernel is for cost=100 and degree =2.
#Radial Kernel
set.seed(5)
tune.rad=tune(svm,mpglevel~.,data=Auto,kernel='radial',ranges=list(cost=c(0.1,1,5,25,100),gamma=c(0.01,0.1,10,25,100)))
summary(tune.rad)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 100 0.01
##
## - best performance: 0.01012821
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.1 0.01 0.08416667 0.02962936
## 2 1.0 0.01 0.07134615 0.02315997
## 3 5.0 0.01 0.04833333 0.02175755
## 4 25.0 0.01 0.01019231 0.01315951
## 5 100.0 0.01 0.01012821 0.01307720
## 6 0.1 0.10 0.07647436 0.02060620
## 7 1.0 0.10 0.05089744 0.02357836
## 8 5.0 0.10 0.02044872 0.02354784
## 9 25.0 0.10 0.02032051 0.01999445
## 10 100.0 0.10 0.02288462 0.01870128
## 11 0.1 10.00 0.58410256 0.04075521
## 12 1.0 10.00 0.55115385 0.04522834
## 13 5.0 10.00 0.54608974 0.04883070
## 14 25.0 10.00 0.54608974 0.04883070
## 15 100.0 10.00 0.54608974 0.04883070
## 16 0.1 25.00 0.58410256 0.04075521
## 17 1.0 25.00 0.57397436 0.04512869
## 18 5.0 25.00 0.56641026 0.04556866
## 19 25.0 25.00 0.56641026 0.04556866
## 20 100.0 25.00 0.56641026 0.04556866
## 21 0.1 100.00 0.58410256 0.04075521
## 22 1.0 100.00 0.58410256 0.04075521
## 23 5.0 100.00 0.58410256 0.04075521
## 24 25.0 100.00 0.58410256 0.04075521
## 25 100.0 100.00 0.58410256 0.04075521
The lowest CV error obtained with the radial kernel is for cost=100 and gamma=.01.
(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=100,degree=2)
svm.rad=svm(mpglevel~.,data=Auto,kernel='radial',cost=100,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)
plotpairs(svm.poly)
plotpairs(svm.rad)
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
detach(Auto)
attach(OJ)
set.seed(5)
train=sample(nrow(OJ),800)
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.
svm.OJ=svm(Purchase~.,kernel='linear',data=train.oj,cost=0.01)
summary(svm.OJ)
##
## 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: 441
##
## ( 219 222 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The SVM created 441 support vectors out of the 800 training points. 219 belong to Citrus Hill and 222 belong to Minute Maid.
(c) What are the training and test error rates?
#Training Error
train.pred=predict(svm.OJ,train.oj)
table(train.oj$Purchase,train.pred)
## train.pred
## CH MM
## CH 431 59
## MM 74 236
mean(train.pred!=train.oj$Purchase)
## [1] 0.16625
The training error rate is 16.63%
#Test Error
test.pred=predict(svm.OJ,test.oj)
table(test.oj$Purchase,test.pred)
## test.pred
## CH MM
## CH 145 18
## MM 27 80
mean(test.pred!=test.oj$Purchase)
## [1] 0.1666667
The test error rate is slightly higher than the training error rate at 16.67%.
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(5)
tune.outy=tune(svm,Purchase~.,data=train.oj,kernel='linear',ranges=list(cost=10^seq(-2,1,by=0.25)))
summary(tune.outy)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 10
##
## - best performance: 0.16625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.17625 0.05382908
## 2 0.01778279 0.17500 0.04750731
## 3 0.03162278 0.17375 0.04945888
## 4 0.05623413 0.17375 0.04767147
## 5 0.10000000 0.17375 0.04348132
## 6 0.17782794 0.17250 0.04199868
## 7 0.31622777 0.17375 0.04730589
## 8 0.56234133 0.17250 0.04923018
## 9 1.00000000 0.16750 0.04456581
## 10 1.77827941 0.16750 0.04495368
## 11 3.16227766 0.17000 0.04758034
## 12 5.62341325 0.17250 0.04241004
## 13 10.00000000 0.16625 0.03955042
It looks like the optimal amount for cost is 10.
(e) Compute the training and test error rates using this new value for cost.
#New training error for cost=10
best=tune.outy$best.parameters$cost
svm.newcost=svm(Purchase~.,kernel='linear',data=train.oj,cost=best)
train.newpred=predict(svm.newcost,train.oj)
table(train.oj$Purchase,train.newpred)
## train.newpred
## CH MM
## CH 435 55
## MM 74 236
mean(train.newpred!=train.oj$Purchase)
## [1] 0.16125
The new training error rate for cost=10 is 16.13%.
#New test error for cost=10
test.newpred=predict(svm.newcost,test.oj)
table(test.oj$Purchase,test.newpred)
## test.newpred
## CH MM
## CH 145 18
## MM 29 78
mean(test.newpred!=test.oj$Purchase)
## [1] 0.1740741
The new test error rate for cost=10 is 17.41%.
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
#Radial (b)
rad.OJ=svm(Purchase~.,kernel='radial',data=train.oj)
summary(rad.OJ)
##
## Call:
## svm(formula = Purchase ~ ., data = train.oj, kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 374
##
## ( 183 191 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The SVM created 374 support vectors out of the 800 training points. 183 belong to Citrus Hill and 191 belong to Minute Maid.
#Radial (c) Training error
train.pred2=predict(rad.OJ,train.oj)
table(train.oj$Purchase,train.pred2)
## train.pred2
## CH MM
## CH 447 43
## MM 77 233
mean(train.pred2!=train.oj$Purchase)
## [1] 0.15
The training error rate is 15%.
#Radial (c) Test error
test.pred2=predict(rad.OJ,test.oj)
table(test.oj$Purchase,test.pred2)
## test.pred2
## CH MM
## CH 147 16
## MM 30 77
mean(test.pred2!=test.oj$Purchase)
## [1] 0.1703704
The test error rate is 17.04%.
#Radial (d)
set.seed(5)
tune.outy2=tune(svm,Purchase~.,data=train.oj,kernel='radial',ranges=list(cost=10^seq(-2,1,by=0.25)))
summary(tune.outy2)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 3.162278
##
## - best performance: 0.16625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.38750 0.04677072
## 2 0.01778279 0.38750 0.04677072
## 3 0.03162278 0.34625 0.06209592
## 4 0.05623413 0.20875 0.04332131
## 5 0.10000000 0.18875 0.04348132
## 6 0.17782794 0.18500 0.04518481
## 7 0.31622777 0.18125 0.03738408
## 8 0.56234133 0.17500 0.03004626
## 9 1.00000000 0.17375 0.02791978
## 10 1.77827941 0.17625 0.03087272
## 11 3.16227766 0.16625 0.03007514
## 12 5.62341325 0.16875 0.03186887
## 13 10.00000000 0.18125 0.03186887
Our optimal cost appears to be 3.162278.
#Radial (e): New training error for cost=3.162278
best2=tune.outy2$best.parameters$cost
svm.newcost2=svm(Purchase~.,kernel='radial',data=train.oj,cost=best2)
train.newpred2=predict(svm.newcost2,train.oj)
table(train.oj$Purchase,train.newpred2)
## train.newpred2
## CH MM
## CH 452 38
## MM 77 233
mean(train.newpred2!=train.oj$Purchase)
## [1] 0.14375
Our new training error rate is 14.38%.
#Radial (e): New test error for cost=3.162278
test.newpred2=predict(svm.newcost2,test.oj)
table(test.oj$Purchase,test.newpred2)
## test.newpred2
## CH MM
## CH 148 15
## MM 32 75
mean(test.newpred2!=test.oj$Purchase)
## [1] 0.1740741
Our new test error rate is 17.41%, which was worse than it was before we found the optimal cost. This is the same as the linear kernel.
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
#Poly (b)
poly.OJ=svm(Purchase~.,kernel='polynomial',data=train.oj,degree=2)
summary(poly.OJ)
##
## 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: 439
##
## ( 216 223 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The SVM created 439 support vectors out of the 800 training points. 216 belong to Citrus Hill and 223 belong to Minute Maid.
#Poly (c) Training error
train.pred3=predict(poly.OJ,train.oj)
table(train.oj$Purchase,train.pred3)
## train.pred3
## CH MM
## CH 455 35
## MM 106 204
mean(train.pred3!=train.oj$Purchase)
## [1] 0.17625
The training error here is 17.63%.
#Poly (c) Test error
test.pred3=predict(poly.OJ,test.oj)
table(test.oj$Purchase,test.pred3)
## test.pred3
## CH MM
## CH 151 12
## MM 44 63
mean(test.pred3!=test.oj$Purchase)
## [1] 0.2074074
The test error rate here is 20.74%.
#Poly (d)
set.seed(5)
tune.outy3=tune(svm,Purchase~.,data=train.oj,kernel='poly',degree=2,ranges=list(cost=10^seq(-2,1,by=0.25)))
summary(tune.outy3)
##
## 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.36625 0.05205833
## 2 0.01778279 0.35375 0.05744865
## 3 0.03162278 0.34750 0.05645795
## 4 0.05623413 0.32250 0.06061032
## 5 0.10000000 0.30875 0.05070681
## 6 0.17782794 0.25250 0.05857094
## 7 0.31622777 0.20500 0.03689324
## 8 0.56234133 0.20250 0.03809710
## 9 1.00000000 0.20250 0.04199868
## 10 1.77827941 0.19625 0.03682259
## 11 3.16227766 0.19375 0.03596391
## 12 5.62341325 0.18375 0.03387579
## 13 10.00000000 0.17500 0.03280837
It appears that the optimal cost here is 10.
#Poly (e): New training error for cost=10
best3=tune.outy3$best.parameters$cost
svm.newcost3=svm(Purchase~.,kernel='poly',degree=2,data=train.oj,cost=best3)
train.newpred3=predict(svm.newcost3,train.oj)
table(train.oj$Purchase,train.newpred3)
## train.newpred3
## CH MM
## CH 452 38
## MM 75 235
mean(train.newpred3!=train.oj$Purchase)
## [1] 0.14125
The training error rate here is 14.13%.
#Poly (e): New test error for cost=10
test.newpred3=predict(svm.newcost3,test.oj)
table(test.oj$Purchase,test.newpred3)
## test.newpred3
## CH MM
## CH 149 14
## MM 31 76
mean(test.newpred3!=test.oj$Purchase)
## [1] 0.1666667
The test error rate here is 16.67%.
(h) Overall, which approach seems to give the best results on this data?
The polynomial approach with degree=2 and cost=10 seems to give the best results. It has the lowest test error rate at 16.67% and the lowest training error rate at 14.13%!