rtidymodelsr-rangerr-parsnip

How to save a parsnip model fit (from ranger)?


I have a parsnip model (from ranger), roughly from here:

# install.packages("tidymodels")

data(cells, package = "modeldata")

rf_mod <- 
  rand_forest(trees = 100) %>% 
  set_engine("ranger") %>% 
  set_mode("classification")

set.seed(123)
cell_split <- initial_split(cells %>% select(-case), strata = class)

cell_train <- training(cell_split)

rf_fit <- 
  rf_mod %>% 
  fit(class ~ ., data = cell_train)
> class(rf_fit)
[1] "_ranger"   "model_fit"

How do I save it to disk so that I can load it at a later time?

I tried dput, and that gets an error:

dput(rf_fit, file="rf_fit.R")
rf_fit2 <- dget("rf_fit.R")
Error in missing_arg() : could not find function "missing_arg"

It's true, the model_fit.R file has a couple of missing_arg calls in it, which appears to be some sort of way to mark missing args. However, that's a side line. I don't need to use dput, I just want to be able to save and load a model.


Solution

  • Try with this option. save() and load() functions allow you to store the model and then inkove it again. Here the code:

    data(cells, package = "modeldata")
    
    rf_mod <- 
      rand_forest(trees = 100) %>% 
      set_engine("ranger") %>% 
      set_mode("classification")
    
    set.seed(123)
    cell_split <- initial_split(cells %>% select(-case), strata = class)
    
    cell_train <- training(cell_split)
    
    rf_fit <- 
      rf_mod %>% 
      fit(class ~ ., data = cell_train)
    
    #Export option
    save(rf_fit,file='Mymod.RData')
    load('Mymod.RData')
    

    The other option would be using saveRDS() to save the model and then use readRDS() to load it but it requires to be allocated in an object:

    #Export option 2
    saveRDS(rf_fit, file = "Mymod.rds")
    # Restore the object
    rf_fit <- readRDS(file = "Mymod.rds")