Chapter 09 (page 368): 5, 7, 8
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.
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 3.6.3
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.2 v purrr 0.3.4
## v tibble 3.0.3 v dplyr 1.0.1
## v tidyr 1.1.1 v stringr 1.4.0
## v readr 1.3.1 v forcats 0.5.0
## Warning: package 'ggplot2' was built under R version 3.6.3
## Warning: package 'tibble' was built under R version 3.6.3
## Warning: package 'tidyr' was built under R version 3.6.3
## Warning: package 'readr' was built under R version 3.6.3
## Warning: package 'purrr' was built under R version 3.6.3
## Warning: package 'dplyr' was built under R version 3.6.3
## Warning: package 'stringr' was built under R version 3.6.3
## Warning: package 'forcats' was built under R version 3.6.3
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
set.seed(421)
x1=runif(500) - 0.5
x2=runif(500) - 0.5
y=as_factor(1*(x1*x1 - x2*x2 > 0))
df<-tibble(x1=x1,
x2=x2,
y=y)
df
## # A tibble: 500 x 3
## x1 x2 y
## <dbl> <dbl> <fct>
## 1 0.290 -0.384 0
## 2 -0.355 -0.313 1
## 3 0.215 0.0556 1
## 4 -0.185 -0.459 0
## 5 0.345 -0.143 1
## 6 0.200 0.0506 1
## 7 0.400 0.149 1
## 8 0.183 -0.476 0
## 9 0.0298 -0.388 0
## 10 -0.291 -0.130 1
## # ... with 490 more rows
library(plotly)
## Warning: package 'plotly' was built under R version 3.6.3
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
p<-ggplot(data=df,mapping=aes(x=x1,y=x2,color=y))+
geom_point() +
theme_light() +
theme(legend.position = "none")
ggplotly(p)
x1 and x2 are not significant
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.278 -1.227 1.089 1.135 1.175
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.11999 0.08971 1.338 0.181
## x1 -0.16881 0.30854 -0.547 0.584
## x2 -0.08198 0.31476 -0.260 0.795
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 691.35 on 499 degrees of freedom
## Residual deviance: 690.99 on 497 degrees of freedom
## AIC: 696.99
##
## Number of Fisher Scoring iterations: 3
With the given model and a probability threshold of 0.5, all points are classified to single class and no decision boundary can be shown. So I shifted the probability threshold to 0.52 to show a meaningful decision boundary. This boundary is linear.
glm_prob = predict(lm.fit, df, type = "response")
df<-mutate(df, pred = as_factor(ifelse(glm_prob > 0.52, 1, 0)))
q<-ggplot(data=df,mapping=aes(x=x1,y=x2,color=pred))+
geom_point() +
theme_light() +
theme(legend.position = "none")
ggplotly(q)
squares, product interaction terms are being used to fit the model.
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
This non-linear decision boundary closely resembles the true decision boundary.
A linear kernel, even with low cost fails to find non-linear decision boundary and classifies all points to a single class.
library(e1071)
## Warning: package 'e1071' was built under R version 3.6.3
svm_fit = svm(y ~ x1 + x2, df, kernel = "linear", cost = 0.1)
df3<-mutate(df, svm_pred = as_factor(predict(svm_fit, df)))
s<-ggplot(data=df3,mapping=aes(x=x1,y=x2,color=svm_pred))+
geom_point() +
theme_light() +
theme(legend.position = "none")
ggplotly(s)
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.
Comment on your results.
Similar to the non-linear logistic regression model, the non-linear decision boundary on predicted labels closely resembles the true decision boundary.
svm_fit2 = svm(y ~ x1 + x2, df, gamma = 1)
df4<-mutate(df, svm_pred = as_factor(predict(svm_fit2, df)))
t<-ggplot(data=df4,mapping=aes(x=x1,y=x2,color=svm_pred))+
geom_point() +
theme_light() +
theme(legend.position = "none")
ggplotly(t)
library(ISLR)
## Warning: package 'ISLR' was built under R version 3.6.3
data("Auto")
mpg.med = median(Auto$mpg)
bin.var = ifelse(Auto$mpg > mpg.med, 1, 0)
Auto$mpglevel = as.factor(bin.var)
We see that cross-validation error is minimized for cost=1.
set.seed(12345)
tune_out = tune(svm, mpglevel ~ . -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.01
##
## - best performance: 0.08666667
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.08666667 0.02443906
## 2 1e-01 0.09429487 0.03599454
## 3 1e+00 0.08903846 0.03765106
## 4 5e+00 0.10192308 0.04644181
## 5 1e+01 0.10705128 0.05214726
## 6 1e+02 0.12243590 0.04476075
Finally, for radial basis kernel, cost=10 and gamma=0.01. The lowest cross-validation error is obtained for cost=10 and degree=2.
set.seed(21)
tune.out = tune(svm, mpglevel ~ . -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: 0.5435897
##
## - Detailed performance results:
## cost degree error dispersion
## 1 0.1 2 0.5587821 0.04538579
## 2 1.0 2 0.5587821 0.04538579
## 3 5.0 2 0.5587821 0.04538579
## 4 10.0 2 0.5435897 0.05611162
## 5 0.1 3 0.5587821 0.04538579
## 6 1.0 3 0.5587821 0.04538579
## 7 5.0 3 0.5587821 0.04538579
## 8 10.0 3 0.5587821 0.04538579
## 9 0.1 4 0.5587821 0.04538579
## 10 1.0 4 0.5587821 0.04538579
## 11 5.0 4 0.5587821 0.04538579
## 12 10.0 4 0.5587821 0.04538579
svm_poly<-tune_out$best.model
set.seed(463)
tune_out = 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)))
summary(tune_out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 10 0.1
##
## - best performance: 0.08160256
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.1 1e-02 0.11467949 0.03621710
## 2 1.0 1e-02 0.09423077 0.04937793
## 3 5.0 1e-02 0.08653846 0.04145630
## 4 10.0 1e-02 0.08910256 0.03593430
## 5 0.1 1e-01 0.09679487 0.05051148
## 6 1.0 1e-01 0.08910256 0.04158825
## 7 5.0 1e-01 0.08410256 0.03390616
## 8 10.0 1e-01 0.08160256 0.04314552
## 9 0.1 1e+00 0.57660256 0.05479863
## 10 1.0 1e+00 0.09166667 0.04963524
## 11 5.0 1e+00 0.09435897 0.04681077
## 12 10.0 1e+00 0.09685897 0.04780259
## 13 0.1 5e+00 0.57660256 0.05479863
## 14 1.0 5e+00 0.50000000 0.07252377
## 15 5.0 5e+00 0.50012821 0.07730307
## 16 10.0 5e+00 0.50012821 0.07730307
## 17 0.1 1e+01 0.57660256 0.05479863
## 18 1.0 1e+01 0.52814103 0.05853644
## 19 5.0 1e+01 0.53064103 0.05772933
## 20 10.0 1e+01 0.53064103 0.05772933
## 21 0.1 1e+02 0.57660256 0.05479863
## 22 1.0 1e+02 0.57660256 0.05479863
## 23 5.0 1e+02 0.57660256 0.05479863
## 24 10.0 1e+02 0.57660256 0.05479863
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)
library(RColorBrewer)
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)
library(ISLR)
set.seed(9004)
inTrain = sample(nrow(OJ), 800)
train_oj = OJ[inTrain,]
test_oj = OJ[-inTrain,]
Support vector classifier creates 442 support vectors out of 800 training points. Out of these, 222 belong to level CH and remaining 220 belong to level MM
library(e1071)
svm_linear = svm(Purchase ~ ., kernel = "linear", data = train_oj, cost = 0.01)
summary(svm_linear)
##
## 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: 442
##
## ( 222 220 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
The training error rate is 16% and test error rate is about 17.37%.
train_pred = predict(svm_linear, train_oj)
(t<-table(train_oj$Purchase, train_pred))
## train_pred
## CH MM
## CH 432 51
## MM 80 237
(train_error=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.16375
test_pred = predict(svm_linear, test_oj)
(t<-table(test_oj$Purchase, test_pred))
## test_pred
## CH MM
## CH 146 24
## MM 22 78
(test_error=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.1703704
Tuning shows that optimal cost is 3.395258
set.seed(1554)
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
## 3.162278
##
## - best performance: 0.1625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.16750 0.03395258
## 2 0.01778279 0.16875 0.02960973
## 3 0.03162278 0.16625 0.02638523
## 4 0.05623413 0.16875 0.03076005
## 5 0.10000000 0.16875 0.02901748
## 6 0.17782794 0.16750 0.02838231
## 7 0.31622777 0.17000 0.02898755
## 8 0.56234133 0.16875 0.02841288
## 9 1.00000000 0.16500 0.03106892
## 10 1.77827941 0.16500 0.03106892
## 11 3.16227766 0.16250 0.03118048
## 12 5.62341325 0.16375 0.02664713
## 13 10.00000000 0.16750 0.02581989
The training error is the same to 16.32% but test error slightly increases to 17.4% by using best cost.
svm_linear = svm(Purchase ~ ., kernel = "linear", data = train_oj)
train_pred = predict(svm_linear, train_oj)
(t<-table(train_oj$Purchase, train_pred))
## train_pred
## CH MM
## CH 427 56
## MM 75 242
(train_error_linear=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.16375
test_pred = predict(svm_linear, test_oj)
(t<-table(test_oj$Purchase, test_pred))
## test_pred
## CH MM
## CH 143 27
## MM 20 80
(test_error_linear=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.1740741
The radial basis kernel with default gamma creates 371 support vectors, out of which, 188 belong to level CH and remaining 183 belong to level MM. The classifier has a training error of 14% and a test error of 18% which is an improvement over linear kernel. We now use cross validation to find optimal gamma.
set.seed(410)
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: 371
##
## ( 188 183 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_radial, train_oj)
(t<-table(train_oj$Purchase, train_pred))
## train_pred
## CH MM
## CH 441 42
## MM 74 243
(test_error=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.145
test_pred = predict(svm_radial, test_oj)
(t<-table(test_oj$Purchase, test_pred))
## test_pred
## CH MM
## CH 148 22
## MM 27 73
(test_error=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.1814815
set.seed(755)
tune_out = tune(svm, Purchase ~ ., data = train_oj, 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.3162278
##
## - best performance: 0.1675
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39625 0.06615691
## 2 0.01778279 0.39625 0.06615691
## 3 0.03162278 0.35375 0.09754807
## 4 0.05623413 0.20000 0.04249183
## 5 0.10000000 0.17750 0.04073969
## 6 0.17782794 0.17125 0.03120831
## 7 0.31622777 0.16750 0.04216370
## 8 0.56234133 0.16750 0.03782269
## 9 1.00000000 0.17250 0.03670453
## 10 1.77827941 0.17750 0.03374743
## 11 3.16227766 0.18000 0.04005205
## 12 5.62341325 0.18000 0.03446012
## 13 10.00000000 0.18625 0.04427267
svm_radial = svm(Purchase ~ ., kernel = "radial", data = train_oj, cost = tune_out$best.parameters$cost)
train_pred = predict(svm_radial, train_oj)
(t<-table(train_oj$Purchase, train_pred))
## train_pred
## CH MM
## CH 440 43
## MM 81 236
(train_error_radial=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.155
test_pred = predict(svm_radial, test_oj)
(t<-table(test_oj$Purchase, test_pred))
## test_pred
## CH MM
## CH 145 25
## MM 28 72
(test_error_radial=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.1962963
Tuning slightly decreases training error to 15.5% and increases test error to 19.63% which is still not better than linear kernel.
The polynomial kernel produces 456 support vectors, out of which, 232 belong to level CH and remaining 224 belong to level MM. This kernel produces a train error of 18% and a test error of 20.37% which are slightly higher than the errors produces by linear and radial kernel.
svm_poly = svm(Purchase ~ ., kernel = "poly", data = train_oj, degree=2)
summary(svm_poly)
##
## Call:
## svm(formula = Purchase ~ ., data = train_oj, kernel = "poly", degree = 2)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 1
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 456
##
## ( 232 224 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_poly, train_oj)
(t<-table(train_oj$Purchase, train_pred))
## train_pred
## CH MM
## CH 450 33
## MM 111 206
(train_error=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.18
test_pred = predict(svm_poly, test_oj)
(t<-table(test_oj$Purchase, test_pred))
## test_pred
## CH MM
## CH 149 21
## MM 34 66
(test_error=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.2037037
set.seed(322)
tune_out = tune(svm, Purchase ~ ., data = train_oj, kernel = "poly", 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
## 10
##
## - best performance: 0.18
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.39250 0.05749396
## 2 0.01778279 0.37500 0.05863020
## 3 0.03162278 0.36375 0.05756940
## 4 0.05623413 0.33875 0.06626179
## 5 0.10000000 0.30375 0.05172376
## 6 0.17782794 0.24000 0.04440971
## 7 0.31622777 0.21000 0.04362084
## 8 0.56234133 0.20250 0.03987829
## 9 1.00000000 0.20375 0.03634805
## 10 1.77827941 0.19500 0.04866267
## 11 3.16227766 0.18750 0.04409586
## 12 5.62341325 0.18875 0.04185375
## 13 10.00000000 0.18000 0.03593976
svm_poly = svm(Purchase ~ ., kernel = "poly", data = train_oj, degree=2, cost = tune_out$best.parameters$cost)
train_pred = predict(svm_poly, train_oj)
(t<-table(train_oj$Purchase, train_pred))
## train_pred
## CH MM
## CH 447 36
## MM 85 232
(train_error_poly=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.15125
test_pred = predict(svm_poly, test_oj)
(t<-table(test_oj$Purchase, test_pred))
## test_pred
## CH MM
## CH 148 22
## MM 28 72
(test_error_poly=(t[2]+t[3])/(t[1]+t[2]+t[3]+t[4]))
## [1] 0.1851852
Tuning reduces the training error to 15.12% and test error to 18.52% which is about the same as the radial kernel but worse than linear kernel.
df<-tibble(`SVM kernel`=c("Linear","Radial","Polynomial"),
`Training Error`=c(train_error_linear,train_error_radial,train_error_poly),
`Test Error`=c(test_error_linear,test_error_radial,test_error_poly))
df
## # A tibble: 3 x 3
## `SVM kernel` `Training Error` `Test Error`
## <chr> <dbl> <dbl>
## 1 Linear 0.164 0.174
## 2 Radial 0.155 0.196
## 3 Polynomial 0.151 0.185
Overall, the linear basis kernel seems to be producing minimum misclassification error on test data.