Error message in R:
Error in cv.glmnet(x[train, ], y[train], alpha = 0) :
could not find function "cv.glmnet"
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
In addition: Warning messages:
1: package 'knitr' was built under R version 3.6.3
2: package 'ISLR' was built under R version 3.6.3
3: In block_exec(params) :
Failed to tidy R code in chunk 'unnamed-chunk-2'. Reason:
Error in loadNamespace(name) : there is no package called 'formatR'
4: In block_exec(params) :
Failed to tidy R code in chunk 'unnamed-chunk-3'. Reason:
Error in loadNamespace(name) : there is no package called 'formatR'
5: In block_exec(params) :
Failed to tidy R code in chunk 'unnamed-chunk-4'. Reason:
Error in loadNamespace(name) : there is no package called 'formatR'
Execution halted
---
title: "HW3"
author:
- Me
header-includes:
- \usepackage{bbm}
- \usepackage{amssymb}
- \usepackage{amsmath}
- \usepackage{graphicx}
- \usepackage{natbib}
- \usepackage{float}
- \floatplacement{figure}{H}
output:
pdf_document: default
fontsize: 11pt
---
```{r, echo=FALSE, warning=FALSE}
library(knitr); library(ISLR)
opts_chunk$set(tidy.opts=list(width.cutoff=60),tidy=TRUE)
```
# 1. Exercise 9(a), 9(b), 9(c), 9(d) and 9(g) in Section 6.8 of the Text. Please run `set.seed(1)` before you run any other codes, so that your results are reproducible for grading. Please answer 9(g) with respect to the results obtained in 9(a), 9(b), 9(c) and 9(d). The `College` data set is in the library `ISLR`
```{r}
set.seed(1)
data(College)
n = 1:nrow(College)
train = sample(n, 777*.7)
index = n[-train]
test = sample(index, 777*.3)
train_set = College[train, ]
test_set = College[test, ]
summary(College)
```
```{r}
lm.fit = lm(Apps~., data = train_set)
p = predict(lm.fit, test_set)
MSE = mean((p - test_set$Apps)^2)
MSE
```
```{r}
x=model.matrix(Apps~.,College)[,-1]
y=College$Apps
set.seed(1)
train=sample(1:nrow(x), nrow(x)/2)
test=(-train)
y.test=y[test]
cv.out=cv.glmnet(x[train,],y[train],alpha=0)
plot(cv.out)
bestlam=cv.out$lambda.min
bestlam
ridge.pred=predict(ridge.mod,s=bestlam,newx=x[test,])
MSE = mean((ridge.pred-y.test)^2)
out=glmnet(x,y,alpha=0)
predict(out,type="coefficients",s=bestlam)[1:18,]
MSE
```
```{r}
lasso.mod=glmnet(x[train,],y[train],alpha=1,lambda=grid)
plot(lasso.mod)
set.seed(1)
cv.out=cv.glmnet(x[train,],y[train],alpha=1)
plot(cv.out)
bestlam=cv.out$lambda.min
lasso.pred=predict(lasso.mod,s=bestlam,newx=x[test,])
MSE = mean((lasso.pred-y.test)^2)
MSE
out=glmnet(x,y,alpha=1,lambda=grid)
lasso.coef=predict(out,type="coefficients",s=bestlam)[1:18,]
lasso.coef
lasso.coef[lasso.coef!=0]
```