Saving workflow of XGBoost model for later use

Viewed 194

I am relatively new to R and therefore sorry in advance if this question is weirdly phrased or unclear.

I build an xgboost model based on the tidymodels framework as demonstrated by Julia in her youtube video about the topic (Tuning XGBoost using tidymodels - YouTube).

The problem I now run into is that I would like to save the model for later use (so I can load it into without building the model again), although I read online that saving it with the saveRDS function might cause compatibility issues in case of package version updates in the future.
A more robust option then seems to be "xgb.save" or "xgb.save.raw", although to utilize this function the model should be of class xgb.booster, while my model is of class workflow.

This leads to a few questions that occur to me:

  1. Does the compatibility issue also arise if the object is of type workflow, or only for objects of type xgb.booster?
  2. Is there a way to convert a workflow to xgb.booster model within the framework of tidymodels that I'm using or should I adress this problem from another angle and try to find a better way to save workflows instead?

I would appreciate a response of any kind.

Below is some of my code to clarify (over_under is my DV and represents over 500 emails/under 500 emails):

xgb_bundes <- boost_tree(
  trees = tune(),
  tree_depth = tune(), 
  sample_size = tune(), 
  mtry = tune(),
  learn_rate = 0.06
) %>%
  set_engine("xgboost") %>%
  set_mode("classification")
xgb_grid <- grid_latin_hypercube(
  trees(),
  tree_depth(),
  sample_size = sample_prop(),
  finalize(mtry(), data_train),
  size = 30
)

xgb_wf_bundes <- workflow() %>%
  add_formula(over_under ~ .) %>% 
  add_model(xgb_bundes)

set.seed(210)
data_fold_cv<- vfold_cv(data_train, v = 10, strata = over_under)

library(doParallel)
cores<-detectCores()

cl <- makeCluster(cores[1]-1)
#Register cluster
registerDoParallel(cl)

set.seed(285)
xgb_bundes_result <- tune_grid(
  xgb_wf_bundes,          
  resamples = data_fold_cv, 
  grid = xgb_grid,          
  control = control_grid(save_pred = T)
)

metrics_results <- xgb_bundes_result %>% collect_metrics()
best <- metrics_results %>% filter(.metric == "accuracy")
final_xgb_bundes <- finalize_workflow(xgb_wf_bundes, best)

model_bundes <- final_xgb_bundes %>% fit(data_train)
class(model_bundes)
[1] "workflow"

xgb.save(model_bundes, "model bundes")

---Which gives the following error:
Error in xgb.save(model_bundes, "model bundes") : model must be xgb.Booster.
0 Answers
Related