library(e1071)
library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.3 v purrr 0.3.4
## v tibble 3.0.5 v dplyr 1.0.3
## v tidyr 1.1.2 v stringr 1.4.0
## v readr 1.4.0 v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(caret)
## Loading required package: lattice
##
## Attaching package: 'caret'
## The following object is masked from 'package:purrr':
##
## lift
(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)
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(x = x1, y = x2, col = (3-y))
data = data.frame(x1, x2, y = as.factor(y))
(c) Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.
set.seed(1)
glm.fit = glm(y ~ ., data = data, family = 'binomial')
glm.fit
##
## Call: glm(formula = y ~ ., family = "binomial", data = data)
##
## Coefficients:
## (Intercept) x1 x2
## -0.08214 -0.26673 -0.46509
##
## Degrees of Freedom: 499 Total (i.e. Null); 497 Residual
## Null Deviance: 692.2
## Residual Deviance: 689.2 AIC: 695.2
(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_pred = predict(glm.fit, newdata = data.frame(x1, x2), type = "response")
predicted_class = 1 * (glm_pred > 0.5)
print(1- sum(predicted_class == y)/length(y))
## [1] 0.54
plot(x1, x2, col = (predicted_class +1), pch = ifelse(as.integer(glm_pred > 0) == y, 1, 4))
(e) Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. \({X^2}_1\) , \(X_1 × X_2\), \(log(X_2)\), and so forth).
glm.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
glm.fit2
##
## Call: glm(formula = y ~ poly(x1, 2) + poly(x2, 2), family = "binomial",
## data = data)
##
## Coefficients:
## (Intercept) poly(x1, 2)1 poly(x1, 2)2 poly(x2, 2)1 poly(x2, 2)2
## -36.49 1691.97 79042.44 3505.79 -78117.97
##
## Degrees of Freedom: 499 Total (i.e. Null); 495 Residual
## Null Deviance: 692.2
## Residual Deviance: 2.032e-05 AIC: 10
(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_pred2 = predict(glm.fit2, data.frame(x1, x2))
plot(x1, x2, col = ifelse(glm_pred2 > 0, 'red', 'blue'), pch = ifelse(as.integer(glm_pred2 > 0) == y, 1, 4))
(g) 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.
svm.fit = svm(y ~ ., data = data, kernel = 'linear')
svm_pred = predict(svm.fit, data.frame(x1, x2), type = 'response')
plot(x1, x2, col = ifelse(svm_pred != 0, 'red', 'blue'), pch = ifelse(svm_pred == y, 1, 4))
(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.
svm.fit2 = svm(y ~ ., data = data, kernel = 'polynomial', degree = 2)
svm_pred2 = predict(svm.fit2, data.frame(x1, x2), type = 'response')
plot(x1, x2, col = ifelse(svm_pred2!= 0, 'red', 'blue'), pch = ifelse(svm_pred2 == y, 1, 4))
(i) Comment on your results.
table(predict=glm_pred2>0, truth=data$y )
## truth
## predict 0 1
## FALSE 261 0
## TRUE 0 239
table(predict=svm_pred2, truth=data$y )
## truth
## predict 0 1
## 0 257 12
## 1 4 227
The logistic regression with non-linear function of x1 and x2 perform better than the SVM with polynomial kernel. On the matrix table, one can see that there ate 18 observations that are misclassified by the SVM.
Auto data set.library(ISLR)
str(Auto)
## 'data.frame': 392 obs. of 9 variables:
## $ mpg : num 18 15 18 16 17 15 14 14 14 15 ...
## $ cylinders : num 8 8 8 8 8 8 8 8 8 8 ...
## $ displacement: num 307 350 318 304 302 429 454 440 455 390 ...
## $ horsepower : num 130 165 150 150 140 198 220 215 225 190 ...
## $ weight : num 3504 3693 3436 3433 3449 ...
## $ acceleration: num 12 11.5 11 12 10.5 10 9 8.5 10 8.5 ...
## $ year : num 70 70 70 70 70 70 70 70 70 70 ...
## $ origin : num 1 1 1 1 1 1 1 1 1 1 ...
## $ name : Factor w/ 304 levels "amc ambassador brougham",..: 49 36 231 14 161 141 54 223 241 2 ...
(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.
Auto$mpg = ifelse(Auto$mpg > median(Auto$mpg), 1, 0)
str(Auto)
## 'data.frame': 392 obs. of 9 variables:
## $ mpg : num 0 0 0 0 0 0 0 0 0 0 ...
## $ cylinders : num 8 8 8 8 8 8 8 8 8 8 ...
## $ displacement: num 307 350 318 304 302 429 454 440 455 390 ...
## $ horsepower : num 130 165 150 150 140 198 220 215 225 190 ...
## $ weight : num 3504 3693 3436 3433 3449 ...
## $ acceleration: num 12 11.5 11 12 10.5 10 9 8.5 10 8.5 ...
## $ year : num 70 70 70 70 70 70 70 70 70 70 ...
## $ origin : num 1 1 1 1 1 1 1 1 1 1 ...
## $ name : Factor w/ 304 levels "amc ambassador brougham",..: 49 36 231 14 161 141 54 223 241 2 ...
(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.seed(1)
svm.tune = tune(svm, mpg ~.,data = Auto, kernel ="linear",ranges=list(cost=c(0.001, 0.01, 0.1, 1,5,10,100)))
svm.tune
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.09603609
svm.tune$performances
## cost error dispersion
## 1 1e-03 0.10881486 0.02537281
## 2 1e-02 0.10421950 0.03138085
## 3 1e-01 0.10227373 0.03634911
## 4 1e+00 0.09603609 0.03666741
## 5 5e+00 0.10034346 0.03612147
## 6 1e+01 0.10531309 0.03683207
## 7 1e+02 0.12079079 0.03864160
plot(svm.tune$performances[, c(1,2)], type = 'l')
svm.tune$best.model
##
## Call:
## best.tune(method = svm, train.x = mpg ~ ., data = Auto, ranges = list(cost = c(0.001,
## 0.01, 0.1, 1, 5, 10, 100)), kernel = "linear")
##
##
## Parameters:
## SVM-Type: eps-regression
## SVM-Kernel: linear
## cost: 1
## gamma: 0.003215434
## epsilon: 0.1
##
##
## Number of Support Vectors: 300
(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(1)
svm.tune2 = tune(svm, mpg ~ ., data = Auto, kernel ="radial",
ranges=list(cost = seq(0.05,100,length.out = 5),gamma = seq(0.1,100,length.out = 5)))
summary(svm.tune2)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 25.0375 0.1
##
## - best performance: 0.07305045
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 0.0500 0.100 0.07692174 0.024179053
## 2 25.0375 0.100 0.07305045 0.031296539
## 3 50.0250 0.100 0.08227226 0.032171808
## 4 75.0125 0.100 0.08584153 0.033042775
## 5 100.0000 0.100 0.08770589 0.033540507
## 6 0.0500 25.075 0.47448833 0.037543271
## 7 25.0375 25.075 0.24919430 0.001237404
## 8 50.0250 25.075 0.24919430 0.001237404
## 9 75.0125 25.075 0.24919430 0.001237404
## 10 100.0000 25.075 0.24919430 0.001237404
## 11 0.0500 50.050 0.47461951 0.037598409
## 12 25.0375 50.050 0.25071334 0.001283792
## 13 50.0250 50.050 0.25071334 0.001283792
## 14 75.0125 50.050 0.25071334 0.001283792
## 15 100.0000 50.050 0.25071334 0.001283792
## 16 0.0500 75.025 0.47464053 0.037602553
## 17 25.0375 75.025 0.25088131 0.001387447
## 18 50.0250 75.025 0.25088131 0.001387447
## 19 75.0125 75.025 0.25088131 0.001387447
## 20 100.0000 75.025 0.25088131 0.001387447
## 21 0.0500 100.000 0.47464323 0.037603313
## 22 25.0375 100.000 0.25090196 0.001404230
## 23 50.0250 100.000 0.25090196 0.001404230
## 24 75.0125 100.000 0.25090196 0.001404230
## 25 100.0000 100.000 0.25090196 0.001404230
svm.tune2$best.model
##
## Call:
## best.tune(method = svm, train.x = mpg ~ ., data = Auto, ranges = list(cost = seq(0.05,
## 100, length.out = 5), gamma = seq(0.1, 100, length.out = 5)),
## kernel = "radial")
##
##
## Parameters:
## SVM-Type: eps-regression
## SVM-Kernel: radial
## cost: 25.0375
## gamma: 0.1
## epsilon: 0.1
##
##
## Number of Support Vectors: 248
(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.
plot(svm.tune$best.model, Auto, cylinders ~ horsepower)
plot(svm.tune2$best.model, Auto, cylinders ~ horsepower)
OJ data set which is part of the ISLR package.library(ISLR)
attach(OJ)
str(OJ)
## 'data.frame': 1070 obs. of 18 variables:
## $ Purchase : Factor w/ 2 levels "CH","MM": 1 1 1 2 1 1 1 1 1 1 ...
## $ WeekofPurchase: num 237 239 245 227 228 230 232 234 235 238 ...
## $ StoreID : num 1 1 1 1 7 7 7 7 7 7 ...
## $ PriceCH : num 1.75 1.75 1.86 1.69 1.69 1.69 1.69 1.75 1.75 1.75 ...
## $ PriceMM : num 1.99 1.99 2.09 1.69 1.69 1.99 1.99 1.99 1.99 1.99 ...
## $ DiscCH : num 0 0 0.17 0 0 0 0 0 0 0 ...
## $ DiscMM : num 0 0.3 0 0 0 0 0.4 0.4 0.4 0.4 ...
## $ SpecialCH : num 0 0 0 0 0 0 1 1 0 0 ...
## $ SpecialMM : num 0 1 0 0 0 1 1 0 0 0 ...
## $ LoyalCH : num 0.5 0.6 0.68 0.4 0.957 ...
## $ SalePriceMM : num 1.99 1.69 2.09 1.69 1.69 1.99 1.59 1.59 1.59 1.59 ...
## $ SalePriceCH : num 1.75 1.75 1.69 1.69 1.69 1.69 1.69 1.75 1.75 1.75 ...
## $ PriceDiff : num 0.24 -0.06 0.4 0 0 0.3 -0.1 -0.16 -0.16 -0.16 ...
## $ Store7 : Factor w/ 2 levels "No","Yes": 1 1 1 1 2 2 2 2 2 2 ...
## $ PctDiscMM : num 0 0.151 0 0 0 ...
## $ PctDiscCH : num 0 0 0.0914 0 0 ...
## $ ListPriceDiff : num 0.24 0.24 0.23 0 0 0.3 0.3 0.24 0.24 0.24 ...
## $ STORE : num 1 1 1 1 0 0 0 0 0 0 ...
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(1)
index_train = sample(1:nrow(OJ), 800)
OJ_train = OJ[index_train,]
OJ_test = OJ[-index_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.
OJ_svm = svm(Purchase ~ ., data = OJ_train, kernel = "linear", cost = 0.01)
summary(OJ_svm)
##
## 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
The support vector machine used 435 observations as support vectors. The support vectors are split by CH = 219 and MM = 216
(c) What are the training and test error rates?
svm_pred_train = predict(OJ_svm, OJ_train)
table(OJ_train$Purchase, svm_pred_train)
## svm_pred_train
## CH MM
## CH 420 65
## MM 75 240
mean(svm_pred_train != OJ_train$Purchase)
## [1] 0.175
svm_pred_test = predict(OJ_svm, OJ_test)
table(OJ_test$Purchase, svm_pred_test)
## svm_pred_test
## CH MM
## CH 153 15
## MM 33 69
mean(svm_pred_test != OJ_test$Purchase)
## [1] 0.1777778
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
OJ_svm_tune = tune(svm, Purchase ~ ., data = OJ_train, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(OJ_svm_tune)
##
## 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.01 0.17375 0.03884174
## 2 0.10 0.17875 0.03064696
## 3 1.00 0.17500 0.03061862
## 4 5.00 0.17250 0.03322900
## 5 10.00 0.17125 0.03488573
(e) Compute the training and test error rates using this new value for cost.
OJ_svm_tune_pred_train = predict(OJ_svm_tune$best.model, OJ_train)
table(OJ_train$Purchase, OJ_svm_tune_pred_train)
## OJ_svm_tune_pred_train
## CH MM
## CH 423 62
## MM 69 246
mean(OJ_svm_tune_pred_train != OJ_train$Purchase)
## [1] 0.16375
OJ_svm_tune_pred_test = predict(OJ_svm_tune$best.model, OJ_test)
table(OJ_test$Purchase, OJ_svm_tune_pred_test)
## OJ_svm_tune_pred_test
## CH MM
## CH 156 12
## MM 28 74
mean(OJ_svm_tune_pred_test != OJ_test$Purchase)
## [1] 0.1481481
(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
OJ_svm_radial = svm(Purchase ~ ., data = OJ_train, kernel = "radial", cost = 0.01)
summary(OJ_svm_radial)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ_train, kernel = "radial", cost = 0.01)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 0.01
##
## Number of Support Vectors: 634
##
## ( 319 315 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
svm_radial_pred_train = predict(OJ_svm_radial, OJ_train)
table(OJ_train$Purchase, svm_radial_pred_train)
## svm_radial_pred_train
## CH MM
## CH 485 0
## MM 315 0
mean(svm_radial_pred_train != OJ_train$Purchase)
## [1] 0.39375
svm_radial_pred_test = predict(OJ_svm_radial, OJ_test)
table(OJ_test$Purchase, svm_radial_pred_test)
## svm_radial_pred_test
## CH MM
## CH 168 0
## MM 102 0
mean(svm_radial_pred_test != OJ_test$Purchase)
## [1] 0.3777778
OJ_svm_radial_tune = tune(svm, Purchase ~ ., data = OJ_train, kernel = "radial", ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(OJ_svm_radial_tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 1
##
## - best performance: 0.17625
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39375 0.06568284
## 2 0.10 0.18250 0.05470883
## 3 1.00 0.17625 0.03793727
## 4 5.00 0.18125 0.04299952
## 5 10.00 0.18125 0.04340139
OJ_svm_radial_tune_pred_train = predict(OJ_svm_radial_tune$best.model, OJ_train)
table(OJ_train$Purchase, OJ_svm_radial_tune_pred_train)
## OJ_svm_radial_tune_pred_train
## CH MM
## CH 441 44
## MM 77 238
mean(OJ_svm_radial_tune_pred_train != OJ_train$Purchase)
## [1] 0.15125
OJ_svm_radial_tune_pred_test = predict(OJ_svm_radial_tune$best.model, OJ_test)
table(OJ_test$Purchase, OJ_svm_radial_tune_pred_test)
## OJ_svm_radial_tune_pred_test
## CH MM
## CH 151 17
## MM 33 69
mean(OJ_svm_radial_tune_pred_test != OJ_test$Purchase)
## [1] 0.1851852
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
OJ_svm_poly = svm(Purchase ~ ., data = OJ_train, kernel = "polynomial", degree = 2, cost = 0.01)
summary(OJ_svm_poly)
##
## Call:
## svm(formula = Purchase ~ ., data = OJ_train, kernel = "polynomial",
## degree = 2, cost = 0.01)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: polynomial
## cost: 0.01
## degree: 2
## coef.0: 0
##
## Number of Support Vectors: 636
##
## ( 321 315 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
svm_poly_pred_train = predict(OJ_svm_poly, OJ_train)
table(OJ_train$Purchase, svm_poly_pred_train)
## svm_poly_pred_train
## CH MM
## CH 484 1
## MM 297 18
mean(svm_poly_pred_train != OJ_train$Purchase)
## [1] 0.3725
svm_poly_pred_test = predict(OJ_svm_poly, OJ_test)
table(OJ_test$Purchase, svm_poly_pred_test)
## svm_poly_pred_test
## CH MM
## CH 167 1
## MM 98 4
mean(svm_poly_pred_test != OJ_test$Purchase)
## [1] 0.3666667
OJ_svm_poly_tune = tune(svm, Purchase ~ ., data = OJ_train, kernel = "polynomial", degree = 2, ranges = list(cost = c(0.01, 0.1, 1, 5, 10)))
summary(OJ_svm_poly_tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 5
##
## - best performance: 0.18375
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01 0.39000 0.08287373
## 2 0.10 0.32375 0.06730166
## 3 1.00 0.20000 0.05137012
## 4 5.00 0.18375 0.05104804
## 5 10.00 0.18625 0.05185785
OJ_svm_poly_tune_pred_train = predict(OJ_svm_poly_tune$best.model, OJ_train)
table(OJ_train$Purchase, OJ_svm_poly_tune_pred_train)
## OJ_svm_poly_tune_pred_train
## CH MM
## CH 447 38
## MM 86 229
mean(OJ_svm_poly_tune_pred_train != OJ_train$Purchase)
## [1] 0.155
OJ_svm_poly_tune_pred_test = predict(OJ_svm_poly_tune$best.model, OJ_test)
table(OJ_test$Purchase, OJ_svm_poly_tune_pred_test)
## OJ_svm_poly_tune_pred_test
## CH MM
## CH 155 13
## MM 36 66
mean(OJ_svm_poly_tune_pred_test != OJ_test$Purchase)
## [1] 0.1814815
(h) Overall, which approach seems to give the best results on this data?
res_lineal = cbind( 'train' = mean(svm_pred_train != OJ_train$Purchase), 'test' = mean(svm_pred_test != OJ_test$Purchase), 'CV' = OJ_svm_tune$best.performance, 'train.tuned' = mean(OJ_svm_tune_pred_train != OJ_train$Purchase), 'test.tuned' = mean(OJ_svm_tune_pred_test != OJ_test$Purchase))
res_radial = cbind('train' = mean(svm_radial_pred_train != OJ_train$Purchase), 'test' = mean(svm_radial_pred_test != OJ_test$Purchase), 'CV' = OJ_svm_radial_tune$best.performance, 'train.tuned' = mean(OJ_svm_radial_tune_pred_train != OJ_train$Purchase), 'test.tuned' = mean(OJ_svm_radial_tune_pred_test != OJ_test$Purchase))
res_polynomial = cbind('train' = mean(svm_poly_pred_train != OJ_train$Purchase), 'test' = mean(svm_poly_pred_test != OJ_test$Purchase), 'CV' = OJ_svm_poly_tune$best.performance, 'train.tuned' = mean(OJ_svm_poly_tune_pred_train != OJ_train$Purchase), 'test.tuned' = mean(OJ_svm_poly_tune_pred_test != OJ_test$Purchase))
table1 = rbind(res_lineal, res_radial, res_polynomial )
rownames(table1) = c('LINEAR','RADIAL','POLYNOMIAL')
table1
## train test CV train.tuned test.tuned
## LINEAR 0.17500 0.1777778 0.17125 0.16375 0.1481481
## RADIAL 0.39375 0.3777778 0.17625 0.15125 0.1851852
## POLYNOMIAL 0.37250 0.3666667 0.18375 0.15500 0.1814815
The linear `SVM performs better on this data.