Search code examples
rfor-loopautomlr-glue

Glue and For to many models with Automl - R


I want to reproduce this code:

X_train_model1 <- data.table::fread("datasets_atualizados/dataset_y1.csv") %>% 
  h2o::as.h2o()

X_train_model2<- data.table::fread("datasets_atualizados/dataset_y2.csv") %>% 
  h2o::as.h2o()

#Model construction (20 different models)
model_automl <- h2o.automl(x = 1:11, y = 12, training_frame = X_train_model1,
                max_models = 20, seed = 1)

# Save the model
# In this case the leaderboard model is StackedEnsemble_AllModels
model_path <- h2o.saveModel(object = model_automl@leader, path = "models", force=TRUE)

Look like this:

for (i in 1:2) {

  #Exec the model
  model_automl <- h2o.automl(x = 1:11, y = 12, training_frame = glue::glue("X_train_model", {i}),
                               max_models = 20, seed = 1)
  #Saving the model
  h2o.saveModel(object = model_automl@leader, 
                path = paste0("models", i),
                force=TRUE)
}

I sincerely already tried different forms, but I don't conclude this code. Can you help me?


Solution

  • I think {i} is in the wrong place in your code, should be inside the string:

    for (i in 1:2) {
    
      #Exec the model
      model_automl <- h2o.automl(
        x = 1:11, 
        y = 12, 
        training_frame = get(glue::glue("X_train_modelo{i}")),
        max_models = 20, 
        seed = 1
      )
    
      #Saving the model
      h2o.saveModel(object = model_automl@leader, 
                    path = paste0("models", i),
                    force=TRUE)
    }
    

    I understand that you have multiple X_train_modelo objects, so you will need to use get() to refer to them by name.