exposes custom classesfunctions to keras deserialization internals under a scope with customobjectscopeobjectsdict keras methods such as keras models loadmodel or keras models modelfromconfig 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 myregularizer python layer dense3 kernelregularizermyregularizer config contains a reference to myregularizer config layer getconfig later with customobjectscope myregularizer myregularizer layer dense fromconfigconfig args customobjects dictionary of name object pairs alias retrieves a live reference to the global dictionary of custom objects custom objects set using using customobjectscope are not added to the global dictionary of custom objects and will not appear in the returned dictionary example python getcustomobjects clear getcustomobjects myobject myobject returns global dictionary mapping registered class names to classes 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 userprovided 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 getconfig method functions do not have this requirement the object will be registered under the key packagename where name defaults to the object name if not passed example python note that mypackage is used as the package argument here and since the name argument is not provided mydense is used as the name registerkerasserializable mypackage class mydensekeras layers dense pass assert getregisteredobject mypackagemydense mydense assert getregisterednamemydense mypackagemydense args package the package that this class belongs to this is used for the key which is packagename to idenfify the class note that this is the first argument passed into the decorator name the name to serialize this class under in this package if not provided or none the class name will be used note that this is the case when the decorator is used with only one argument which becomes the package returns a decorator that registers the decorated class with the passed names registers a class with the keras serialization framework classname name if name is not none else arg name registeredname package classname if inspect isclassarg and not hasattrarg getconfig raise valueerror cannot register a class that does not have a getconfig method globalcustomobjectsregisteredname arg globalcustomnamesarg registeredname return arg return decorator kerasexport keras saving getregisteredname keras utils getregisteredname def getregisterednameobj if obj in globalcustomnames return globalcustomnamesobj else return obj name kerasexport keras saving getregisteredobject keras utils getregisteredobject def getregisteredobjectname customobjectsnone moduleobjectsnone customobjectsscopedict globalstate getglobalattribute customobjectsscopedict if name in customobjectsscopedict return customobjectsscopedictname elif name in globalcustomobjects return globalcustomobjectsname elif customobjects and name in customobjects return customobjectsname elif moduleobjects and name in moduleobjects return moduleobjectsname return none exposes custom classes functions to keras deserialization internals under a scope with custom_object_scope objects_dict keras methods such as keras models load_model or 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 python layer dense 3 kernel_regularizer my_regularizer config contains a reference to my_regularizer config layer get_config later with custom_object_scope my_regularizer my_regularizer layer dense from_config config args custom_objects dictionary of name object pairs alias retrieves a live reference to the global dictionary of custom objects custom objects set using using custom_object_scope are not added to the global dictionary of custom objects and will not appear in the returned dictionary example python get_custom_objects clear get_custom_objects myobject myobject returns global dictionary mapping registered class names to classes 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 example python note that my_package is used as the package argument here and since the name argument is not provided mydense is used as the name register_keras_serializable my_package class mydense keras layers dense pass assert get_registered_object my_package mydense mydense assert get_registered_name mydense my_package mydense args package the package that this class belongs to this is used for the key which is package name to idenfify the class note that this is the first argument passed into the decorator name the name to serialize this class under in this package if not provided or none the class name will be used note that this is the case when the decorator is used with only one argument which becomes the package returns a decorator that registers the decorated class with the passed names registers a class with the keras serialization framework returns the name registered to an object within the keras framework this function is part of the keras serialization and deserialization framework it maps objects to the string names associated with those objects for serialization deserialization args obj the object to look up returns the name associated with the object or the default python name if the object is not registered returns the class associated with name if it is registered with keras this function is part of the keras serialization and deserialization framework it maps strings to the objects associated with them for serialization deserialization example python def from_config cls config custom_objects none if my_custom_object_name in config config hidden_cls tf keras saving get_registered_object config my_custom_object_name custom_objects custom_objects args name the name to look up custom_objects a dictionary of custom objects to look the name up in generally custom_objects is provided by the user module_objects a dictionary of custom objects to look the name up in generally module_objects is provided by midlevel library implementers returns an instantiable class associated with name or none if no such class exists
import inspect

from keras.api_export import keras_export
from keras.backend.common import global_state

GLOBAL_CUSTOM_OBJECTS = {}
GLOBAL_CUSTOM_NAMES = {}


@keras_export(
    [
        "keras.saving.CustomObjectScope",
        "keras.saving.custom_object_scope",
        "keras.utils.CustomObjectScope",
        "keras.utils.custom_object_scope",
    ]
)
class CustomObjectScope:
    

    def __init__(self, custom_objects):
        self.custom_objects = custom_objects or {}
        self.backup = None

    def __enter__(self):
        self.backup = global_state.get_global_attribute(
            "custom_objects_scope_dict", {}
        ).copy()
        global_state.set_global_attribute(
            "custom_objects_scope_dict", self.custom_objects.copy()
        )
        return self

    def __exit__(self, *args, **kwargs):
        global_state.set_global_attribute(
            "custom_objects_scope_dict", self.backup.copy()
        )



custom_object_scope = CustomObjectScope


@keras_export(
    [
        "keras.saving.get_custom_objects",
        "keras.utils.get_custom_objects",
    ]
)
def get_custom_objects():
    
    return GLOBAL_CUSTOM_OBJECTS


@keras_export(
    [
        "keras.saving.register_keras_serializable",
        "keras.utils.register_keras_serializable",
    ]
)
def register_keras_serializable(package="Custom", name=None):
    

    def decorator(arg):
        
        class_name = name if name is not None else arg.__name__
        registered_name = package + ">" + class_name

        if inspect.isclass(arg) and not hasattr(arg, "get_config"):
            raise ValueError(
                "Cannot register a class that does not have a "
                "get_config() method."
            )

        GLOBAL_CUSTOM_OBJECTS[registered_name] = arg
        GLOBAL_CUSTOM_NAMES[arg] = registered_name

        return arg

    return decorator


@keras_export(
    [
        "keras.saving.get_registered_name",
        "keras.utils.get_registered_name",
    ]
)
def get_registered_name(obj):
    
    if obj in GLOBAL_CUSTOM_NAMES:
        return GLOBAL_CUSTOM_NAMES[obj]
    else:
        return obj.__name__


@keras_export(
    [
        "keras.saving.get_registered_object",
        "keras.utils.get_registered_object",
    ]
)
def get_registered_object(name, custom_objects=None, module_objects=None):
    
    custom_objects_scope_dict = global_state.get_global_attribute(
        "custom_objects_scope_dict", {}
    )
    if name in custom_objects_scope_dict:
        return custom_objects_scope_dict[name]
    elif name in GLOBAL_CUSTOM_OBJECTS:
        return GLOBAL_CUSTOM_OBJECTS[name]
    elif custom_objects and name in custom_objects:
        return custom_objects[name]
    elif module_objects and name in module_objects:
        return module_objects[name]
    return None