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.
(5.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:
set.seed(421)
n = 500
p = 2
x1=runif (n) - 0.5
x2=runif (n) - 0.5
y=1*(x1^p-x2^p > 0)
(5.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(x1[y == 0], x2[y == 0], xlab = "X1", ylab = "X2", col="yellow", pch = "0")
points(x1[y == 1], x2[y == 1], pch = "1")
(5.c) Fit a logistic regression model to the data, using \(X_1\) and \(X_2\) as predictors.
glm.model = glm(y ~ x1 + x2, family = binomial)
(5.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 = data.frame(x1 = x1, x2 = x2, y = y)
glm.prob = predict(glm.model, df, type = "response")
glm.pred = ifelse(glm.prob > 0.54, 1, 0)
pos = df[glm.pred == 1, ]
neg = df[glm.pred == 0, ]
plot(pos$x1, pos$x2,
xlab = "X1",
ylab = "X2",
pch = "1")
points(neg$x1, neg$x2,
col = "yellow",
pch = "0")
(5.e) Now fit a logistic regression model to the data using non-linear functions of $X_1 $ and $X_2 $ as predictors (e.g. \(X_1^{2}\) , \(X_1 * X_2\), log( \(X_2\)), and so forth).
poly.model = glm(y ~ poly(x1, 2) +
poly(x1, 3) +
poly(x1, 4) +
poly(x2, 2) +
poly(x2, 3) +
poly(x2, 4) +
#log(x1) +
#log(x2) +
I(x1 * x2), data = df, family = binomial)
poly.step = step(poly.model, direction="both",test="Chisq", trace = F); #poly.step
(5.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.
poly.prob = predict(poly.model, df, type = "response")
poly.pred = ifelse(poly.prob > 0.50, 1, 0)
pos2 = df[poly.pred == 1, ]
neg2 = df[poly.pred == 0, ]
plot(pos2$x1, pos2$x2,
xlab = "X1",
ylab = "X2",
pch = "1")
points(neg2$x1, neg2$x2,
col = "yellow",
pch = "0")
(5.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.linear.model = svm(as.factor(y) ~ x1 + x2, df, kernel = "linear")
svm.linear.pred = predict(svm.linear.model, df)
pos3 = df[svm.linear.pred == 1, ]
neg3 = df[svm.linear.pred == 0, ]
plot(pos3$x1, pos3$x2,
xlab = "X1",
ylab = "X2",
pch = "1")
points(neg3$x1, neg3$x2,
col = "yellow",
pch = "0")
(5.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.radial.model = svm(as.factor(y) ~ x1 + x2, df); #summary(svm.radial.model)
svm.radial.pred = predict(svm.radial.model, df)
pos4 = df[svm.radial.pred == 1, ]
neg4 = df[svm.radial.pred == 0, ]
plot(pos4$x1, pos4$x2,
xlab = "X1",
ylab = "X2",
pch = "1")
points(neg4$x1, neg4$x2,
col = "yellow",
pch = "0")
(5.i) Comment on your results.
(5.i) Comment: When it comes to non-linear data, basic glm and linear kernel SVM models struggle with finding the decision boundary. Including non-linear terms and/or interactions in glm models can work but takes some trial and error. Tuned SVM with non-linear kernels seem to work easiest and fastest on non-linear decision boundaries.
(7.0) 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..
data(Auto)
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 ...
(7.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.
above_median = ifelse(Auto$mpg > (median(Auto$mpg)), 1, 0)
Auto$mpg_above_median = as.factor(above_median)
str(Auto)
## 'data.frame': 392 obs. of 10 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 ...
## $ mpg_above_median: Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
(7.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.linear.tune = tune(svm,
mpg_above_median ~ .,
data = Auto,
kernel = "linear",
ranges = list(cost = seq(0.25,2.5, 0.25))); summary(svm.linear.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.75
##
## - best performance: 0.01025641
##
## - Detailed performance results:
## cost error dispersion
## 1 0.25 0.02557692 0.02093679
## 2 0.50 0.01282051 0.01813094
## 3 0.75 0.01025641 0.01792836
## 4 1.00 0.01025641 0.01792836
## 5 1.25 0.01025641 0.01792836
## 6 1.50 0.01025641 0.01792836
## 7 1.75 0.01282051 0.02179068
## 8 2.00 0.01282051 0.02179068
## 9 2.25 0.01282051 0.02179068
## 10 2.50 0.01282051 0.02179068
svm.linear.tune$best.parameters$cost
## [1] 0.75
(7.b) Comment: For the tuned linear svm the best performance (lowest cv error = 0.01025641) seen at costs between 0.75 - 1.50
(7.c) Now repeat (7.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.radial.tune = tune(svm,
mpg_above_median ~ .,
data = Auto,
kernel = "radial",
ranges = list(cost = seq(15,25,5),
gamma = seq(0.00,0.02,0.01))); summary(svm.radial.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 20 0.01
##
## - best performance: 0.01025641
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 15 0.00 0.55115385 0.04366593
## 2 20 0.00 0.55115385 0.04366593
## 3 25 0.00 0.55115385 0.04366593
## 4 15 0.01 0.01538462 0.01792836
## 5 20 0.01 0.01025641 0.01792836
## 6 25 0.01 0.01282051 0.01813094
## 7 15 0.02 0.01282051 0.01813094
## 8 20 0.02 0.02051282 0.02648194
## 9 25 0.02 0.01794872 0.02110955
set.seed(1)
svm.polynomial.tune = tune(svm,
mpg_above_median ~ .,
data = Auto,
kernel = "polynomial",
ranges = list(cost = seq(10,13,1),
degree = c(2,3))); summary(svm.polynomial.tune)
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost degree
## 12 2
##
## - best performance: 0.4825
##
## - Detailed performance results:
## cost degree error dispersion
## 1 10 2 0.5130128 0.08963366
## 2 11 2 0.4952564 0.09619477
## 3 12 2 0.4825000 0.10506480
## 4 13 2 0.4902564 0.08752957
## 5 10 3 0.5511538 0.04366593
## 6 11 3 0.5511538 0.04366593
## 7 12 3 0.5511538 0.04366593
## 8 13 3 0.5511538 0.04366593
(7.c) Comment: The tuned radial svm best performance (lowest cv error = 0.01025641) seen at costs=20, gamma=0.01. The tuned poly svm best performance (lowest cv error = 0.4825000) seen at costs=12, degree=2.
(7.d) Make some plots to back up your assertions in (7.b) and (7.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(1)
svm.linear = svm(mpg_above_median ~ .,
data = Auto,
kernel = "linear",
cost = svm.linear.tune$best.parameters$cost)
svm.poly = svm(mpg_above_median ~ .,
data = Auto,
kernel = "polynomial",
cost = svm.polynomial.tune$best.parameters$cost,
degree = svm.polynomial.tune$best.parameters$degree)
svm.radial = svm(mpg_above_median ~ .,
data = Auto,
kernel = "radial",
cost = svm.radial.tune$best.parameters$cost,
gamma = svm.radial.tune$best.parameters$gamma)
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[2])))
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[3])))
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[4])))
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[5])))
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[6])))
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[7])))
plot(svm.linear, Auto, as.formula(paste("mpg~", names(Auto)[8])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[2])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[3])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[4])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[5])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[6])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[7])))
plot(svm.poly, Auto, as.formula(paste("mpg~", names(Auto)[8])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[2])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[3])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[4])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[5])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[6])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[7])))
plot(svm.radial, Auto, as.formula(paste("mpg~", names(Auto)[8])))
(8.0) This problem involves the OJ data set which is part of the ISLR package.
data("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 ...
(8.a) Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations..
set.seed(1)
train_indicator = sample(dim(OJ)[1], 800)
train = OJ[train_indicator, ]
test = OJ[-train_indicator, ]
(8.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.linear = svm(Purchase ~ .,
kernel = "linear",
data = train,
cost = 0.01); summary(oj.svm.linear)
##
## 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: 435
##
## ( 219 216 )
##
##
## Number of Classes: 2
##
## Levels:
## CH MM
(8.c) What are the training and test error rates?
train.pred = predict(oj.svm.linear, train)
test.pred = predict(oj.svm.linear, newdata=test)
(sum(train$Purchase != train.pred))/length(train.pred)
## [1] 0.175
(sum(test$Purchase != test.pred))/length(test.pred)
## [1] 0.1777778
(8.c) Answer: The training error rate is 0.175 and the testing error rate is 0.178.
(8.d) Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
set.seed(1)
oj.svm.linear.tune = tune(svm,
Purchase ~ .,
data = train,
kernel = "linear",
ranges = list(cost = seq(0.1, 10, by = 0.1)))
oj.svm.linear.tune$best.parameters$cost
## [1] 0.5
(8.e) Compute the training and test error rates using this new value for cost.
set.seed(1)
oj.svm.linear = svm(Purchase ~ .,
kernel = "linear",
data = train,
cost = oj.svm.linear.tune$best.parameters$cost)
oj.svm.linear.train.pred = predict(oj.svm.linear, train); (sum(train$Purchase != oj.svm.linear.train.pred))/length(oj.svm.linear.train.pred)
## [1] 0.165
oj.svm.linear.test.pred = predict(oj.svm.linear, newdata = test); (sum(test$Purchase != oj.svm.linear.test.pred))/length(oj.svm.linear.test.pred)
## [1] 0.1555556
(8.f) Repeat parts (8.b) through (8.e) using a support vector machine with a radial kernel. Use the default value for gamma
set.seed(1)
oj.svm.radial = svm(Purchase ~ .,
data = train,
kernel = "radial"); #summary(svm.radial)
train.pred = predict(oj.svm.radial, train)
test.pred = predict(oj.svm.radial, newdata=test)
(sum(train$Purchase != train.pred))/length(train.pred)
## [1] 0.15125
(sum(test$Purchase != test.pred))/length(test.pred)
## [1] 0.1851852
oj.svm.radial.tune = tune(svm,
Purchase ~ .,
data = train,
kernel = "radial",
ranges = list(cost = seq(0.1, 10, by = 0.1)))
oj.svm.radial = svm(Purchase ~ .,
kernel = "radial",
data = train,
cost = oj.svm.radial.tune$best.parameters$cost)
oj.svm.radial.train.pred = predict(oj.svm.radial, train); (sum(train$Purchase != oj.svm.radial.train.pred))/length(oj.svm.radial.train.pred)
## [1] 0.15
oj.svm.radial.test.pred = predict(oj.svm.radial, newdata = test); (sum(test$Purchase != oj.svm.radial.test.pred))/length(oj.svm.radial.test.pred)
## [1] 0.1851852
(8.g) Repeat parts (8.b) through (8.e) using a support vector machine with a polynomial kernel. Set degree=2.
set.seed(1)
oj.svm.polynomial = svm(Purchase ~ .,
data = train,
kernel = "polynomial"); #summary(svm.polynomial)
train.pred = predict(oj.svm.polynomial, train)
test.pred = predict(oj.svm.polynomial, newdata=test)
(sum(train$Purchase != train.pred))/length(train.pred)
## [1] 0.15375
(sum(test$Purchase != test.pred))/length(test.pred)
## [1] 0.2222222
oj.svm.polynomial.tune = tune(svm,
Purchase ~ .,
data = train,
kernel = "polynomial",
degree = 2,
ranges = list(cost = seq(0.1, 10, by = 0.1)))
oj.svm.polynomial = svm(Purchase ~ .,
kernel = "polynomial",
data = train,
cost = oj.svm.polynomial.tune$best.parameters$cost,
degree = 2)
oj.svm.polynomial.train.pred = predict(oj.svm.polynomial, train); (sum(train$Purchase != oj.svm.polynomial.train.pred))/length(oj.svm.polynomial.train.pred)
## [1] 0.15625
oj.svm.polynomial.test.pred = predict(oj.svm.polynomial, newdata = test); (sum(test$Purchase != oj.svm.polynomial.test.pred))/length(oj.svm.polynomial.test.pred)
## [1] 0.2074074
(8.h) Overall, which approach seems to give the best results on this data?
df <- data.frame(
kernel=c('linear', 'radial', 'polynomial'),
train=c((sum(train$Purchase != oj.svm.linear.train.pred))/length(oj.svm.linear.train.pred),
(sum(train$Purchase != oj.svm.radial.train.pred))/length(oj.svm.radial.train.pred),
(sum(train$Purchase != oj.svm.polynomial.train.pred))/length(oj.svm.polynomial.train.pred)),
test=c((sum(test$Purchase != oj.svm.linear.test.pred))/length(oj.svm.linear.test.pred),
(sum(test$Purchase != oj.svm.radial.test.pred))/length(oj.svm.radial.test.pred),
(sum(test$Purchase != oj.svm.polynomial.test.pred))/length(oj.svm.polynomial.test.pred))); df
(8.h) Answer: Overall the linear kernel seems to give the best results on this data.