使用循环来计算不同的Lambda和最小MSE值

时间:2018-10-20 13:41:34

标签: loops regression lasso

我正在尝试以0.1增量在0和1之间的alpha中计算弹性网中的lambda和Min MSE的不同值。我想输出一个包含三列alpha,lambda和min MSE的表格,以及绘制alpha vs min MSE的图表,但是我一直收到错误消息。我的代码如下所示;

`library(ISLR)
library(glmnet)
alpha <- seq(0, 1, by = 0.1)
min_lambda <- NA
for(i in seq_along(alpha)) {
x=model.matrix(Apps~.,College)[,-1] 
y=College$Apps
grid=10^seq(10,-2,length=100)
elnet.mod=glmnet(x,y,alpha=alpha[i],lambda=grid)
set.seed(1)
train=sample(1:nrow(x), nrow(x)/2)
y.test=y[-train]
set.seed(1)
fit.elnet=cv.glmnet(x[train,],y[train],alpha= alpha[i])
min_lambda[i]=fit.elnet$lambda.min
elnet.pred=predict(elnet.mod,s=min_MSE[i],newx=x[-train,])
min_MSE<-mean((elnet.pred-y.test)^2)

}
table(alpha,min_MSE,min_lambda)
plot(alpha,min_MSE)`

我的错误消息是

Error in intI(j, n = x@Dim[2], dn[[2]], give.dn = FALSE) : 
'NA' indices are not (yet?) supported for sparse Matrices
 > table(alpha,min_MSE,min_lambda)
 Error in table(alpha, min_MSE, min_lambda) : 
 all arguments must have the same length
 > plot(alpha,min_MSE)
 Error in xy.coords(x, y, xlabel, ylabel, log) : 
 'x' and 'y' lengths differ

有人可以帮我解决这个问题吗?谢谢

0 个答案:

没有答案