Skip to contents

Loads a model saved via save_model().

Usage

load_model(model, custom_objects = NULL, compile = TRUE, safe_mode = TRUE)

Arguments

model

string, path to the saved model file, or a raw vector, as returned by save_model(filepath = NULL)

custom_objects

Optional named list mapping names to custom classes or functions to be considered during deserialization.

compile

Boolean, whether to compile the model after loading.

safe_mode

Boolean, whether to disallow unsafe lambda deserialization. When safe_mode=FALSE, loading an object has the potential to trigger arbitrary code execution. This argument is only applicable to the Keras v3 model format. Defaults to TRUE.

Value

A Keras model instance. If the original model was compiled, and the argument compile = TRUE is set, then the returned model will be compiled. Otherwise, the model will be left uncompiled.

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)
))

Note that the model variables may have different name values (var$name property, e.g. "dense_1/kernel:0") after being reloaded. It is recommended that you use layer attributes to access specific variables, e.g. model |> get_layer("dense_1") |> _$kernel.