ยป Keras API reference / Utilities / Serialization utilities

Serialization utilities

CustomObjectScope class

tf.keras.utils.custom_object_scope(*args)

Exposes custom classes/functions to Keras deserialization internals.

Under a scope with custom_object_scope(objects_dict), Keras methods such as tf.keras.models.load_model or tf.keras.models.model_from_config will be able to deserialize any custom object referenced by a saved config (e.g. a custom layer or metric).

Example

Consider a custom regularizer my_regularizer:

layer = Dense(3, kernel_regularizer=my_regularizer)
config = layer.get_config()  # Config contains a reference to `my_regularizer`
...
# Later:
with custom_object_scope({'my_regularizer': my_regularizer}):
  layer = Dense.from_config(config)

Arguments

  • *args: Dictionary or dictionaries of {name: object} pairs.

get_custom_objects function

tf.keras.utils.get_custom_objects()

Retrieves a live reference to the global dictionary of custom objects.

Updating and clearing custom objects using custom_object_scope is preferred, but get_custom_objects can be used to directly access the current collection of custom objects.

Example

get_custom_objects().clear()
get_custom_objects()['MyObject'] = MyObject

Returns

Global dictionary of names to classes (_GLOBAL_CUSTOM_OBJECTS).


register_keras_serializable function

tf.keras.utils.register_keras_serializable(package="Custom", name=None)

Registers an object with the Keras serialization framework.

This decorator injects the decorated class or function into the Keras custom object dictionary, so that it can be serialized and deserialized without needing an entry in the user-provided custom object dict. It also injects a function that Keras will call to get the object's serializable string key.

Note that to be serialized and deserialized, classes must implement the get_config() method. Functions do not have this requirement.

The object will be registered under the key 'package>name' where name, defaults to the object name if not passed.

Arguments

  • package: The package that this class belongs to.
  • name: The name to serialize this class under in this package. If None, the class' name will be used.

Returns

A decorator that registers the decorated class with the passed names.


serialize_keras_object function

tf.keras.utils.serialize_keras_object(instance)

Serialize a Keras object into a JSON-compatible representation.


deserialize_keras_object function

tf.keras.utils.deserialize_keras_object(
    identifier, module_objects=None, custom_objects=None, printable_module_name="object"
)

Turns the serialized form of a Keras object back into an actual object.