For parts (a) through (c), indicate which of i. through iv. is correct. Justify your answer.
Statement iii is correct - lasso applies a penalty restricting model flexibility. Variance decreases and bias increases as a result.
Statement iii is correct - lasso applies a penalty restricting model flexibility. Variance decreases and bias increases as a result.
Statement ii is correct - nonlinear models are usually more flexible than linear models. Variance increases and bias decreases as a result.
In this exercise, we will predict the number of applications received using the other variables in the College data set.
library(ISLR)
##
## Attaching package: 'ISLR'
## The following objects are masked from 'package:ISLR2':
##
## Auto, Credit
library(MASS)
library(leaps)
library(glmnet)
## Loading required package: Matrix
##
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
## Loaded glmnet 4.1-8
library(pls)
##
## Attaching package: 'pls'
## The following object is masked from 'package:stats':
##
## loadings
library(caTools)
set.seed(15)
college_data = sample(777, 500, replace=FALSE)
train = College[college_data,]
test = College[-college_data,]
lm.college = lm(Apps~., train)
predict.college = predict(lm.college, test)
error.lm.college = mean((predict.college-test$Apps)^2)
mean((predict.college-test$Apps)^2)
## [1] 1593075
grid = 10^seq(10,-2, length=100)
train = sample(777, 500, replace=FALSE)
test = -train
x = model.matrix(Apps~., College)[,-1]
y = College$Apps
ridge.mod = glmnet(x[train,],y[train], alpha=0, lambda=grid)
cv.out = cv.glmnet(x[train,],y[train], alpha=0)
bestlam = cv.out$lambda.min
ridge.pred = predict(ridge.mod, s=bestlam, newx=x[test,])
err.ridge = mean((ridge.pred-y[test])^2)
mean((ridge.pred-y[test])^2)
## [1] 2727719
lasso.mod = glmnet(x[train,],y[train], alpha=1, lambda=grid)
cv.out.2 = cv.glmnet(x[train,],y[train], alpha=1)
bestlam.2 = cv.out.2$lambda.min
lasso.pred = predict(lasso.mod,s=bestlam.2,newx=x[test,])
err.lasso = mean((lasso.pred-y[test])^2)
mean((lasso.pred-y[test])^2)
## [1] 1665872
coef.lasso = predict(lasso.mod, type="coefficients", s=bestlam.2, newx=x[test,])
length(coef.lasso[coef.lasso!=0])
## [1] 14
The ridge regression model’s error was the largest at 2727719. The other two models’ errors were similar, but linear model’s error was the smallest at 1593075.