View source: R/model-persistence.R
with_custom_object_scope | R Documentation |
Provide a scope with mappings of names to custom objects
with_custom_object_scope(objects, expr)
objects |
Named list of objects |
expr |
Expression to evaluate |
There are many elements of Keras models that can be customized with
user objects (e.g. losses, metrics, regularizers, etc.). When
loading saved models that use these functions you typically
need to explicitly map names to user objects via the custom_objects
parameter.
The with_custom_object_scope()
function provides an alternative that
lets you create a named alias for a user object that applies to an entire
block of code, and is automatically recognized when loading saved models.
The result from evaluating expr
within the custom object scope.
# define custom metric metric_top_3_categorical_accuracy <- custom_metric("top_3_categorical_accuracy", function(y_true, y_pred) { metric_top_k_categorical_accuracy(y_true, y_pred, k = 3) }) with_custom_object_scope(c(top_k_acc = sparse_top_k_cat_acc), { # ...define model... # compile model (refer to "top_k_acc" by name) model |> compile( loss = "binary_crossentropy", optimizer = optimizer_nadam(), metrics = c("top_k_acc") ) # save the model model |> save_model("my_model.keras") # loading the model within the custom object scope doesn't # require explicitly providing the custom_object reloaded_model <- load_model("my_model.keras") })
Other saving and loading functions:
export_savedmodel.keras.src.models.model.Model()
layer_tfsm()
load_model()
load_model_weights()
register_keras_serializable()
save_model()
save_model_config()
save_model_weights()
Other serialization utilities:
deserialize_keras_object()
get_custom_objects()
get_registered_name()
get_registered_object()
register_keras_serializable()
serialize_keras_object()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.