library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.2
library(e1071)
library(ISLR2)
library(caret)
## Loading required package: lattice
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.2     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ✔ readr     2.1.5
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ purrr::lift()   masks caret::lift()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Problem 5

  1. Generate a data set with n = 500 and p = 2, such that the obser- vations belong to two classes with a quadratic decision boundary between them. For instance, you can do this as follows:
set.seed(123)


x1 <- runif(500) - 0.5
x2 <- runif(500) - 0.5


y <- as.integer(x1^2 - x2^2 > 0)

data <- data.frame(x1, x2, y)
head(data)
##            x1         x2 y
## 1 -0.21242248 -0.1463939 1
## 2  0.28830514 -0.1335586 1
## 3 -0.09102308 -0.2128999 0
## 4  0.38301740 -0.4200271 0
## 5  0.44046728 -0.1345457 1
## 6 -0.45444350 -0.3219862 1
  1. Plot the observations, colored according to their class labels. Your plot should display X1 on the x-axis, and X2 on the y- axis.
plot <- ggplot(data, aes(x = x1, y = x2, color = factor(y))) +
  geom_point() + 
  labs(color = "Class", x = "X1", y = "X2") +
  ggtitle("Scatter Plot of Observations with Quadratic Decision Boundary") +
  scale_color_manual(values = c("orange", "green")) 

print(plot)

  1. Fit a logistic regression model to the data, using X1 and X2 as predictors
model <- glm(y ~ x1 + x2, family = binomial, data = data)

summary(model)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = binomial, data = data)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  0.04792    0.08949   0.535    0.592
## x1          -0.03999    0.31516  -0.127    0.899
## x2           0.11509    0.30829   0.373    0.709
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 692.86  on 499  degrees of freedom
## Residual deviance: 692.71  on 497  degrees of freedom
## AIC: 698.71
## 
## Number of Fisher Scoring iterations: 3
  1. Apply this model to the training data in order to obtain a pre- dicted class label for each training observation. Plot the ob- servations, colored according to the predicted class labels. The decision boundary should be linear.
predicted_probs <- predict(model, type = "response")

predicted_labels <- as.integer(predicted_probs > 0.5)

data$predicted_labels <- predicted_labels

plot_predicted <- ggplot(data, aes(x = x1, y = x2, color = factor(predicted_labels))) +
  geom_point() + 
  labs(color = "Predicted Class", x = "X1", y = "X2") +
  ggtitle("Scatter Plot of Predicted Class Labels with Linear Decision Boundary") +
  scale_color_manual(values = c("orange", "green")) 
print(plot_predicted)

  1. Now fit a logistic regression model to the data using non-linear functions of X1 and X2 as predictors (e.g. X12, X1 ×X2, log(X2), and so forth).
model_nl <- glm(y ~ x1 + x2 + I(x1^2) + I(x2^2) + I(x1*x2), family = binomial, data = data)
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(model_nl)
## 
## Call:
## glm(formula = y ~ x1 + x2 + I(x1^2) + I(x2^2) + I(x1 * x2), family = binomial, 
##     data = data)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept)     -7.12    1170.02  -0.006    0.995
## x1            -146.56   10983.22  -0.013    0.989
## x2              55.75   11290.45   0.005    0.996
## I(x1^2)      12828.87  479505.56   0.027    0.979
## I(x2^2)     -12842.99  481258.81  -0.027    0.979
## I(x1 * x2)     566.19   36927.06   0.015    0.988
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9286e+02  on 499  degrees of freedom
## Residual deviance: 2.3990e-06  on 494  degrees of freedom
## AIC: 12
## 
## Number of Fisher Scoring iterations: 25
  1. Apply this model to the training data in order to obtain a pre- dicted class label for each training observation. Plot the ob- servations, 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.
predicted_probs_nl <- predict(model_nl, type = "response")

predicted_labels_nl <- as.integer(predicted_probs_nl > 0.5)

data$predicted_labels_nl <- predicted_labels_nl

plot_predicted_nl <- ggplot(data, aes(x = x1, y = x2, color = factor(predicted_labels_nl))) +
  geom_point() + 
  labs(color = "Predicted Class", x = "X1", y = "X2") +
  ggtitle("Scatter Plot of Predicted Class Labels with Non-linear Decision Boundary") +
  scale_color_manual(values = c("orange", "green")) 

print(plot_predicted_nl)

  1. Fit a support vector classifier to the data with X1 and X2 as predictors. Obtain a class prediction for each training observa- tion. Plot the observations, colored according to the predicted class labels.
svc_model <- svm(y ~ x1 + x2, data = data, type = "C-classification", kernel = "linear")

svc_predictions <- predict(svc_model, data)

data$svc_predictions <- svc_predictions

plot_svc <- ggplot(data, aes(x = x1, y = x2, color = factor(svc_predictions))) +
  geom_point() +
  labs(color = "Predicted Class", x = "X1", y = "X2") +
  ggtitle("Scatter Plot of SVC Predicted Class Labels") +
  scale_color_manual(values = c("orange", "green"))  # Customize colors

print(plot_svc)

  1. 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_nonlinear <- svm(y ~ x1 + x2, data = data, type = "C-classification", kernel = "radial")

svm_nonlinear_predictions <- predict(svm_nonlinear, data)

data$svm_nonlinear_predictions <- svm_nonlinear_predictions

plot_svm_nonlinear <- ggplot(data, aes(x = x1, y = x2, color = factor(svm_nonlinear_predictions))) +
  geom_point() +
  labs(color = "Predicted Class", x = "X1", y = "X2") +
  ggtitle("Scatter Plot with SVM Non-linear Kernel Predicted Class Labels") +
  scale_color_manual(values = c("red", "blue"))  # Customize colors

print(plot_svm_nonlinear)

  1. Comment on your results.

In question “h”, it’s evident that support vector machines with radial kernels effectively highlight the non-linear boundary. This contrasts with other methods, which struggled to clearly define the linear boundary, if they managed to define it at all.

Question 7

  1. 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.
auto <- read.csv("/Users/paymankhalid/Desktop/Auto.csv")

head(auto)
##   mpg cylinders displacement horsepower weight acceleration year origin
## 1  18         8          307        130   3504         12.0   70      1
## 2  15         8          350        165   3693         11.5   70      1
## 3  18         8          318        150   3436         11.0   70      1
## 4  16         8          304        150   3433         12.0   70      1
## 5  17         8          302        140   3449         10.5   70      1
## 6  15         8          429        198   4341         10.0   70      1
##                        name
## 1 chevrolet chevelle malibu
## 2         buick skylark 320
## 3        plymouth satellite
## 4             amc rebel sst
## 5               ford torino
## 6          ford galaxie 500
str(auto)
## 'data.frame':    397 obs. of  9 variables:
##  $ mpg         : num  18 15 18 16 17 15 14 14 14 15 ...
##  $ cylinders   : int  8 8 8 8 8 8 8 8 8 8 ...
##  $ displacement: num  307 350 318 304 302 429 454 440 455 390 ...
##  $ horsepower  : chr  "130" "165" "150" "150" ...
##  $ weight      : int  3504 3693 3436 3433 3449 4341 4354 4312 4425 3850 ...
##  $ acceleration: num  12 11.5 11 12 10.5 10 9 8.5 10 8.5 ...
##  $ year        : int  70 70 70 70 70 70 70 70 70 70 ...
##  $ origin      : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ name        : chr  "chevrolet chevelle malibu" "buick skylark 320" "plymouth satellite" "amc rebel sst" ...
  1. 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.
median <- median(Auto$mpg)
Auto$high <- ifelse(Auto$mpg > median, 1, 0)
  1. 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 dif- ferent 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.

The lowest error, 0.068, was achieved with a cost parameter of 1. The highest error, 0.105, occurred when the cost parameter was set to 100.

set.seed(10)
tune7 <- tune(svm,high~.,data=Auto,kernel="linear", ranges=list(cost=c(0.001, 0.01, 0.1, 1,5,10,100)))
summary(tune7)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.06810309 
## 
## - Detailed performance results:
##    cost      error dispersion
## 1 1e-03 0.09320471 0.01631536
## 2 1e-02 0.08291148 0.02165372
## 3 1e-01 0.07654201 0.02370418
## 4 1e+00 0.06810309 0.01237864
## 5 5e+00 0.07582447 0.01623029
## 6 1e+01 0.08106759 0.01733018
## 7 1e+02 0.10509634 0.02755424
  1. Now repeat (b), this time using SVMs with radial and polyno- mial basis kernels, with different values of gamma and degree and cost. Comment on your results.

The SVM with a radial kernel achieved the lowest error of 0.051 with gamma set to 0.5 and cost set to 100.

tuner <- tune(svm,high~.,data=Auto, kernel="radial",ranges=list(cost=c(0.1,1,10,100,1000),gamma=c(0.5,1,2,3,4)))
summary(tuner)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma
##   100   0.5
## 
## - best performance: 0.05108172 
## 
## - Detailed performance results:
##     cost gamma      error  dispersion
## 1  1e-01   0.5 0.07992382 0.006821918
## 2  1e+00   0.5 0.05145108 0.009724641
## 3  1e+01   0.5 0.05109581 0.010186243
## 4  1e+02   0.5 0.05108172 0.010163405
## 5  1e+03   0.5 0.05108172 0.010163405
## 6  1e-01   1.0 0.30053012 0.025143810
## 7  1e+00   1.0 0.09824722 0.007983103
## 8  1e+01   1.0 0.09913269 0.009064953
## 9  1e+02   1.0 0.09913269 0.009064953
## 10 1e+03   1.0 0.09913269 0.009064953
## 11 1e-01   2.0 0.43095390 0.029751060
## 12 1e+00   2.0 0.20679244 0.007190694
## 13 1e+01   2.0 0.20700060 0.007532780
## 14 1e+02   2.0 0.20700060 0.007532780
## 15 1e+03   2.0 0.20700060 0.007532780
## 16 1e-01   3.0 0.44362435 0.029477687
## 17 1e+00   3.0 0.23084414 0.006807369
## 18 1e+01   3.0 0.23090449 0.006865420
## 19 1e+02   3.0 0.23090449 0.006865420
## 20 1e+03   3.0 0.23090449 0.006865420
## 21 1e-01   4.0 0.44783443 0.028966389
## 22 1e+00   4.0 0.23574602 0.006552739
## 23 1e+01   4.0 0.23576094 0.006560007
## 24 1e+02   4.0 0.23576094 0.006560007
## 25 1e+03   4.0 0.23576094 0.006560007
tunep <- tune(svm,high~.,data=Auto,kernel="polynomial",ranges=list(cost=c(0.1,1,10,100,1000),gamma=c(0.5,1,2,3,4),degree=c(2,3,4)))
summary(tunep)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost gamma degree
##   0.1   0.5      3
## 
## - best performance: 0.09785217 
## 
## - Detailed performance results:
##     cost gamma degree      error dispersion
## 1  1e-01   0.5      2 0.13086817 0.03066167
## 2  1e+00   0.5      2 0.12469909 0.02386606
## 3  1e+01   0.5      2 0.15629747 0.03706943
## 4  1e+02   0.5      2 0.16715207 0.04088601
## 5  1e+03   0.5      2 0.16715207 0.04088601
## 6  1e-01   1.0      2 0.12245522 0.02618249
## 7  1e+00   1.0      2 0.13892702 0.02911607
## 8  1e+01   1.0      2 0.16715207 0.04088601
## 9  1e+02   1.0      2 0.16715207 0.04088601
## 10 1e+03   1.0      2 0.16715207 0.04088601
## 11 1e-01   2.0      2 0.12820131 0.02498771
## 12 1e+00   2.0      2 0.15915447 0.03924310
## 13 1e+01   2.0      2 0.16715207 0.04088601
## 14 1e+02   2.0      2 0.16715207 0.04088601
## 15 1e+03   2.0      2 0.16715207 0.04088601
## 16 1e-01   3.0      2 0.13797549 0.02892231
## 17 1e+00   3.0      2 0.16714198 0.04087876
## 18 1e+01   3.0      2 0.16714198 0.04087876
## 19 1e+02   3.0      2 0.16714198 0.04087876
## 20 1e+03   3.0      2 0.16714198 0.04087876
## 21 1e-01   4.0      2 0.14797161 0.03346448
## 22 1e+00   4.0      2 0.16715207 0.04088601
## 23 1e+01   4.0      2 0.16715207 0.04088601
## 24 1e+02   4.0      2 0.16715207 0.04088601
## 25 1e+03   4.0      2 0.16715207 0.04088601
## 26 1e-01   0.5      3 0.09785217 0.02228256
## 27 1e+00   0.5      3 0.12632101 0.06148868
## 28 1e+01   0.5      3 0.15788113 0.06866574
## 29 1e+02   0.5      3 0.15788113 0.06866574
## 30 1e+03   0.5      3 0.15788113 0.06866574
## 31 1e-01   1.0      3 0.12374300 0.05938214
## 32 1e+00   1.0      3 0.15324716 0.06643947
## 33 1e+01   1.0      3 0.15788113 0.06866574
## 34 1e+02   1.0      3 0.15788113 0.06866574
## 35 1e+03   1.0      3 0.15788113 0.06866574
## 36 1e-01   2.0      3 0.14900247 0.06496859
## 37 1e+00   2.0      3 0.15788113 0.06866574
## 38 1e+01   2.0      3 0.15788113 0.06866574
## 39 1e+02   2.0      3 0.15788113 0.06866574
## 40 1e+03   2.0      3 0.15788113 0.06866574
## 41 1e-01   3.0      3 0.15788550 0.06867294
## 42 1e+00   3.0      3 0.15788550 0.06867294
## 43 1e+01   3.0      3 0.15788550 0.06867294
## 44 1e+02   3.0      3 0.15788550 0.06867294
## 45 1e+03   3.0      3 0.15788550 0.06867294
## 46 1e-01   4.0      3 0.15788113 0.06866574
## 47 1e+00   4.0      3 0.15788113 0.06866574
## 48 1e+01   4.0      3 0.15788113 0.06866574
## 49 1e+02   4.0      3 0.15788113 0.06866574
## 50 1e+03   4.0      3 0.15788113 0.06866574
## 51 1e-01   0.5      4 0.27597002 0.16171207
## 52 1e+00   0.5      4 0.37492046 0.22223398
## 53 1e+01   0.5      4 0.42519522 0.27943059
## 54 1e+02   0.5      4 0.42519522 0.27943059
## 55 1e+03   0.5      4 0.42519522 0.27943059
## 56 1e-01   1.0      4 0.38493239 0.22489581
## 57 1e+00   1.0      4 0.42519522 0.27943059
## 58 1e+01   1.0      4 0.42519522 0.27943059
## 59 1e+02   1.0      4 0.42519522 0.27943059
## 60 1e+03   1.0      4 0.42519522 0.27943059
## 61 1e-01   2.0      4 0.42519522 0.27943059
## 62 1e+00   2.0      4 0.42519522 0.27943059
## 63 1e+01   2.0      4 0.42519522 0.27943059
## 64 1e+02   2.0      4 0.42519522 0.27943059
## 65 1e+03   2.0      4 0.42519522 0.27943059
## 66 1e-01   3.0      4 0.42518618 0.27941546
## 67 1e+00   3.0      4 0.42518618 0.27941546
## 68 1e+01   3.0      4 0.42518618 0.27941546
## 69 1e+02   3.0      4 0.42518618 0.27941546
## 70 1e+03   3.0      4 0.42518618 0.27941546
## 71 1e-01   4.0      4 0.42519522 0.27943059
## 72 1e+00   4.0      4 0.42519522 0.27943059
## 73 1e+01   4.0      4 0.42519522 0.27943059
## 74 1e+02   4.0      4 0.42519522 0.27943059
## 75 1e+03   4.0      4 0.42519522 0.27943059

The best SVM with a polynomial kernel achieved an error rate of 0.097 with gamma set to 0.5, cost set to 0.1, and a degree 3 polynomial.

The SVM model that performed best on the data used a radial kernel, while the one with the poorest performance used a polynomial kernel.

  1. 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.
set.seed(10)

tune_linear <- tune(svm, high ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.001, 0.01, 0.1, 1, 5, 10, 100)))
best_linear_svm <- tune_linear$best.model

tune_radial <- tune(svm, high ~ ., data = Auto, kernel = "radial", ranges = list(cost = c(0.1, 1, 10, 100, 1000), gamma = c(0.5, 1, 2, 3, 4)))
best_radial_svm <- tune_radial$best.model

tune_poly <- tune(svm, high ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.1, 1, 10, 100, 1000), gamma = c(0.5, 1, 2, 3, 4), degree = c(2, 3, 4)))
best_poly_svm <- tune_poly$best.model

par(mfrow = c(2, 2)) # Set up a 2x2 plotting space
plot(best_linear_svm, Auto, displacement ~ horsepower, main = "Linear SVM: Displacement vs Horsepower")
plot(best_linear_svm, Auto, weight ~ horsepower, main = "Linear SVM: Weight vs Horsepower")

plot(best_radial_svm, Auto, displacement ~ horsepower, main = "Radial SVM: Displacement vs Horsepower")
plot(best_radial_svm, Auto, weight ~ horsepower, main = "Radial SVM: Weight vs Horsepower")

plot(best_poly_svm, Auto, displacement ~ horsepower, main = "Polynomial SVM: Displacement vs Horsepower")
plot(best_poly_svm, Auto, weight ~ horsepower, main = "Polynomial SVM: Weight vs Horsepower")

par(mfrow = c(1, 1))

Question 8

  1. This problem involves the OJ data set which is part of the ISLR2 package.
data("OJ")

head(OJ)
##   Purchase WeekofPurchase StoreID PriceCH PriceMM DiscCH DiscMM SpecialCH
## 1       CH            237       1    1.75    1.99   0.00    0.0         0
## 2       CH            239       1    1.75    1.99   0.00    0.3         0
## 3       CH            245       1    1.86    2.09   0.17    0.0         0
## 4       MM            227       1    1.69    1.69   0.00    0.0         0
## 5       CH            228       7    1.69    1.69   0.00    0.0         0
## 6       CH            230       7    1.69    1.99   0.00    0.0         0
##   SpecialMM  LoyalCH SalePriceMM SalePriceCH PriceDiff Store7 PctDiscMM
## 1         0 0.500000        1.99        1.75      0.24     No  0.000000
## 2         1 0.600000        1.69        1.75     -0.06     No  0.150754
## 3         0 0.680000        2.09        1.69      0.40     No  0.000000
## 4         0 0.400000        1.69        1.69      0.00     No  0.000000
## 5         0 0.956535        1.69        1.69      0.00    Yes  0.000000
## 6         1 0.965228        1.99        1.69      0.30    Yes  0.000000
##   PctDiscCH ListPriceDiff STORE
## 1  0.000000          0.24     1
## 2  0.000000          0.24     1
## 3  0.091398          0.23     1
## 4  0.000000          0.00     1
## 5  0.000000          0.00     0
## 6  0.000000          0.30     0
  1. Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
set.seed(123)

train_indices <- sample(nrow(OJ), 800)

train_set <- OJ[train_indices, ]

test_set <- OJ[-train_indices, ]
  1. Fit a support vector classifier to the training data using cost = 0.01, with Purchase as the response and the other vari- ables as predictors. Use the summary() function to produce sum- mary statistics, and describe the results obtained.

It created 442 vectors, 220 of them belong to CH and 222 belong to MM

svm_model <- svm(Purchase ~ ., data = train_set, type = "C-classification", kernel = "linear", cost = 0.01)

summary(svm_model)
## 
## Call:
## svm(formula = Purchase ~ ., data = train_set, type = "C-classification", 
##     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
  1. What are the training and test error rates?
train_predictions <- predict(svm_model, train_set)

test_predictions <- predict(svm_model, test_set)

train_error_rate <- mean(train_predictions != train_set$Purchase)
test_error_rate <- mean(test_predictions != test_set$Purchase)



cat("Training Error Rate: ", train_error_rate, "\n")
## Training Error Rate:  0.165
cat("Test Error Rate: ", test_error_rate, "\n")
## Test Error Rate:  0.1777778
  1. Use the tune() function to select an optimal cost. Consider val- ues in the range 0.01 to 10.
cost_values <- 10^seq(-2, 1, length.out = 10)  


tuning_results <- tune(svm, Purchase ~ ., data = train_set, 
                       kernel = "linear", 
                       ranges = list(cost = cost_values),
                       tunecontrol = tune.control(sampling = "cross", cross = 10))

print(tuning_results)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##      cost
##  4.641589
## 
## - best performance: 0.165
best_cost <- tuning_results$best.parameters$cost
best_performance <- tuning_results$best.performance

cat("Optimal Cost: ", best_cost, "\n")
## Optimal Cost:  4.641589
cat("Best Performance (Cross-validation Error): ", best_performance, "\n")
## Best Performance (Cross-validation Error):  0.165
optimized_svm_model <- svm(Purchase ~ ., data = train_set, 
                           type = "C-classification", kernel = "linear", 
                           cost = best_cost)

summary(optimized_svm_model)
## 
## Call:
## svm(formula = Purchase ~ ., data = train_set, type = "C-classification", 
##     kernel = "linear", cost = best_cost)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  4.641589 
## 
## Number of Support Vectors:  336
## 
##  ( 167 169 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
  1. Compute the training and test error rates using this new value for cost.
optimized_svm_model <- svm(Purchase ~ ., data = train_set, 
                           type = "C-classification", kernel = "linear", 
                           cost = best_cost)


train_predictions_optimized <- predict(optimized_svm_model, train_set)

test_predictions_optimized <- predict(optimized_svm_model, test_set)

train_error_rate_optimized <- mean(train_predictions_optimized != train_set$Purchase)
test_error_rate_optimized <- mean(test_predictions_optimized != test_set$Purchase)

cat("Optimized Training Error Rate: ", train_error_rate_optimized, "\n")
## Optimized Training Error Rate:  0.16125
cat("Optimized Test Error Rate: ", test_error_rate_optimized, "\n")
## Optimized Test Error Rate:  0.162963
  1. Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
svm_model_radial <- svm(Purchase ~ ., data = train_set, type = "C-classification",
                        kernel = "radial", cost = 0.01)  

summary(svm_model_radial)
## 
## Call:
## svm(formula = Purchase ~ ., data = train_set, type = "C-classification", 
##     kernel = "radial", cost = 0.01)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  0.01 
## 
## Number of Support Vectors:  629
## 
##  ( 313 316 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train_predictions_radial <- predict(svm_model_radial, train_set)
test_predictions_radial <- predict(svm_model_radial, test_set)

train_error_rate_radial <- mean(train_predictions_radial != train_set$Purchase)
test_error_rate_radial <- mean(test_predictions_radial != test_set$Purchase)

cat("Training Error Rate with Radial Kernel: ", train_error_rate_radial, "\n")
## Training Error Rate with Radial Kernel:  0.39125
cat("Test Error Rate with Radial Kernel: ", test_error_rate_radial, "\n")
## Test Error Rate with Radial Kernel:  0.3851852
tune_results_radial <- tune(svm, Purchase ~ ., data = train_set, 
                            kernel = "radial", 
                            ranges = list(cost = 10^seq(-2, 1, length.out = 10)))

cat("Best Cost (Radial): ", tune_results_radial$best.parameters$cost, "\n")
## Best Cost (Radial):  1
cat("Best Performance (Radial): ", tune_results_radial$best.performance, "\n")
## Best Performance (Radial):  0.1625
optimized_svm_radial <- svm(Purchase ~ ., data = train_set, 
                            type = "C-classification", kernel = "radial", 
                            cost = tune_results_radial$best.parameters$cost)

train_predictions_optimized_radial <- predict(optimized_svm_radial, train_set)
test_predictions_optimized_radial <- predict(optimized_svm_radial, test_set)

train_error_rate_optimized_radial <- mean(train_predictions_optimized_radial != train_set$Purchase)
test_error_rate_optimized_radial <- mean(test_predictions_optimized_radial != test_set$Purchase)

cat("Optimized Training Error Rate (Radial): ", train_error_rate_optimized_radial, "\n")
## Optimized Training Error Rate (Radial):  0.13875
cat("Optimized Test Error Rate (Radial): ", test_error_rate_optimized_radial, "\n")
## Optimized Test Error Rate (Radial):  0.1888889
  1. Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.
svm_model_poly <- svm(Purchase ~ ., data = train_set, type = "C-classification",
                      kernel = "polynomial", degree = 2, cost = 0.01)  
summary(svm_model_poly)
## 
## Call:
## svm(formula = Purchase ~ ., data = train_set, type = "C-classification", 
##     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:  631
## 
##  ( 313 318 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train_predictions_poly <- predict(svm_model_poly, train_set)
test_predictions_poly <- predict(svm_model_poly, test_set)

train_error_rate_poly <- mean(train_predictions_poly != train_set$Purchase)
test_error_rate_poly <- mean(test_predictions_poly != test_set$Purchase)

cat("Training Error Rate with Polynomial Kernel: ", train_error_rate_poly, "\n")
## Training Error Rate with Polynomial Kernel:  0.3725
cat("Test Error Rate with Polynomial Kernel: ", test_error_rate_poly, "\n")
## Test Error Rate with Polynomial Kernel:  0.3740741
tune_results_poly <- tune(svm, Purchase ~ ., data = train_set, 
                          kernel = "polynomial", degree = 2,
                          ranges = list(cost = 10^seq(-2, 1, length.out = 10)))

cat("Best Cost (Polynomial): ", tune_results_poly$best.parameters$cost, "\n")
## Best Cost (Polynomial):  4.641589
cat("Best Performance (Polynomial): ", tune_results_poly$best.performance, "\n")
## Best Performance (Polynomial):  0.17
optimized_svm_poly <- svm(Purchase ~ ., data = train_set, 
                          type = "C-classification", kernel = "polynomial", 
                          degree = 2, cost = tune_results_poly$best.parameters$cost)

train_predictions_optimized_poly <- predict(optimized_svm_poly, train_set)
test_predictions_optimized_poly <- predict(optimized_svm_poly, test_set)

train_error_rate_optimized_poly <- mean(train_predictions_optimized_poly != train_set$Purchase)
test_error_rate_optimized_poly <- mean(test_predictions_optimized_poly != test_set$Purchase)

cat("Optimized Training Error Rate (Polynomial): ", train_error_rate_optimized_poly, "\n")
## Optimized Training Error Rate (Polynomial):  0.1475
cat("Optimized Test Error Rate (Polynomial): ", test_error_rate_optimized_poly, "\n")
## Optimized Test Error Rate (Polynomial):  0.2
  1. Overall, which approach seems to give the best results on this data?

The linear basis approach seems to give the best results on this data.