Chapter 9 numbers 5, 7, and 8

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.

x1 = runif(500) - 0.5
x2 = runif(500) - 0.5
y = 1 * (x1^2 - x2^2 > 0)

df = data.frame(x1 = x1, x2 = x2, y = factor(y))

(b) Plot the observations, colored according to their class labels. Your plot should display X1 on the x-axis, and X2 on the y- axis.

df |>
  ggplot(aes(x = x1, y = x2, color = y)) +
  geom_point(alpha = 0.7) +
  labs(title = "Quadratic Decision Boundary Example",
       x = "X1", y = "X2", color = "Class") +
  theme_minimal()

(c) Fit a logistic regression model to the data, using X1 and X2 as predictors.

glm_model = glm(y ~ x1 + x2, data = df, family = binomial)

summary(glm_model)
## 
## Call:
## glm(formula = y ~ x1 + x2, family = binomial, data = df)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.01185    0.08967  -0.132    0.895
## x1           0.19651    0.31425   0.625    0.532
## x2           0.14794    0.30878   0.479    0.632
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 693.14  on 499  degrees of freedom
## Residual deviance: 692.50  on 497  degrees of freedom
## AIC: 698.5
## 
## 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.

df$pred_prob = predict(glm_model, type = "response")

df$pred_class = as.factor(ifelse(df$pred_prob > 0.5, 1, 0))

ggplot(df, aes(x = x1, y = x2, color = pred_class)) +
  geom_point(alpha = 0.6) +
  labs(title = "Predicted Class Labels from Logistic Regression",
       x = "X1", y = "X2", color = "Predicted Class") +
  theme_minimal()

(e) 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).

glm_model_nonlinear <- glm(y ~ x1 + x2 + I(x1^2) + I(x2^2) + I(x1 * x2), data = df, family = binomial)
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(glm_model_nonlinear)
## 
## Call:
## glm(formula = y ~ x1 + x2 + I(x1^2) + I(x2^2) + I(x1 * x2), family = binomial, 
##     data = df)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)
## (Intercept)     -6.965    181.559  -0.038    0.969
## x1            -181.046  11288.094  -0.016    0.987
## x2             -81.412  12293.841  -0.007    0.995
## I(x1^2)      69504.168 818340.890   0.085    0.932
## I(x2^2)     -70591.092 838172.809  -0.084    0.933
## I(x1 * x2)     583.798  32676.466   0.018    0.986
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 6.9314e+02  on 499  degrees of freedom
## Residual deviance: 6.9735e-05  on 494  degrees of freedom
## AIC: 12
## 
## 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.

df$pred_prob_nonlinear = predict(glm_model_nonlinear, type = "response")

df$pred_class_nonlinear = as.factor(ifelse(df$pred_prob_nonlinear > 0.5, 1, 0))

ggplot(df, aes(x = x1, y = x2, color = pred_class_nonlinear)) +
  geom_point(alpha = 0.6) +
  labs(title = "Predicted Class Labels from Nonlinear Logistic Regression",
       x = "X1", y = "X2", color = "Predicted Class") +
  theme_minimal()

(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.

library(e1071)
svc_model = svm(y ~ x1 + x2, data = df, kernel = "linear", cost = 1, scale = TRUE)

df$svc_pred = predict(svc_model, newdata = df)

ggplot(df, aes(x = x1, y = x2, color = svc_pred)) +
  geom_point(alpha = 0.6) +
  labs(title = "Support Vector Classifier Predictions",
       x = "X1", y = "X2", color = "Predicted Class") +
  theme_minimal()

(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.

svc_model = svm(y ~ x1 + x2, data = df, kernel = "radial", cost = 1, scale = TRUE)

df$svc_pred = predict(svc_model, newdata = df)

ggplot(df, aes(x = x1, y = x2, color = svc_pred)) +
  geom_point(alpha = 0.6) +
  labs(title = "Support Vector Classifier Predictions",
       x = "X1", y = "X2", color = "Predicted Class") +
  theme_minimal()

(i) Comment on your results. The radial kernel captured the true classes of the data better than the linear kernel.

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.

library(ISLR2)
data(Auto)

auto = Auto

(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_level = ifelse(auto$mpg > median(auto$mpg), 1, 0)
auto$mpg_level = as.factor(auto$mpg_level)

(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.

cost_values = c(0.01, 0.1, 1, 10, 100)

cv_errors = numeric(length(cost_values))

set.seed(123)
for (i in seq_along(cost_values)) {
  model = svm(mpg_level ~ . - mpg, data = auto, kernel = "linear",
               cost = cost_values[i], cross = 10)
  
  cv_errors[i] <- 1 - model$tot.accuracy / 100
}

results = data.frame(Cost = cost_values, CV_Error = cv_errors)

print(results)
##    Cost   CV_Error
## 1 1e-02 0.09183673
## 2 1e-01 0.08928571
## 3 1e+00 0.09183673
## 4 1e+01 0.10714286
## 5 1e+02 0.12755102

(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.

cost_values = c(0.01, 0.1, 1, 10, 100)

cv_errors = numeric(length(cost_values))

set.seed(123)
for (i in seq_along(cost_values)) {
  model = svm(mpg_level ~ . - mpg, data = auto, kernel = "radial",
               cost = cost_values[i], cross = 10)
  
  cv_errors[i] <- 1 - model$tot.accuracy / 100
}

results = data.frame(Cost = cost_values, CV_Error = cv_errors)

print(results)
##    Cost   CV_Error
## 1 1e-02 0.53316327
## 2 1e-01 0.16071429
## 3 1e+00 0.09183673
## 4 1e+01 0.09183673
## 5 1e+02 0.08418367
cost_values = c(0.01, 0.1, 1, 10, 100)

cv_errors = numeric(length(cost_values))

set.seed(123)
for (i in seq_along(cost_values)) {
  model = svm(mpg_level ~ . - mpg, data = auto, kernel = "polynomial",
               cost = cost_values[i], cross = 10)
  
  cv_errors[i] <- 1 - model$tot.accuracy / 100
}

results = data.frame(Cost = cost_values, CV_Error = cv_errors)

print(results)
##    Cost  CV_Error
## 1 1e-02 0.5535714
## 2 1e-01 0.5561224
## 3 1e+00 0.5714286
## 4 1e+01 0.5561224
## 5 1e+02 0.4668367

(d) Make some plots to back up your assertions in (b) and (c).

cost_values <- c(0.01, 0.1, 1, 10, 100)
kernels <- c("linear", "radial", "polynomial")

results <- data.frame()

set.seed(123)
for (kernel in kernels) {
  for (cost in cost_values) {
    model <- svm(mpg_level ~ . - mpg, data = auto,
                 kernel = kernel, cost = cost, cross = 10)
    
    cv_error <- 1 - model$tot.accuracy / 100
    results <- rbind(results, data.frame(Kernel = kernel, Cost = cost, CV_Error = cv_error))
  }
}

ggplot(results, aes(x = log10(Cost), y = CV_Error, color = Kernel)) +
  geom_line() +
  geom_point(size = 2) +
  labs(title = "SVM Cross-Validation Error by Kernel and Cost",
       x = "log10(Cost)", y = "CV Error") +
  theme_minimal()

8

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

data(OJ)

oj = OJ

(a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.

set.seed(22)

train_index = sample(1:nrow(oj), 800)

train = oj[train_index, ]
test = oj[-train_index, ]

(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.

svc_fit = svm(Purchase ~ ., data = train, kernel = "linear", cost = 0.01)
summary(svc_fit)
## 
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "linear", cost = 0.01)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  0.01 
## 
## Number of Support Vectors:  449
## 
##  ( 224 225 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

There were 449 support vectors. 224 in one class and 225 in the other.

(c) What are the training and test error rates?

train_preds = predict(svc_fit, newdata = train)
test_preds = predict(svc_fit, newdata = test)

train_error = mean(train_preds != train$Purchase)
test_error = mean(test_preds != test$Purchase)

train_error
## [1] 0.18125
test_error
## [1] 0.1592593

(d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.

set.seed(1)

ranges = list(cost = c(0.01, 0.1, 1, 5, 10))
tune_out = tune(svm, Purchase ~ ., data = train, kernel = "linear", ranges = ranges)

summary(tune_out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##   0.1
## 
## - best performance: 0.1775 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.18250 0.04571956
## 2  0.10 0.17750 0.04322101
## 3  1.00 0.18000 0.04377975
## 4  5.00 0.18625 0.03884174
## 5 10.00 0.18625 0.04348132
best_model = tune_out$best.model
summary(best_model)
## 
## Call:
## best.tune(METHOD = svm, train.x = Purchase ~ ., data = train, ranges = ranges, 
##     kernel = "linear")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  0.1 
## 
## Number of Support Vectors:  365
## 
##  ( 182 183 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM

(e) Compute the training and test error rates using this new value for cost.

train_preds = predict(best_model, newdata = train)
test_preds = predict(best_model, newdata = test)

train_error = mean(train_preds != train$Purchase)
test_error = mean(test_preds != test$Purchase)

train_error
## [1] 0.17625
test_error
## [1] 0.1407407

(f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.

radial_fit = svm(Purchase ~ ., data = train, kernel = "radial", cost = 0.01, gamma = 1)
summary(radial_fit)
## 
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "radial", cost = 0.01, 
##     gamma = 1)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  0.01 
## 
## Number of Support Vectors:  656
## 
##  ( 315 341 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train_preds = predict(radial_fit, newdata = train)
test_preds = predict(radial_fit, newdata = test)

train_error = mean(train_preds != train$Purchase)
test_error = mean(test_preds != test$Purchase)

train_error
## [1] 0.39375
test_error
## [1] 0.3777778
set.seed(1)

ranges = list(cost = c(0.01, 0.1, 1, 5, 10))
tune_out = tune(svm, Purchase ~ ., data = train, kernel = "radial", ranges = ranges, gamma = 1)

summary(tune_out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     1
## 
## - best performance: 0.2275 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.39375 0.05810969
## 2  0.10 0.34500 0.06043821
## 3  1.00 0.22750 0.04440971
## 4  5.00 0.23625 0.04101575
## 5 10.00 0.23875 0.04581439
best_model = tune_out$best.model
summary(best_model)
## 
## Call:
## best.tune(METHOD = svm, train.x = Purchase ~ ., data = train, ranges = ranges, 
##     kernel = "radial", gamma = 1)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  radial 
##        cost:  1 
## 
## Number of Support Vectors:  501
## 
##  ( 230 271 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train_preds = predict(best_model, newdata = train)
test_preds = predict(best_model, newdata = test)

train_error = mean(train_preds != train$Purchase)
test_error = mean(test_preds != test$Purchase)

train_error
## [1] 0.11875
test_error
## [1] 0.1962963

(g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree = 2.

poly_fit = svm(Purchase ~ ., data = train, kernel = "polynomial", cost = 0.01, degree = 2)
summary(poly_fit)
## 
## Call:
## svm(formula = Purchase ~ ., data = train, kernel = "polynomial", 
##     cost = 0.01, degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  0.01 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  638
## 
##  ( 315 323 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train_preds = predict(poly_fit, newdata = train)
test_preds = predict(poly_fit, newdata = test)

train_error = mean(train_preds != train$Purchase)
test_error = mean(test_preds != test$Purchase)

train_error
## [1] 0.39375
test_error
## [1] 0.3777778
set.seed(1)

ranges = list(cost = c(0.01, 0.1, 1, 5, 10))
tune_out = tune(svm, Purchase ~ ., data = train, kernel = "polynomial", ranges = ranges, degree = 2)

summary(tune_out)
## 
## Parameter tuning of 'svm':
## 
## - sampling method: 10-fold cross validation 
## 
## - best parameters:
##  cost
##     5
## 
## - best performance: 0.18875 
## 
## - Detailed performance results:
##    cost   error dispersion
## 1  0.01 0.39375 0.05810969
## 2  0.10 0.31250 0.05559027
## 3  1.00 0.21625 0.03438447
## 4  5.00 0.18875 0.04910660
## 5 10.00 0.19000 0.03855011
best_model = tune_out$best.model
summary(best_model)
## 
## Call:
## best.tune(METHOD = svm, train.x = Purchase ~ ., data = train, ranges = ranges, 
##     kernel = "polynomial", degree = 2)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  polynomial 
##        cost:  5 
##      degree:  2 
##      coef.0:  0 
## 
## Number of Support Vectors:  380
## 
##  ( 188 192 )
## 
## 
## Number of Classes:  2 
## 
## Levels: 
##  CH MM
train_preds = predict(best_model, newdata = train)
test_preds = predict(best_model, newdata = test)

train_error = mean(train_preds != train$Purchase)
test_error = mean(test_preds != test$Purchase)

train_error
## [1] 0.16875
test_error
## [1] 0.1481481

(h) Overall, which approach seems to give the best results on this data?

The linear model looks to be the best overall.