C.W.K.
Stream
Lesson 06 of 07 · published

Custom Object Registration

~9 min · serialize

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

The loader can't import what it's never met

A built-in layer like Dense serializes cleanly because load_model already knows the class — it ships with Keras. Your own subclassed layer doesn't have that luxury. The config stores the layer's name as a string, but when the loader reads it back, it has no map from that string to your Python class. The result is the classic Unknown layer error.

Two pieces close the loop

Registration plus get_config together make a custom layer round-trip. The @register_keras_serializable decorator adds your class to a name → class registry, so the loader can resolve the string back to the right Python object. get_config handles the other half: it returns the __init__ arguments (here, units) as a plain dict, so the loader can reconstruct the layer with the same settings it was built with. Call super().get_config() first to inherit the base layer's keys, then add your own.

The package namespace

The package= argument prefixes the registered name (e.g. my_package>MyCustomLayer), which prevents collisions when two projects both define a layer called Attention. Pick a stable package string and keep it consistent — it becomes part of the saved file's identity.

Code

Register a custom layer and implement get_config·python
@keras.saving.register_keras_serializable(package="my_package")
class MyCustomLayer(keras.layers.Layer):
    def __init__(self, units, **kwargs):
        super().__init__(**kwargs)
        self.units = units

    def get_config(self):
        config = super().get_config()
        config.update({"units": self.units})
        return config

# Now model.save() / load_model() works with custom objects

External links

Exercise

Take your custom Transformer block from earlier. Add @keras.saving.register_keras_serializable() decorator + get_config method. Save and reload a model that uses it. Verify outputs match exactly.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.