Is using setattr + list to create a variable number of sublayers serializable?

3 weeks ago 29
ARTICLE AD BOX

I am implementing a custom Keras Layer where the number of internal sublayers depends on a user-defined parameter, so I don’t know the number of layers in advance.

To handle this, I create the sublayers in a loop, assign each one as an attribute using setattr, and also keep them in a Python list for easy iteration:

@keras.saving.register_keras_serializable() class MyBlock(tf.keras.layers.Layer): def __init__(self, n_layers): super().__init__() self.n_layers = n_layers self.blocks = [] for i in range(n_layers): layer = tf.keras.layers.Dense(8) setattr(self, f"block_{i}", layer) self.blocks.append(getattr(self, f"block_{i}")) def call(self, x): for layer in self.blocks: x = layer(x) return x def get_config(self): return {"n_layers": self.n_layers} My understanding is that:

Keras only tracks layers assigned as attributes

Lists alone are not tracked

Using setattr ensures each sublayer is registered and serialized correctly

Is this approach correct and safe for model saving/loading, or is there a better Keras-recommended pattern for variable numbers of sublayers?

Read Entire Article