Using dput to save a tidymodels model object

88 views Asked by At

I'm doing an ML course and I'm trying to save a trained model from the course's workspace so that I can reproduce everything on my own computer. So far I've just used dput() on a variable and it has worked perfectly. Now I'm trying to do the same on a model object, which is a decision tree. class(model) yields "_rpart" "model_fit"

When I run dput(model) it all seems to work but when I try to run the copied code I get the following error message: Error in missing_arg() : could not find function "missing_arg"

I can see that the code for the object contains missing_arg() several places like so:

structure(list(lvl = c("yes", "no"), spec = structure(list(args = list(
    cost_complexity = ~1e-10, tree_depth = ~15L, min_n = ~NULL), 
    eng_args = structure(list(), names = character(0), class = c("quosures", 
    "list")), mode = "classification", user_specified_mode = TRUE, 
    method = list(libs = "rpart", fit = list(interface = "formula", 
        protect = c("formula", "data", "weights"), func = c(pkg = "rpart", 
        fun = "rpart"), defaults = list(), args = list(formula = missing_arg(), 
            data = missing_arg(), weights = missing_arg(), cp = ~1e-10, 
            maxdepth = ~15L)), pred = list(class = list(pre = NULL, 
        post = NULL, func = c(fun = "predict"), args = list(object = object$fit, 
            newdata = new_data, type = "class")), prob = list(
        pre = NULL, post = function (x, object) 

Is there a way to save this model using dput(), or something similar, so that I can reproduce all the work on my own computer?

I'm sorry for not having a better reprex...

1

There are 1 answers

2
dufei On

I would always prefer .rds to store any R object compared to dput() (which stores an ASCII text representation of the object). Try

readr::write_rds(model)