Skip to contents

Saves a model as a .keras file.

Usage

save_model(model, filepath = NULL, overwrite = FALSE, ...)

Arguments

model

A keras model.

filepath

string, Path where to save the model. Must end in .keras.

overwrite

Whether we should overwrite any existing model at the target location, or instead ask the user via an interactive prompt.

...

For forward/backward compatability.

Value

If filepath is provided, then this function is called primarily for side effects, and model is returned invisibly. If filepath is not provided or NULL, then the serialized model is returned as an R raw vector.

Examples

model <- keras_model_sequential(input_shape = c(3)) |>
  layer_dense(5) |>
  layer_activation_softmax()

model |> save_model("model.keras")
loaded_model <- load_model("model.keras")

x <- random_uniform(c(10, 3))
stopifnot(all.equal(
  model |> predict(x),
  loaded_model |> predict(x)
))

The saved .keras file contains:

  • The model's configuration (architecture)

  • The model's weights

  • The model's optimizer's state (if any)

Thus models can be reinstantiated in the exact same state.

zip::zip_list("model.keras")[, "filename"]

## [1] "metadata.json"    "config.json"      "model.weights.h5"