library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.1     ✔ purrr   1.0.1
## ✔ tibble  3.1.8     ✔ dplyr   1.1.0
## ✔ tidyr   1.3.0     ✔ stringr 1.5.0
## ✔ readr   2.1.4     ✔ forcats 1.0.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(ISLR2)
library(glmnet)
## Warning: package 'glmnet' was built under R version 4.2.3
## Loading required package: Matrix
## 
## Attaching package: 'Matrix'
## 
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
## 
## Loaded glmnet 4.1-7
library(pls)
## Warning: package 'pls' was built under R version 4.2.3
## 
## Attaching package: 'pls'
## 
## The following object is masked from 'package:stats':
## 
##     loadings
library(dplyr)
library(caret)
## Warning: package 'caret' was built under R version 4.2.3
## Loading required package: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:pls':
## 
##     R2
## 
## The following object is masked from 'package:purrr':
## 
##     lift
library(leaps)
## Warning: package 'leaps' was built under R version 4.2.3
library(boot)
## 
## Attaching package: 'boot'
## 
## The following object is masked from 'package:lattice':
## 
##     melanoma
library(gam)
## Warning: package 'gam' was built under R version 4.2.3
## Loading required package: splines
## Loading required package: foreach
## 
## Attaching package: 'foreach'
## 
## The following objects are masked from 'package:purrr':
## 
##     accumulate, when
## 
## Loaded gam 1.22-2
library(leaps)
library(tree)
## Warning: package 'tree' was built under R version 4.2.3
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.2.3
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
## 
## The following object is masked from 'package:ggplot2':
## 
##     margin
library(BART)
## Warning: package 'BART' was built under R version 4.2.3
## Loading required package: nlme
## 
## Attaching package: 'nlme'
## 
## The following object is masked from 'package:dplyr':
## 
##     collapse
## 
## Loading required package: nnet
## Loading required package: survival
## 
## Attaching package: 'survival'
## 
## The following object is masked from 'package:boot':
## 
##     aml
## 
## The following object is masked from 'package:caret':
## 
##     cluster
library(e1071)
library(ggthemes)
## Warning: package 'ggthemes' was built under R version 4.2.3

Question 5

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:
  
  > x1 <- runif (500) - 0.5
  > x2 <- runif (500) - 0.5
  > y <- 1 * (x1^2 - x2^2 > 0)
  
set.seed(421)
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.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
  (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 = x1, x2 = x2, y = y)
lm.prob = predict(lm.fit, data, type = "response")
lm.pred = ifelse(lm.prob > 0.52, 1, 0)
data.pos = data[lm.pred == 1, ]
data.neg = data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)

  (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.fit = glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), 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.prob = predict(lm.fit, data, type = "response")
lm.pred = ifelse(lm.prob > 0.5, 1, 0)
data.pos = data[lm.pred == 1, ]
data.neg = data[lm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)

  (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.
  
svm.fit = svm(as.factor(y) ~ x1 + x2, data, kernel = "linear", cost = 0.1)
svm.pred = predict(svm.fit, data)
data.pos = data[svm.pred == 1, ]
data.neg = data[svm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 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.fit = svm(as.factor(y) ~ x1 + x2, data, gamma = 1)
svm.pred = predict(svm.fit, data)
data.pos = data[svm.pred == 1, ]
data.neg = data[svm.pred == 0, ]
plot(data.pos$x1, data.pos$x2, col = "blue", xlab = "X1", ylab = "X2", pch = "+")
points(data.neg$x1, data.neg$x2, col = "red", pch = 4)

  (i) Comment on your results.
  
      The models performed in the experiment perfromed shows the importance of use for finding non-linear models and using cross-validation is simplier with the parameter of gamma. to add the method used in part h is the better of the methods used as the boundries are more clear to see and analyze.   

Question 7

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(ISLR2)
gas.med = median(Auto$mpg)
new.var = ifelse(Auto$mpg > gas.med, 1, 0)
Auto$mpglevel = as.factor(new.var)
(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.
library(e1071)
set.seed(3255)
tune.out = tune(e1071 :: svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100)))
summary(tune.out)
## 
## Parameter tuning of 'e1071::svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.01269231 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-02 0.07397436 0.06863413
## 2 1e-01 0.05102564 0.06923024
## 3 1e+00 0.01269231 0.02154160
## 4 5e+00 0.01519231 0.01760469
## 5 1e+01 0.02025641 0.02303772
## 6 1e+02 0.03294872 0.02898463
(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(21)
tune.out = tune(e1071 :: svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1, 1, 5, 10), degree = c(2, 3, 4)))
summary(tune.out)
## 
## Parameter tuning of 'e1071::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
set.seed(463)
tune.out = tune(e1071 :: svm, mpglevel ~ ., 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 'e1071::svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##    10  0.01
## 
## - best performance: 0.02551282 
## 
## - Detailed performance results:
##    cost gamma      error dispersion
## 1   0.1 1e-02 0.09429487 0.04814900
## 2   1.0 1e-02 0.07897436 0.03875105
## 3   5.0 1e-02 0.05352564 0.02532795
## 4  10.0 1e-02 0.02551282 0.02417610
## 5   0.1 1e-01 0.07891026 0.03847631
## 6   1.0 1e-01 0.05602564 0.02881876
## 7   5.0 1e-01 0.03826923 0.03252085
## 8  10.0 1e-01 0.03320513 0.02964746
## 9   0.1 1e+00 0.57660256 0.05479863
## 10  1.0 1e+00 0.06628205 0.02996211
## 11  5.0 1e+00 0.06115385 0.02733573
## 12 10.0 1e+00 0.06115385 0.02733573
## 13  0.1 5e+00 0.57660256 0.05479863
## 14  1.0 5e+00 0.51538462 0.06642516
## 15  5.0 5e+00 0.50775641 0.07152757
## 16 10.0 5e+00 0.50775641 0.07152757
## 17  0.1 1e+01 0.57660256 0.05479863
## 18  1.0 1e+01 0.53833333 0.05640443
## 19  5.0 1e+01 0.53070513 0.05708644
## 20 10.0 1e+01 0.53070513 0.05708644
## 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
(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 = 10,
degree = 2)
svm.radial = svm(mpglevel ~ ., data = Auto, kernel = "radial", cost = 10, gamma = 0.01)
plotpairs = function(fit) {
for (name in names(Auto)[!(names(Auto) %in% c("mpg", "mpglevel", "name"))]) {
plot(fit, Auto, as.formula(paste("mpg~", name, sep = "")))
}
}

plotpairs(svm.linear)

plotpairs(svm.poly)

plotpairs(svm.radial)

Question 8

This problem involves the OJ data set which is part of the ISLR2 package.

require(ISLR); require(tidyverse); require(ggthemes)
## Loading required package: ISLR
## 
## Attaching package: 'ISLR'
## The following object is masked _by_ '.GlobalEnv':
## 
##     Auto
## The following objects are masked from 'package:ISLR2':
## 
##     Auto, Credit
require(caret); require(e1071)
set.seed(1)

data('OJ')
(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
inTrain <- sample(nrow(OJ), 800, replace = FALSE)

training <- OJ[inTrain,]
testing <- OJ[-inTrain,]
(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 <- svm(Purchase ~ ., data = training,
                  kernel = 'linear',
                  cost = 0.01)
summary(svm_linear)
## 
## Call:
## svm(formula = Purchase ~ ., data = training, 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?
svm_linear <- svm(Purchase ~ ., data = training,
                  kernel = 'linear',
                  cost = 0.01)
summary(svm_linear)
## 
## Call:
## svm(formula = Purchase ~ ., data = training, 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
postResample(predict(svm_linear, testing), testing$Purchase)
##  Accuracy     Kappa 
## 0.8222222 0.6082699
(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
svm_linear_tune <- train(Purchase ~ ., data = training,
                         method = 'svmLinear2',
                         trControl = trainControl(method = 'cv', number = 10),
                         preProcess = c('center', 'scale'),
                         tuneGrid = expand.grid(cost = seq(0.01, 10, length.out = 20)))
svm_linear_tune
## Support Vector Machines with Linear Kernel 
## 
## 800 samples
##  17 predictor
##   2 classes: 'CH', 'MM' 
## 
## Pre-processing: centered (17), scaled (17) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 721, 720, 720, 720, 721, 719, ... 
## Resampling results across tuning parameters:
## 
##   cost        Accuracy   Kappa    
##    0.0100000  0.8199215  0.6202565
##    0.5357895  0.8273760  0.6360834
##    1.0615789  0.8236101  0.6284665
##    1.5873684  0.8261105  0.6333280
##    2.1131579  0.8261105  0.6333280
##    2.6389474  0.8273605  0.6362121
##    3.1647368  0.8261105  0.6338114
##    3.6905263  0.8248605  0.6309732
##    4.2163158  0.8248605  0.6309732
##    4.7421053  0.8261105  0.6338114
##    5.2678947  0.8273605  0.6361662
##    5.7936842  0.8273605  0.6361662
##    6.3194737  0.8260947  0.6331693
##    6.8452632  0.8260947  0.6331693
##    7.3710526  0.8260947  0.6331693
##    7.8968421  0.8273605  0.6361662
##    8.4226316  0.8273605  0.6361662
##    8.9484211  0.8273605  0.6361662
##    9.4742105  0.8248447  0.6308145
##   10.0000000  0.8248447  0.6308145
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was cost = 0.5357895.
(e) Compute the training and test error rates using this new value for cost.
postResample(predict(svm_linear_tune, training), training$Purchase)
##  Accuracy     Kappa 
## 0.8350000 0.6524601
postResample(predict(svm_linear_tune, testing), testing$Purchase)
##  Accuracy     Kappa 
## 0.8444444 0.6585983
(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 ~ ., data = training,
                  method = 'radial',
                  cost = 0.01)
summary(svm_radial)
## 
## Call:
## svm(formula = Purchase ~ ., data = training, method = "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
postResample(predict(svm_radial, training), training$Purchase)
## Accuracy    Kappa 
##  0.60625  0.00000
postResample(predict(svm_radial, testing), testing$Purchase)
##  Accuracy     Kappa 
## 0.6222222 0.0000000
svm_radial_tune <- train(Purchase ~ ., data = training,
                         method = 'svmRadial',
                         trControl = trainControl(method = 'cv', number = 10),
                         preProcess = c('center', 'scale'),
                         tuneGrid = expand.grid(C = seq(0.01, 10, length.out = 20),
                                                sigma = 0.05691))
svm_radial_tune
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 800 samples
##  17 predictor
##   2 classes: 'CH', 'MM' 
## 
## Pre-processing: centered (17), scaled (17) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 720, 719, 719, 721, 719, 720, ... 
## Resampling results across tuning parameters:
## 
##   C           Accuracy   Kappa    
##    0.0100000  0.6062600  0.0000000
##    0.5357895  0.8274369  0.6315267
##    1.0615789  0.8249527  0.6267051
##    1.5873684  0.8199986  0.6165675
##    2.1131579  0.8174982  0.6105624
##    2.6389474  0.8149824  0.6041027
##    3.1647368  0.8112166  0.5964807
##    3.6905263  0.8112166  0.5964807
##    4.2163158  0.8124512  0.5993391
##    4.7421053  0.8137170  0.6021336
##    5.2678947  0.8137174  0.6017074
##    5.7936842  0.8137174  0.6017074
##    6.3194737  0.8124828  0.5988491
##    6.8452632  0.8124828  0.5988491
##    7.3710526  0.8137641  0.6020343
##    7.8968421  0.8112324  0.5967764
##    8.4226316  0.8112324  0.5967764
##    8.9484211  0.8099666  0.5939493
##    9.4742105  0.8124982  0.5992398
##   10.0000000  0.8124982  0.5992398
## 
## Tuning parameter 'sigma' was held constant at a value of 0.05691
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were sigma = 0.05691 and C = 0.5357895.
postResample(predict(svm_radial_tune, training), training$Purchase)
## Accuracy    Kappa 
## 0.851250 0.684392
postResample(predict(svm_radial_tune, testing), testing$Purchase)
##  Accuracy     Kappa 
## 0.8185185 0.6040582
(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
svm_poly <- svm(Purchase ~ ., data = training,
                  method = 'polynomial', degree = 2,
                  cost = 0.01)
summary(svm_poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = training, method = "polynomial", 
##     degree = 2, 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
postResample(predict(svm_poly, training), training$Purchase)
## Accuracy    Kappa 
##  0.60625  0.00000
postResample(predict(svm_poly, testing), testing$Purchase)
##  Accuracy     Kappa 
## 0.6222222 0.0000000
vm_poly_tune <- train(Purchase ~ ., data = training,
                         method = 'svmPoly',
                         trControl = trainControl(method = 'cv', number = 10),
                         preProcess = c('center', 'scale'),
                         tuneGrid = expand.grid(degree = 2,
                                         C = seq(0.01, 10, length.out = 20),
                                         scale = TRUE))
vm_poly_tune
## Support Vector Machines with Polynomial Kernel 
## 
## 800 samples
##  17 predictor
##   2 classes: 'CH', 'MM' 
## 
## Pre-processing: centered (17), scaled (17) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 721, 720, 719, 719, 720, 721, ... 
## Resampling results across tuning parameters:
## 
##   C           Accuracy   Kappa    
##    0.0100000  0.8249986  0.6233962
##    0.5357895  0.8224662  0.6237344
##    1.0615789  0.8224975  0.6238801
##    1.5873684  0.8162783  0.6107559
##    2.1131579  0.8199816  0.6194664
##    2.6389474  0.8187316  0.6172318
##    3.1647368  0.8187475  0.6166477
##    3.6905263  0.8137625  0.6061815
##    4.2163158  0.8137467  0.6062677
##    4.7421053  0.8162158  0.6109565
##    5.2678947  0.8174816  0.6133548
##    5.7936842  0.8162158  0.6109565
##    6.3194737  0.8149812  0.6080981
##    6.8452632  0.8149812  0.6080981
##    7.3710526  0.8174816  0.6138489
##    7.8968421  0.8187316  0.6162900
##    8.4226316  0.8174816  0.6139101
##    8.9484211  0.8174816  0.6139101
##    9.4742105  0.8174816  0.6139101
##   10.0000000  0.8174816  0.6139101
## 
## Tuning parameter 'degree' was held constant at a value of 2
## Tuning
##  parameter 'scale' was held constant at a value of TRUE
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were degree = 2, scale = TRUE and C = 0.01.
postResample(predict(vm_poly_tune, training), training$Purchase)
## Accuracy    Kappa 
## 0.850000 0.678295
 postResample(predict(vm_poly_tune, testing), testing$Purchase)
##  Accuracy     Kappa 
## 0.8148148 0.5886654
(h) Overall, which approach seems to give the best results on this data?

    After analyzing, comparing and running the models it is found that the model findings are simular but the radial kernal does best by a small margin.