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. For instance, you can do this as follows:
set.seed(2)
x1 <- runif(500)-0.50
x2 <- runif(500)-0.50
y <- as.factor(1*(x1^2-x2^2 > 0))
df_qrd <- data.frame(x1=x1, x2=x2, y=y)
df_qrd %>% head()
## x1 x2 y
## 1 -0.31511774 0.19200555 1
## 2 0.20237404 0.05995692 1
## 3 0.07332633 -0.15730879 0
## 4 -0.33194808 -0.26550250 1
## 5 0.44383934 -0.07039724 1
## 6 0.44347496 0.23670066 1
(b) Plot the observations, colored according to their class labels. Your plot should display X1 on the x-axis, and X2 on the yaxis.
df_qrd %>% ggplot(aes(x=x1,y=x2,col=y))+
geom_point() +
theme(legend.position = "none")
(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
lr_fit = glm(y~x1+x2, data=df_qrd, family = 'binomial')
summary(lr_fit)
##
## Call:
## glm(formula = y ~ x1 + x2, family = "binomial", data = df_qrd)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.271 -1.193 1.097 1.147 1.209
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.07138 0.08959 0.797 0.426
## x1 -0.03532 0.29825 -0.118 0.906
## x2 0.27548 0.30762 0.896 0.370
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 692.50 on 499 degrees of freedom
## Residual deviance: 691.67 on 497 degrees of freedom
## AIC: 697.67
##
## Number of Fisher Scoring iterations: 3
A) With \(\alpha = 0.05\),neither \(x1\) nor \(x2\) are significant.
(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.
# Predictions
lr_probs = predict(lr_fit, newdata=df_qrd, type = 'response')
lr_preds = rep(0,500)
lr_preds[lr_probs>0.50] = 1
df_lr <- cbind(df_qrd,lr_preds)
df_lr %>% ggplot(aes(x=x1,y=x2,col=lr_preds))+
geom_point() +
theme(legend.position = "none")
table(df_lr$y,df_lr$lr_preds)
##
## 0 1
## 0 96 145
## 1 24 235
Decision boundary looks linear and the misclassification rate is 33.8%
(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X21 , X1×X2, log(X2), and so forth).
lr_fit_poly = glm(y~I(x1^2)+I(x2^2), data=df_qrd, family = 'binomial')
summary(lr_fit_poly)
##
## Call:
## glm(formula = y ~ I(x1^2) + I(x2^2), family = "binomial", data = df_qrd)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -0.004698 0.000000 0.000000 0.000000 0.004649
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -2.547 154.280 -0.017 0.987
## I(x1^2) 78240.759 828909.472 0.094 0.925
## I(x2^2) -78173.118 828242.299 -0.094 0.925
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9250e+02 on 499 degrees of freedom
## Residual deviance: 4.9846e-05 on 497 degrees of freedom
## AIC: 6
##
## Number of Fisher Scoring iterations: 25
(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.
# Predictions
lr_prob_p = predict(lr_fit_poly, newdata=df_qrd, type = 'response')
lr_preds_p = rep(0,500)
lr_preds_p[lr_prob_p>0.50] = 1
df_lr_p <- cbind(df_qrd,lr_preds_p)
df_lr_p %>% ggplot(aes(x=x1,y=x2,col=lr_preds_p))+
geom_point() +
theme(legend.position = "none")
table(df_lr_p$y,df_lr_p$lr_preds_p)
##
## 0 1
## 0 241 0
## 1 0 259
A) Decision boundary is exactly the true decision boundary as the formual used is same as the way data was generated and with this the misclassification rate is zero.
(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.
# Set up Repeated k-fold Cross Validation
train_control <- trainControl(method="repeatedcv", number=10, repeats=3)
svm_linear <- train(y ~., data = df_qrd, method = "svmLinear", trControl = train_control, preProcess = c("center","scale"),
tuneGrid = expand.grid(C = seq(0, 2, length = 20)))
#View the model
svm_linear
## Support Vector Machines with Linear Kernel
##
## 500 samples
## 2 predictor
## 2 classes: '0', '1'
##
## Pre-processing: centered (2), scaled (2)
## Resampling: Cross-Validated (10 fold, repeated 3 times)
## Summary of sample sizes: 450, 451, 450, 450, 450, 450, ...
## Resampling results across tuning parameters:
##
## C Accuracy Kappa
## 0.0000000 NaN NaN
## 0.1052632 0.5153341 -0.0008457076
## 0.2105263 0.5206675 0.0119368428
## 0.3157895 0.5220008 0.0151966487
## 0.4210526 0.5206675 0.0126705006
## 0.5263158 0.5206675 0.0126705006
## 0.6315789 0.5206675 0.0126705006
## 0.7368421 0.5206675 0.0126705006
## 0.8421053 0.5206675 0.0126705006
## 0.9473684 0.5213341 0.0139767976
## 1.0526316 0.5213341 0.0139767976
## 1.1578947 0.5220008 0.0152707732
## 1.2631579 0.5240008 0.0197737935
## 1.3684211 0.5240008 0.0198684743
## 1.4736842 0.5253341 0.0227748515
## 1.5789474 0.5246675 0.0214685545
## 1.6842105 0.5246675 0.0214596983
## 1.7894737 0.5240008 0.0202410595
## 1.8947368 0.5246675 0.0216353902
## 2.0000000 0.5240008 0.0203327010
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was C = 1.473684.
df_svm_l <- cbind(df_qrd,svm_l_p=as.factor(predict(svm_linear, df_qrd)))
df_svm_l %>% ggplot(aes(x=x1,y=x2,col=svm_l_p))+
geom_point() +
theme(legend.position = "none")
table(df_svm_l$y,df_svm_l$svm_l_p)
##
## 0 1
## 0 0 241
## 1 0 259
A)SVM with a linear kernel,fails to find non-linear decision boundary and classifies all points to a single class. We can see this in the confusion matrix and plot.
(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.
# Set up Repeated k-fold Cross Validation
train_control <- trainControl(method="repeatedcv", number=5, repeats=3)
svm_nlinear <- train(y ~., data = df_qrd, method = "svmPoly", trControl = train_control,preProcess = c("center","scale"),
tuneLength = 3)
#View the model
svm_nlinear
## Support Vector Machines with Polynomial Kernel
##
## 500 samples
## 2 predictor
## 2 classes: '0', '1'
##
## Pre-processing: centered (2), scaled (2)
## Resampling: Cross-Validated (5 fold, repeated 3 times)
## Summary of sample sizes: 399, 401, 400, 400, 400, 400, ...
## Resampling results across tuning parameters:
##
## degree scale C Accuracy Kappa
## 1 0.001 0.25 0.5180004 0.000000000
## 1 0.001 0.50 0.5180004 0.000000000
## 1 0.001 1.00 0.5180004 0.000000000
## 1 0.010 0.25 0.5180004 0.000000000
## 1 0.010 0.50 0.5180004 0.000000000
## 1 0.010 1.00 0.5180004 0.000000000
## 1 0.100 0.25 0.5031856 -0.028395062
## 1 0.100 0.50 0.5138725 -0.003821128
## 1 0.100 1.00 0.5085327 -0.012077898
## 2 0.001 0.25 0.5180004 0.000000000
## 2 0.001 0.50 0.5180004 0.000000000
## 2 0.001 1.00 0.5180004 0.000000000
## 2 0.010 0.25 0.5180004 0.000000000
## 2 0.010 0.50 0.5180004 0.000000000
## 2 0.010 1.00 0.5099196 -0.015936587
## 2 0.100 0.25 0.8346621 0.665304799
## 2 0.100 0.50 0.8779771 0.753735311
## 2 0.100 1.00 0.9179979 0.834926463
## 3 0.001 0.25 0.5180004 0.000000000
## 3 0.001 0.50 0.5180004 0.000000000
## 3 0.001 1.00 0.5180004 0.000000000
## 3 0.010 0.25 0.5180004 0.000000000
## 3 0.010 0.50 0.5173270 -0.001345952
## 3 0.010 1.00 0.5045122 -0.024545975
## 3 0.100 0.25 0.9066577 0.811955350
## 3 0.100 0.50 0.9233047 0.845619566
## 3 0.100 1.00 0.9313250 0.861799887
##
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were degree = 3, scale = 0.1 and C = 1.
df_svm_nl <- cbind(df_qrd,svm_nl_p=as.factor(predict(svm_nlinear, df_qrd)))
df_svm_nl %>% ggplot(aes(x=x1,y=x2,col=svm_nl_p))+
geom_point() +
theme(legend.position = "none")
table(df_svm_nl$y,df_svm_nl$svm_nl_p)
##
## 0 1
## 0 210 31
## 1 4 255
(i) Comment on your results.
Linear non-linear logistic regression, SVM with non-linear kernel comes close to the true non-linear decision boundary with 92.9% accuracy. SVM linear fails completely on a this data with non-linear boundary.Logistic regression with linear terms performed better than SVM wth linear kernel.
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.
myauto <- Auto %>%
mutate(mpg01 = as_factor(ifelse(mpg > median(mpg), 1, 0)))
myauto %>% tail()
## mpg cylinders displacement horsepower weight acceleration year origin
## 387 27 4 151 90 2950 17.3 82 1
## 388 27 4 140 86 2790 15.6 82 1
## 389 44 4 97 52 2130 24.6 82 2
## 390 32 4 135 84 2295 11.6 82 1
## 391 28 4 120 79 2625 18.6 82 1
## 392 31 4 119 82 2720 19.4 82 1
## name mpg01
## 387 chevrolet camaro 1
## 388 ford mustang gl 1
## 389 vw pickup 1
## 390 dodge rampage 1
## 391 ford ranger 1
## 392 chevy s-10 1
(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 up Repeated k-fold Cross Validation
train_control <- trainControl(method="repeatedcv", number=10, repeats=3)
svm_lauto <- train(mpg01 ~.-mpg, data = myauto, method = "svmLinear", trControl = train_control, preProcess = c("center","scale"),
tuneGrid = expand.grid(C = c(0.01, 0.1, 1,2, 5, 10, 100)))
#View the model
svm_lauto
## Support Vector Machines with Linear Kernel
##
## 392 samples
## 9 predictor
## 2 classes: '0', '1'
##
## Pre-processing: centered (310), scaled (310)
## Resampling: Cross-Validated (10 fold, repeated 3 times)
## Summary of sample sizes: 352, 352, 353, 354, 352, 353, ...
## Resampling results across tuning parameters:
##
## C Accuracy Kappa
## 1e-02 0.8961853 0.7923214
## 1e-01 0.8962303 0.7924272
## 1e+00 0.8887067 0.7773901
## 2e+00 0.8802002 0.7603725
## 5e+00 0.8689755 0.7379434
## 1e+01 0.8766925 0.7533326
## 1e+02 0.8732254 0.7464162
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was C = 0.1.
svm_lauto$results %>% mutate(Error = 1-svm_lauto$results$Accuracy ) %>% head()
## C Accuracy Kappa AccuracySD KappaSD Error
## 1 0.01 0.8961853 0.7923214 0.03609441 0.07225113 0.1038147
## 2 0.10 0.8962303 0.7924272 0.03592639 0.07191767 0.1037697
## 3 1.00 0.8887067 0.7773901 0.04587175 0.09175484 0.1112933
## 4 2.00 0.8802002 0.7603725 0.05232108 0.10460893 0.1197998
## 5 5.00 0.8689755 0.7379434 0.05390249 0.10778324 0.1310245
## 6 10.00 0.8766925 0.7533326 0.05293693 0.10587357 0.1233075
set.seed(123)
tune_out = tune(svm, mpg01 ~ . -mpg, data = myauto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1,2, 5, 10, 100)))
summary(tune_out)
##
## 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 2e+00 0.10423077 0.06075234
## 5 5e+00 0.10423077 0.06425850
## 6 1e+01 0.10673077 0.06562804
## 7 1e+02 0.12724359 0.06371052
A) I have tried using caret and e1071 packages, lowest error is at cost = 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(123)
tune_out = tune(svm, mpg01 ~ . -mpg, data = myauto, kernel = "polynomial",
ranges = list(cost = c(0.01, 0.1, 1,2, 5, 10, 100),degree = c(2, 3, 4)))
summary(tune_out)
##
## 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 2e+00 2 0.5817308 0.04740051
## 5 5e+00 2 0.5817308 0.04740051
## 6 1e+01 2 0.5714744 0.04575370
## 7 1e+02 2 0.3086538 0.10382736
## 8 1e-02 3 0.5817308 0.04740051
## 9 1e-01 3 0.5817308 0.04740051
## 10 1e+00 3 0.5817308 0.04740051
## 11 2e+00 3 0.5817308 0.04740051
## 12 5e+00 3 0.5817308 0.04740051
## 13 1e+01 3 0.5817308 0.04740051
## 14 1e+02 3 0.4159615 0.12008716
## 15 1e-02 4 0.5817308 0.04740051
## 16 1e-01 4 0.5817308 0.04740051
## 17 1e+00 4 0.5817308 0.04740051
## 18 2e+00 4 0.5817308 0.04740051
## 19 5e+00 4 0.5817308 0.04740051
## 20 1e+01 4 0.5817308 0.04740051
## 21 1e+02 4 0.5817308 0.04740051
set.seed(123)
tune_out = tune(svm, mpg01 ~ . -mpg, data = myauto, kernel = "radial",
ranges = list(cost = c(0.01, 0.1, 1,2, 5, 10, 100),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
## 5 0.1
##
## - best performance: 0.07365385
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-02 1e-02 0.58173077 0.04740051
## 2 1e-01 1e-02 0.11211538 0.05486624
## 3 1e+00 1e-02 0.08910256 0.03791275
## 4 2e+00 1e-02 0.08653846 0.03578151
## 5 5e+00 1e-02 0.08397436 0.03933133
## 6 1e+01 1e-02 0.09403846 0.04842472
## 7 1e+02 1e-02 0.09147436 0.05690990
## 8 1e-02 1e-01 0.26000000 0.09153493
## 9 1e-01 1e-01 0.08910256 0.03979296
## 10 1e+00 1e-01 0.08653846 0.03578151
## 11 2e+00 1e-01 0.08141026 0.04410310
## 12 5e+00 1e-01 0.07365385 0.05975763
## 13 1e+01 1e-01 0.07365385 0.05852240
## 14 1e+02 1e-01 0.10442308 0.05095556
## 15 1e-02 1e+00 0.58173077 0.04740051
## 16 1e-01 1e+00 0.58173077 0.04740051
## 17 1e+00 1e+00 0.08660256 0.04466420
## 18 2e+00 1e+00 0.09173077 0.05459763
## 19 5e+00 1e+00 0.08916667 0.05328055
## 20 1e+01 1e+00 0.08916667 0.05328055
## 21 1e+02 1e+00 0.08916667 0.05328055
## 22 1e-02 5e+00 0.58173077 0.04740051
## 23 1e-01 5e+00 0.58173077 0.04740051
## 24 1e+00 5e+00 0.51532051 0.06910961
## 25 2e+00 5e+00 0.50769231 0.06675495
## 26 5e+00 5e+00 0.50769231 0.06675495
## 27 1e+01 5e+00 0.50769231 0.06675495
## 28 1e+02 5e+00 0.50769231 0.06675495
## 29 1e-02 1e+01 0.58173077 0.04740051
## 30 1e-01 1e+01 0.58173077 0.04740051
## 31 1e+00 1e+01 0.53583333 0.07213142
## 32 2e+00 1e+01 0.53333333 0.07201901
## 33 5e+00 1e+01 0.53333333 0.07201901
## 34 1e+01 1e+01 0.53333333 0.07201901
## 35 1e+02 1e+01 0.53333333 0.07201901
## 36 1e-02 1e+02 0.58173077 0.04740051
## 37 1e-01 1e+02 0.58173077 0.04740051
## 38 1e+00 1e+02 0.58173077 0.04740051
## 39 2e+00 1e+02 0.58173077 0.04740051
## 40 5e+00 1e+02 0.58173077 0.04740051
## 41 1e+01 1e+02 0.58173077 0.04740051
## 42 1e+02 1e+02 0.58173077 0.04740051
The lowest cross-validation error is obtained for polynomial kernel is at cost=100 and degree=2.
The lowest cross-validation error is obtained for radial kernel is at cost=5 and gamma=0.1.
(d) Make some plots to back up your assertions in (b) and (c).
svm_linear = svm(mpg01 ~ ., data = myauto, kernel = "linear", cost = 0.01)
svm_poly = svm(mpg01 ~ ., data = myauto, kernel = "polynomial", cost = 100,degree = 2)
svm_radial = svm(mpg01 ~ ., data = myauto, kernel = "radial", cost = 5, gamma = 0.1)
plotautopairs<-function(fit){
for(name in names(myauto)[!(names(myauto)) %in% c("mpg","name","mpg01")]){
plot(fit,myauto,as.formula(paste("mpg~",name,sep="")))
}
}
plotautopairs(svm_linear)
plotautopairs(svm_poly)
plotautopairs(svm_radial)
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(123)
ind <- sample(nrow(OJ), 800)
train_oj<- OJ[ind, ]
test_oj <- OJ[-ind, ]
(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_oj = svm(Purchase ~ ., kernel = "linear", data = train_oj, cost = 0.01)
summary(svm_linear_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: 442
##
## ( 220 222 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
A)The support vector classifier svm using the training data and with cost 0.01 created 442 support vectors with 2 classes, that’s CH level with 222 support vectors and MM level with 220 support vectors.
(c) What are the training and test error rates?
train_pred = predict(svm_linear_oj, train_oj)
df <- table(train_oj$Purchase, train_pred)
train_error_linear=(df[2]+df[3])/(dim(train_oj)[1])
test_pred = predict(svm_linear_oj, test_oj)
df <- table(test_oj$Purchase, test_pred)
test_error_linear=(df[2]+df[3])/(dim(test_oj)[1])
A) $ Linear SVM Train error $ 0.165
$ Linear SVM Test error $ 0.1777778
(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 = c(0.01, 0.1, 1,2,3,3.5,4,4.5, 5, 10)))
summary(tune_out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 3.5
##
## - best performance: 0.165
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.17625 0.03143004
## 2 0.10 0.17250 0.03425801
## 3 1.00 0.16875 0.03596391
## 4 2.00 0.16625 0.03634805
## 5 3.00 0.16625 0.03007514
## 6 3.50 0.16500 0.02934469
## 7 4.00 0.16625 0.03007514
## 8 4.50 0.16750 0.02898755
## 9 5.00 0.16625 0.03007514
## 10 10.00 0.17250 0.02751262
A) Tuning linear SVM for the best cost results in cost = 4.5, with lowest CV error.
(e) Compute the training and test error rates using this new value for cost.
svm_linear_oj = svm(Purchase ~ ., kernel = "linear", data = train_oj, cost = 4.5)
summary(svm_linear_oj)
##
## Call:
## svm(formula = Purchase ~ ., data = train_oj, kernel = "linear", cost = 4.5)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: linear
## cost: 4.5
##
## Number of Support Vectors: 336
##
## ( 167 169 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_linear_oj, train_oj)
df <- table(train_oj$Purchase, train_pred)
train_error_linear=(df[2]+df[3])/(dim(train_oj)[1])
test_pred = predict(svm_linear_oj, test_oj)
df <- table(test_oj$Purchase, test_pred)
test_error_linear=(df[2]+df[3])/(dim(test_oj)[1])
A) $ Linear SVM Train error after cost tuning $ 0.16125
$ Linear SVM Test error after cost tuning $ 0.162963
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
svm_radial_oj = svm(Purchase ~ ., kernel = "radial", data = train_oj)
summary(svm_radial_oj)
##
## Call:
## svm(formula = Purchase ~ ., data = train_oj, kernel = "radial")
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 367
##
## ( 181 186 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_radial_oj, train_oj)
df <- table(train_oj$Purchase, train_pred)
train_error_radial=(df[2]+df[3])/(dim(train_oj)[1])
test_pred = predict(svm_linear_oj, test_oj)
df <- table(test_oj$Purchase, test_pred)
test_error_radial=(df[2]+df[3])/(dim(test_oj)[1])
The SVM with radial kernel with default gamma and cost model creates 371 support vectors, with 188 support vectors for the level CH and remaining 183 support vectors for the level MM.
tune_out = tune(svm, Purchase ~ ., data = train_oj, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1,2,3,3.5,4,4.5, 5, 10)))
summary(tune_out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.1625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39125 0.04411554
## 2 0.10 0.18125 0.03691676
## 3 1.00 0.16250 0.03486083
## 4 2.00 0.16375 0.02913689
## 5 3.00 0.16500 0.03322900
## 6 3.50 0.16875 0.03346329
## 7 4.00 0.16875 0.03346329
## 8 4.50 0.16750 0.03184162
## 9 5.00 0.16625 0.03175973
## 10 10.00 0.16500 0.03622844
svm_radial_oj = svm(Purchase ~ ., kernel = "radial", data = train_oj, cost = 0.1)
summary(svm_radial_oj)
##
## Call:
## svm(formula = Purchase ~ ., data = train_oj, kernel = "radial", cost = 0.1)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 0.1
##
## Number of Support Vectors: 550
##
## ( 273 277 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_radial_oj, train_oj)
df <- table(train_oj$Purchase, train_pred)
train_error_radial=(df[2]+df[3])/(dim(train_oj)[1])
test_pred = predict(svm_radial_oj, test_oj)
df <- table(test_oj$Purchase, test_pred)
test_error_radial=(df[2]+df[3])/(dim(test_oj)[1])
A) Tuning radial SVM for the best cost results in cost = 0.1, with lowest CV error. $ Radial SVM Train error after cost tuning $ 0.16
$ Radial SVM Test error after cost tuning $ 0.1962963
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
svm_poly_oj = svm(Purchase ~ ., kernel = "poly", data = train_oj,degree=2)
summary(svm_poly_oj)
##
## 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: 445
##
## ( 219 226 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_poly_oj, train_oj)
df <- table(train_oj$Purchase, train_pred)
train_error_poly=(df[2]+df[3])/(dim(train_oj)[1])
test_pred = predict(svm_poly_oj, test_oj)
df <- table(test_oj$Purchase, test_pred)
test_error_poly=(df[2]+df[3])/(dim(test_oj)[1])
A)``The SVM withpolykernel withdegree =2and defaultcost` model creates 456 support vectors, with 232 support vectors for the level CH and remaining 224 support vectors for the level MM.
tune_out = tune(svm, Purchase ~ ., data = train_oj, kernel = "poly",degree=2, ranges = list(cost = c(0.01, 0.1, 1,2,3,3.5,4,4.5, 5, 10)))
summary(tune_out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 3.5
##
## - best performance: 0.17
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.38750 0.04289846
## 2 0.10 0.30875 0.01772671
## 3 1.00 0.18375 0.03335936
## 4 2.00 0.17625 0.04059026
## 5 3.00 0.17375 0.03653860
## 6 3.50 0.17000 0.03827895
## 7 4.00 0.17250 0.03899786
## 8 4.50 0.17125 0.04126894
## 9 5.00 0.17000 0.04090979
## 10 10.00 0.17125 0.03729108
svm_poly_oj = svm(Purchase ~ ., kernel = "poly", data = train_oj, degree=2,cost = 10)
summary(svm_radial_oj)
##
## Call:
## svm(formula = Purchase ~ ., data = train_oj, kernel = "radial", cost = 0.1)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 0.1
##
## Number of Support Vectors: 550
##
## ( 273 277 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
train_pred = predict(svm_poly_oj, train_oj)
df <- table(train_oj$Purchase, train_pred)
train_error_poly=(df[2]+df[3])/(dim(train_oj)[1])
test_pred = predict(svm_poly_oj, test_oj)
df <- table(test_oj$Purchase, test_pred)
test_error_poly=(df[2]+df[3])/(dim(test_oj)[1])
A) Tuning poly SVM for the best cost results in cost = 10, with lowest CV error.
$ Poly SVM Train error after cost tuning $ 0.14375
$ Poly SVM Test error after cost tuning $ 0.2037037
(h) Overall, which approach seems to give the best results on this data?
# Train Err analysis
df_tr_error <- data.frame(model=c("Linear","Radial","Polynomial"),
Err = c(train_error_linear,train_error_radial,train_error_poly))
hc <- df_tr_error %>%
hchart('column', hcaes(x = model, y = Err))
hc %>%
hc_add_theme(hc_theme_economist()) %>%
hc_title(text = "Train Classification Error across various models SVM Kernels")
df_ts_error <- data.frame(model=c("Linear","Radial","Polynomial"),
Err = c(test_error_linear,test_error_radial,test_error_poly))
hc <- df_ts_error %>%
hchart('column', hcaes(x = model, y = Err))
hc %>%
hc_add_theme(hc_theme_economist()) %>%
hc_title(text = "Test Classification Error across various models SVM Kernels")
A) Comparing the training error rates across three kernels show that the Polynomial kernel has an better error rate but when we look at the test error rate Linear kernel outperforms the other non-linear SVM kernel models.