# 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(11)
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, x2, xlab = "X1", ylab = "X2", col = (4 - y), pch = (3 - y))

# (c) Fit a logistic regression model to the data, using X1 and X2 as predictors.
logit.fit <- glm(y ~ x1 + x2, family = "binomial")
summary(logit.fit)
##
## Call:
## glm(formula = y ~ x1 + x2, family = "binomial")
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.174 -1.126 -1.063 1.239 1.299
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.15180 0.08987 -1.689 0.0912 .
## x1 0.07975 0.32300 0.247 0.8050
## x2 0.23196 0.30306 0.765 0.4440
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 690.26 on 499 degrees of freedom
## Residual deviance: 689.59 on 497 degrees of freedom
## AIC: 695.59
##
## 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)
probs <- predict(logit.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.47] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0))

### The decision boundary is very linear, lined up all the way to the left of the graph.
# (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).
logitnl.fit <- glm(y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = "binomial")
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(logitnl.fit)
##
## Call:
## glm(formula = y ~ poly(x1, 2) + poly(x2, 2) + I(x1 * x2), family = "binomial")
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -0.01002 0.00000 0.00000 0.00000 0.01249
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1344.3 12358.9 -0.109 0.913
## poly(x1, 2)1 -308.2 204045.7 -0.002 0.999
## poly(x1, 2)2 237386.3 1452287.1 0.163 0.870
## poly(x2, 2)1 2068.2 218704.4 0.009 0.992
## poly(x2, 2)2 -262961.8 1604540.6 -0.164 0.870
## I(x1 * x2) -4992.2 114092.0 -0.044 0.965
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6.9026e+02 on 499 degrees of freedom
## Residual deviance: 3.5346e-04 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.
probs <- predict(logitnl.fit, data, type = "response")
preds <- rep(0, 500)
preds[probs > 0.47] <- 1
plot(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1), xlab = "X1", ylab = "X2")
points(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0))

### The decision boundary does not look linear, looks like an x
# (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)
data$y <- as.factor(data$y)
svm.fit <- svm(y ~ x1 + x2, data, kernel = "linear", cost = 0.01)
preds <- predict(svm.fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))

# (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.
data$y <- as.factor(data$y)
svmnl.fit <- svm(y ~ x1 + x2, data, kernel = "radial", gamma = 1)
preds <- predict(svmnl.fit, data)
plot(data[preds == 0, ]$x1, data[preds == 0, ]$x2, col = (4 - 0), pch = (3 - 0), xlab = "X1", ylab = "X2")
points(data[preds == 1, ]$x1, data[preds == 1, ]$x2, col = (4 - 1), pch = (3 - 1))

# (i) Comment on your results.
### We can see how changing from linear to non linear models with svm and the logistic regression affect the decision boundaries. The changes are very obvious in these examples. we can go from seeing clear cut linear boudaries to non linear boundaries based on the interaction terms.
# 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(ISLR)
var <- ifelse(Auto$mpg > median(Auto$mpg), 1, 0)
Auto$mpglevel <- as.factor(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.
set.seed(11)
tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "linear", ranges = list(cost = c(0.01, 0.1, 1, 5, 10, 100, 1000)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 5
##
## - best performance: 0.01538462
##
## - Detailed performance results:
## cost error dispersion
## 1 1e-02 0.07384615 0.03634338
## 2 1e-01 0.04839744 0.03433628
## 3 1e+00 0.01794872 0.02110955
## 4 5e+00 0.01538462 0.01792836
## 5 1e+01 0.02551282 0.02076457
## 6 1e+02 0.03314103 0.03180827
## 7 1e+03 0.03314103 0.03180827
### A cost of 5 is the best parameters.
# (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(11)
tune.out <- tune(svm, mpglevel ~ ., data = Auto, kernel = "polynomial", ranges = list(cost = c(0.01, 0.1, 1, 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.3032051
##
## - Detailed performance results:
## cost degree error dispersion
## 1 1e-02 2 0.5458333 0.03010509
## 2 1e-01 2 0.5458333 0.03010509
## 3 1e+00 2 0.5458333 0.03010509
## 4 5e+00 2 0.5458333 0.03010509
## 5 1e+01 2 0.5023718 0.08403390
## 6 1e+02 2 0.3032051 0.08201566
## 7 1e-02 3 0.5458333 0.03010509
## 8 1e-01 3 0.5458333 0.03010509
## 9 1e+00 3 0.5458333 0.03010509
## 10 5e+00 3 0.5458333 0.03010509
## 11 1e+01 3 0.5458333 0.03010509
## 12 1e+02 3 0.3362179 0.10473454
## 13 1e-02 4 0.5458333 0.03010509
## 14 1e-01 4 0.5458333 0.03010509
## 15 1e+00 4 0.5458333 0.03010509
## 16 5e+00 4 0.5458333 0.03010509
## 17 1e+01 4 0.5458333 0.03010509
## 18 1e+02 4 0.5458333 0.03010509
### Best cost of 100 with a degree of 2.
# (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)







# 8. 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(11)
train <- sample(nrow(OJ), 800)
OJ.train <- OJ[train, ]
OJ.test <- OJ[-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.
svm.linear <- svm(Purchase ~ ., data = OJ.train, kernel = "linear", cost = 0.01)
summary(svm.linear)
##
## 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: 425
##
## ( 213 212 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
### there are 425 support vectors and 2 classes. 213 belong to the CH and 212 belong to MM
# (c) What are the training and test error rates?
train.pred <- predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 436 52
## MM 76 236
### the train error rates are 0.16
test.pred <- predict(svm.linear, OJ.test)
table(OJ.test$Purchase, test.pred)
## test.pred
## CH MM
## CH 139 26
## MM 27 78
### The test error rates is 0.1964
# (d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(11)
tune.out <- tune(svm, Purchase ~ ., data = OJ.train, kernel = "linear", ranges = list(cost = 10^seq(-2, 1, by = 0.25)))
summary(tune.out)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.3162278
##
## - best performance: 0.15
##
## - Detailed performance results:
## cost error dispersion
## 1 0.01000000 0.16500 0.03106892
## 2 0.01778279 0.16125 0.03304563
## 3 0.03162278 0.15375 0.03634805
## 4 0.05623413 0.15750 0.03291403
## 5 0.10000000 0.15375 0.03335936
## 6 0.17782794 0.15125 0.03143004
## 7 0.31622777 0.15000 0.03227486
## 8 0.56234133 0.15375 0.03438447
## 9 1.00000000 0.15375 0.03387579
## 10 1.77827941 0.15375 0.03335936
## 11 3.16227766 0.15250 0.03216710
## 12 5.62341325 0.15250 0.03216710
## 13 10.00000000 0.15625 0.03596391
### best cost is .3162278
# (e) Compute the training and test error rates using this new value for cost.
svm.linear <- svm(Purchase ~ ., kernel = "linear", data = OJ.train, cost = tune.out$best.parameter$cost)
train.pred <- predict(svm.linear, OJ.train)
table(OJ.train$Purchase, train.pred)
## train.pred
## CH MM
## CH 434 54
## MM 68 244
# (f) Repeat parts (b) through (e) using a support vector machine with a radial kernel. Use the default value for gamma.
# (g) Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
# (h) Overall, which approach seems to give the best results on this data?