



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Introduction to Statistical Learning (James/Witten/Hastie/Tibshirani)
Typology: Exercises
1 / 6
This page cannot be seen from the preview
Don't miss anything!
(a). Create a training set containing a random sample of 800 observations, and a test set containing the remaining observations.
library (ISLR) set.seed (1) train = sample ( dim (OJ)[1], 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 re- sponse and the other variables as predictors. Use the summary() function to produce summary statistics, and describe the results obtained.
library (e1071,quietly = T) svm.linear = svm (Purchase ~ ., kernel = "linear", data = OJ.train, cost = 0.01) summary (svm.linear)
(c). What are the training and test error rates?
train.pred = predict (svm.linear, OJ.train) table (OJ.train$Purchase, train.pred)
test.pred = predict (svm.linear, OJ.test) table (OJ.test$Purchase, test.pred)
(d). Use the tune() function to select an optimal cost. Consider values in the range 0.01 to 10.
tune.out = tune (svm, Purchase ~ ., data = OJ.train, kernel = "linear", ranges = list (cost = 10^ seq (-2, 1, by = 0.25))) summary (tune.out)
(e). Compute the training and test error rates using this new value for cost.
test.pred = predict (svm.radial, OJ.test) table (OJ.test$Purchase, test.pred)
tune.out = tune (svm, Purchase ~ ., data = OJ.train, kernel = "radial", ranges = list (cost = 10^ seq (-2, 1, by = 0.25))) summary (tune.out)
svm.radial = svm (Purchase ~ ., data = OJ.train, kernel = "radial", cost = tune.out$best.parameters$cost) train.pred = predict (svm.radial, OJ.train) table (OJ.train$Purchase, train.pred)
test.pred = predict (svm.radial, OJ.test) table (OJ.test$Purchase, test.pred)
(g). Repeat parts (b) through (e) using a support vector machine with a polynomial kernel. Set degree=2.
svm.poly = svm (Purchase ~ ., data = OJ.train, kernel = "poly", degree = 2) summary (svm.poly)
train.pred = predict (svm.poly, OJ.train) table (OJ.train$Purchase, train.pred)
test.pred = predict (svm.poly, OJ.test) table (OJ.test$Purchase, test.pred)
tune.out = tune (svm, Purchase ~ ., data = OJ.train, kernel = "poly", degree = 2, ranges = list (cost = 10^ seq (-2, 1, by = 0.25))) summary (tune.out)