## 如何在LASSO回归中计算交叉验证的R2？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (1194)

``````library(glmnet)
IV1 <- data.frame(IV1 = rnorm(100))
IV2 <- data.frame(IV2 = rnorm(100))
IV3 <- data.frame(IV3 = rnorm(100))
IV4 <- data.frame(IV4 = rnorm(100))
IV5 <- data.frame(IV5 = rnorm(100))
DV <- data.frame(DV = rnorm(100))

data<-data.frame(IV1,IV2,IV3,IV4,IV5,DV)

x <-model.matrix(DV~.-IV5 , data)[,-1]
y <- data\$DV

AB<-glmnet(x=x, y=y, alpha=1)
plot(AB,xvar="lambda")

lambdas = NULL
for (i in 1:100)
{
fit <- cv.glmnet(x,y)
errors = data.frame(fit\$lambda,fit\$cvm)
lambdas <- rbind(lambdas,errors)
}

lambdas <- aggregate(lambdas[, 2], list(lambdas\$fit.lambda), mean)

bestindex = which(lambdas[2]==min(lambdas[2]))
bestlambda = lambdas[bestindex,1]

fit <- glmnet(x,y,lambda=bestlambda)
``````

``````r2<-max(1-fit\$cvm/var(y))
``````

``````Warning message:
In max(1 - fit\$cvm/var(y)) :
no non-missing arguments to max; returning -Inf
``````

### 1 个回答

``````?glmnet
``````

``````?cv.glmnet
``````

``````fit <- cv.glmnet(x,y,lambda=lambdas[,1])

r2<-max(1-fit\$cvm/var(y))
``````

``````for (i in 1:100)
{
fit <- cv.glmnet(x,y)
errors = data.frame(fit\$lambda,fit\$cvm)
lambdas <- rbind(lambdas,errors)
r2[i]<-max(1-fit\$cvm/var(y))
}

lambdas <- aggregate(lambdas[, 2], list(lambdas\$fit.lambda), mean)

bestindex = which(lambdas[2]==min(lambdas[2]))
bestlambda = lambdas[bestindex,1]
r2[bestindex]
``````