Problem predicting from Keras model trained with parnsip

I'm having problems getting a Keras model trained with parsnip to save and load properly.


library(tidymodels)

keras_model <- 
    mlp(hidden_units = 10) %>%
    set_mode("regression") %>% 
    set_engine("keras")

keras_fit <-
keras_model %>%
  fit(objective~., data = data_frame_train)

#This works
predict(keras_fit, new_data = data_frame_test)

saveRDS(keras_fit,"keras_fit.RDS")

Open a new RStudio session:


library(tidymodels)

keras_fit <- readRDS("keras_fit.RDS")

predict(keras_fit, new_data = data_frame_new)

And I get the following error message:


Error in do.call(object$predict, args) : 
  'what' must be a function or character string

I saved data_frame_new into a feather file and loaded it into the RStudio session where I fit keras_fit and the predict call worked fine, so it seems like the problem is with the saveRDS/readRDS step. Any help would be appreciated, thanks.

I believe I've solved this, documenting here in case someone else has the same problem as me.

In the new session:

keras_fit$fit
<pointer: 0x0>

In other words, the model fit doesn't made it into the RDS file.

In the original session, run:


save_model_hdf5(keras_fit$fit, "keras_fit_fit.hdf5")

In the new session:


keras_fit$fit <- load_model_hdf5( "keras_fit_fit.hdf5")

And now the predict() function works.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.