# 2. For parts (a) through (c), indicate which of i. through iv. is correct. Justify your answer.
# (a) The lasso, relative to least squares, is:
# iii. Less flexible and hence will give improved prediction accuracy when its increase in bias is less than its decrease in variance, because the lasso reduces flexibility.
# (b) Repeat (a) for ridge regression relative to least squares.
# (a) The lasso, relative to least squares, is:
# iii. Less flexible and hence will give improved prediction accuracy when its increase in bias is less than its decrease in variance, because the ridge regression reduces flexibility and increases prediction accuracy.
# (c) Repeat (a) for non-linear methods relative to least squares.
# (a) The lasso, relative to least squares, is:
# ii. More flexible and hence will give improved prediction accuracy when its increase in variance is less than its decrease in bias.
# 9. In this exercise, we will predict the number of applications received using the other variables in the College data set.
# (a) Split the data set into a training set and a test set.
library(ISLR)
data(College)
set.seed(5)
trainid = sample(1:nrow(College), nrow(College)/2)
train = College[trainid,]
test = College[-trainid,]
# (b) Fit a linear model using least squares on the training set, and report the test error obtained.
college.lm = lm(Apps~., data=train)
lm.pred = predict(college.lm, test)
lm.err = mean((test$Apps - lm.pred)^2)
lm.err
## [1] 1166539
# Test error obtained is 1.166539^6
# (c) Fit a ridge regression model on the training set, with λ chosen by cross-validation. Report the test error obtained.
library(glmnet)
## Loading required package: Matrix
## Loaded glmnet 4.1-4
train.X = model.matrix(Apps ~ ., data = train)
train.Y = train[, "Apps"]
test.X = model.matrix(Apps ~ ., data = test)
test.Y = test[, "Apps"]
grid = 10 ^ seq(4, -2, length=100)
ridge.mod = glmnet(train.X, train.Y, alpha =0, lambda=grid, thresh = 1e-12)
lambda.best = ridge.mod$lambda.min
ridge.pred = predict(ridge.mod, newx= test.X, s=lambda.best)
(ridge.err = mean((test.Y - ridge.pred)^2))
## [1] 1245616
# Test error obtained is 1.245616^6
# (d) Fit a lasso model on the training set, with λ chosen by cross validation. Report the test error obtained, along with the number of non-zero coefficient estimates.
college.mod = glmnet(train.X, train.Y, alpha =1, lambda=grid, thresh = 1e-12)
lasso.cv = cv.glmnet(train.X, train.Y, alpha =1, lambda=grid, thresh = 1e-12)
lambda.best = lasso.cv$lambda.min
lasso.pred = predict(college.mod, newx= test.X, s=lambda.best)
(lasso.err = mean((test.Y - lasso.pred)^2))
## [1] 1166444
# Test error obtained is 1.166444^6
predict(college.mod, s = lambda.best, type="coefficients")
## 19 x 1 sparse Matrix of class "dgCMatrix"
## s1
## (Intercept) -9.700451e+02
## (Intercept) .
## PrivateYes -5.555969e+02
## Accept 1.760150e+00
## Enroll -1.702155e+00
## Top10perc 4.954736e+01
## Top25perc -1.469166e+01
## F.Undergrad 1.341664e-01
## P.Undergrad -1.567447e-03
## Outstate -9.798646e-02
## Room.Board 1.418070e-01
## Books -2.288908e-01
## Personal 2.065975e-01
## PhD -1.527557e+01
## Terminal 2.968185e+00
## S.F.Ratio 4.375440e+01
## perc.alumni 7.699153e-01
## Expend 9.609709e-02
## Grad.Rate 1.053685e+01
# (e) Fit a PCR model on the training set, with M chosen by crossvalidation. Report the test error obtained, along with the value of M selected by cross-validation.
library(pls)
##
## Attaching package: 'pls'
## The following object is masked from 'package:stats':
##
## loadings
college.pcr = pcr(Apps~., data=train, scale=TRUE, validation="CV")
validationplot(college.pcr, val.type="MSEP")

summary(college.pcr)
## Data: X dimension: 388 17
## Y dimension: 388 1
## Fit method: svdpc
## Number of components considered: 17
##
## VALIDATION: RMSEP
## Cross-validated using 10 random segments.
## (Intercept) 1 comps 2 comps 3 comps 4 comps 5 comps 6 comps
## CV 4068 4073 2189 2183 2112 1908 1869
## adjCV 4068 4073 2185 2178 2118 1881 1862
## 7 comps 8 comps 9 comps 10 comps 11 comps 12 comps 13 comps
## CV 1870 1826 1804 1807 1843 1851 1922
## adjCV 1863 1802 1795 1798 1835 1842 1913
## 14 comps 15 comps 16 comps 17 comps
## CV 1942 1576 1430 1246
## adjCV 1978 1546 1412 1234
##
## TRAINING: % variance explained
## 1 comps 2 comps 3 comps 4 comps 5 comps 6 comps 7 comps 8 comps
## X 33.325 57.73 65.26 70.81 76.08 81.02 84.91 87.77
## Apps 1.007 72.25 72.60 75.39 79.89 81.19 81.23 82.43
## 9 comps 10 comps 11 comps 12 comps 13 comps 14 comps 15 comps
## X 90.61 92.97 95.08 96.70 97.72 98.54 99.31
## Apps 82.76 83.18 83.21 83.27 83.75 83.79 91.27
## 16 comps 17 comps
## X 99.79 100.00
## Apps 92.11 93.44
pcr.pred = predict(college.pcr, test, ncomp=10)
(pcr.err = mean((test$Apps - pcr.pred)^2))
## [1] 1795496
# (f) Fit a PLS model on the training set, with M chosen by crossvalidation. Report the test error obtained, along with the value of M selected by cross-validation.
college.pls = plsr(Apps~., data=train, scale=TRUE, validation="CV")
validationplot(college.pls, val.type="MSEP")

pls.pred = predict(college.pls, test, ncomp=10)
(pls.err = mean((test$Apps - pls.pred)^2))
## [1] 1147644
# (g) Comment on the results obtained. How accurately can we predict the number of college applications received? Is there much difference among the test errors resulting from these five approaches?
test.avg = mean(test$Apps)
college.lm.mean =1 - lm.err/mean((test.avg - test$Apps)^2)
college.ridge.mean =1 - ridge.err/mean((test.avg - test$Apps)^2)
college.lasso.mean =1 - lasso.err/mean((test.avg - test$Apps)^2)
college.pcr.2 =1 - pcr.err/mean((test.avg - test$Apps)^2)
college.pls.2 =1 - pls.err/mean((test.avg - test$Apps)^2)
college.all.2 = c(college.lm.mean, college.ridge.mean, college.lasso.mean, college.pcr.2,college.pls.2)
names(college.all.2) = c("lm", "ridge", "lasso", "pcr", "pls")
plot(college.all.2 )

# pcr is the lowest accuracy, the rest show higher accuracies.
# 11. We will now try to predict per capita crime rate in the Boston data set.
library(MASS)
library(leaps)
library(glmnet)
data(Boston)
set.seed(21)
predict.regsubsets = function(object, newdata, id, ...) {
form = as.formula(object$call[[2]])
mat = model.matrix(form, newdata)
coefi = coef(object, id = id)
xvars = names(coefi)
mat[, xvars] %*% coefi
}
k = 10
folds = sample(1:k, nrow(Boston), replace = TRUE)
cv.errors = matrix(NA, k, 13, dimnames = list(NULL, paste(1:13)))
for (j in 1:k) {
best.fit = regsubsets(crim ~ ., data = Boston[folds != j, ], nvmax = 13)
for (i in 1:13) {
pred = predict(best.fit, Boston[folds == j, ], id = i)
cv.errors[j, i] = mean((Boston$crim[folds == j] - pred)^2)
}
}
mean.cv.errors = apply(cv.errors, 2, mean)
plot(mean.cv.errors, type = "b", xlab = "Number of variables", ylab = "CV error")

min(mean.cv.errors)
## [1] 42.46423
# (a) Try out some of the regression methods explored in this chapter, such as best subset selection, the lasso, ridge regression, and PCR. Present and discuss results for the approaches that you consider.
x <- model.matrix(crim ~ ., Boston)[, -1]
y <- Boston$crim
cv.out <- cv.glmnet(x, y, alpha = 1, type.measure = "mse")
plot(cv.out)

cv.out = cv.glmnet(x, y, alpha = 0, type.measure = "mse")
cv.out
##
## Call: cv.glmnet(x = x, y = y, type.measure = "mse", alpha = 0)
##
## Measure: Mean-Squared Error
##
## Lambda Index Measure SE Nonzero
## min 0.54 100 43.19 14.83 13
## 1se 74.44 47 57.92 18.63 13
pcr.fit = pcr(crim ~ ., data = Boston, scale = TRUE, validation = "CV")
validationplot(pcr.fit, val.type = "MSEP")

# (b) Propose a model (or set of models) that seem to perform well on this data set, and justify your answer. Make sure that you are evaluating model performance using validation set error, crossvalidation, or some other reasonable alternative, as opposed to using training error.
#
# (c) Does your chosen model involve all of the features in the data set? Why or why not?
#