Search code examples
rtidymodels

Recommended approach to change the engine in a tidymodels workflow


I'm using tidymodels to train and test a Naive Bayes model and predict new data from it.

For training and testing, I've set up the tidymodels workflow as follows:

model_recipe <- recipes::recipe(OUTCOME ~ ., data = dat_train)

model_final <- parsnip::naive_Bayes(Laplace = 1) |>
  parsnip::set_mode("classification") |>
  parsnip::set_engine("klaR", usekernel = FALSE)

model_final_wf <- workflows::workflow() |>
  workflows::add_recipe(model_recipe) |>
  workflows::add_model(model_final)

Now, when I have done my training and testing I want to fit the model, but now do one tiny specification in the set_engine part, i.e. I want to change the priors for each outomce class.

My question is, what is the best way to do this tiny change? Is there an easy way where I can just take my full workflow and update the engine or do I need to re-run the whole engine/workflow part as shown below?

model_final <- parsnip::naive_Bayes(Laplace = 1) |>
  parsnip::set_mode("classification") |>
  parsnip::set_engine("klaR", usekernel = FALSE,
                      prior = rep(0.2, 5))

model_final_wf <- workflows::workflow() |>
  workflows::add_recipe(model_recipe) |>
  workflows::add_model(model_final)

Solution

  • You can just update the engine information (instead of the whole object).

    Similarly, you can update just the model in the workflow.

    model_recipe <- recipes::recipe(OUTCOME ~ ., data = dat_train)
    
    model_final <- parsnip::naive_Bayes(Laplace = 1) |>
      parsnip::set_mode("classification") |>
      parsnip::set_engine("klaR", usekernel = FALSE)
    
    model_final_wf <- workflows::workflow() |>
      workflows::add_recipe(model_recipe) |>
      workflows::add_model(model_final)
    
    # Update the engine parameters via another `set_engine()`
    model_final_final <- 
      model_final %>% 
      set_engine("klaR", usekernel = TRUE)
    
    # Copy the workflow and update with new model spec
    model_final_final_wf <- model_final_final_wf |>
     update_model(model_final_final)