Elastic net regression model with loops is not giving me list of results based on alpha R


i would much appreciate some advice

Im currently doing an elastic net regression where I am using a for loop to apply 10 diferents value of alpha from 0 to 1, the thing is that when I ask the results of the models it is only giving me the result of alpha=1, here is my code

sample_size <- floor(0.75 * nrow(data_scaled))
training_index <- sample(seq_len(nrow(data_scaled)), size = sample_size)

train <- data_scaled[training_index, ]
test <- data_scaled[-training_index, ]

x.train <- train[,-3]
y.train<- train[,3]

x.test <- test[,-3]
y.test<- test[,3]

  list.of.fits<- list()
  for (i in 0:10) {
    fit.name<- paste0('alpha', i/10)
    list.of.fits[[fit.name]]<- cv.glmnet(x.train, y.train, type.measure = "mse", alpha= i/10,

results<- data.frame()

for (i in 10) {
  fit.name<- paste0('alpha', 1/10)
  predicted<- predict(list.of.fits[[fit.name]], s=list.of.fits[[fit.name]]$lambda.1se, newx=x.test)

  mse<- mean((y.test-predicted)^2)  

temp<- data.frame(alpha=i/10, mse=mse, fit.name= fit.name)
  results<- rbind(results, temp)

In results it gives me only alpha 1 result, instead of alpha from 0 to 1 (aplha0.1,alpha0.2, alpha0.3...)

>Solution :

Your results for loop will only produce i = 10, try for (i in 1:10) instead of for (i in 10).

Also, in your results loop, your fit.name is fixed at 1/10.

Fixing these issues should resolve your problem.

Leave a ReplyCancel reply