Skip to content
Prev 395332 / 398502 Next

running crossvalidation many times MSE for Lasso regression

Dear Rui,

I really thank you a lot for your response and your R code.

Best,

Sacha


Le mardi 24 octobre 2023 ? 16:37:56 UTC+2, Rui Barradas <ruipbarradas at sapo.pt> a ?crit : 





?s 20:12 de 23/10/2023, varin sacha via R-help escreveu:
Hello,

In your OP, the following two code lines are where that error comes from.


predictLasso=predict(cv_model, newx=test1)

ypred=predict(predictLasso,newdata=test1)



predictLasso already are predictions, it's the output of predict. So 
when you run the 2nd line above you are passing it a matrix, not a 
fitted model, and the error is thrown.

After the several suggestion in this thread, don't you want something 
like this instead of your for loop?


# make the results reproducible
set.seed(2023)
# this is better than what you had
z <- TT[c("x1", "x2")] |> as.matrix()
y <- TT[["y"]]
cv_model <- cv.glmnet(z, y, alpha = 1, type.measure = "mse")

best_lambda <- cv_model$lambda.min
best_lambda


# these two values should be the same, and they are
# index to minimum mse
(i <- cv_model$index[1])
which(cv_model$lambda == cv_model$lambda.min)

# these two values should be the same, and they are
# value of minimum mse
cv_model$cvm[i]
min(cv_model$cvm)

plot(cv_model)



Hope this helps,

Rui Barradas