Why Build Custom Layers?
Keras has many ready-made layers, but sometimes you need something new: a special calculation from a research paper, or a reusable block for your team. Subclassing lets you create exactly that and still use it like any other Keras layer.
A Simple Custom Layer
python
import keras
from keras import layers
import numpy as np
class MyDense(layers.Layer):
def __init__(self, units, activation=None, **kwargs):
super().__init__(**kwargs)
self.units = units
self.activation = keras.activations.get(activation)
def build(self, input_shape):
# create weights once the input size is known
self.w = self.add_weight(shape=(input_shape[-1], self.units),
initializer="glorot_uniform", name="w")
self.b = self.add_weight(shape=(self.units,), initializer="zeros", name="b")
def call(self, inputs):
return self.activation(keras.ops.matmul(inputs, self.w) + self.b)
def get_config(self):
config = super().get_config()
config.update({"units": self.units,
"activation": keras.activations.serialize(self.activation)})
return config
layer = MyDense(4, activation="relu")
print(layer(np.ones((2, 3), dtype="float32")).shape) # (2, 4)
| Method | Purpose |
__init__ | Store settings such as the number of units |
build | Create weights when the input shape is known |
call | The forward computation |
get_config | Needed for saving and loading the model |
keras.ops: In Keras 3, write calculations with keras.ops (for example keras.ops.matmul). Then your layer works on every backend, not only TensorFlow.
Using the Layer in a Model
python
model = keras.Sequential([
keras.Input(shape=(10,)),
MyDense(32, activation="relu"),
MyDense(1),
])
model.compile(optimizer="adam", loss="mse")
A Layer with a Training Flag
python
class NoisyLayer(layers.Layer):
def __init__(self, stddev=0.1, **kwargs):
super().__init__(**kwargs)
self.stddev = stddev
def call(self, x, training=False):
if training: # add noise only while training
return x + keras.random.normal(keras.ops.shape(x), stddev=self.stddev)
return x
A Custom Model
python
class MyModel(keras.Model):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.d1 = layers.Dense(64, activation="relu")
self.drop = layers.Dropout(0.3)
self.out = layers.Dense(10, activation="softmax")
def call(self, x, training=False):
x = self.d1(x)
x = self.drop(x, training=training)
return self.out(x)
model = MyModel()
model.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
Subclassed models are the most flexible, but they are harder to inspect. The Functional API is usually enough, so use subclassing only when you really need the freedom.
Custom Loss and Metric
python
def huber_like(y_true, y_pred):
err = y_true - y_pred
small = keras.ops.abs(err) < 1.0
return keras.ops.mean(keras.ops.where(small, 0.5 * err ** 2, keras.ops.abs(err) - 0.5))
model.compile(optimizer="adam", loss=huber_like)
Conclusion
Custom layers, losses and models give you the freedom to implement new ideas. Keep them compatible with all backends by using keras.ops.
Quick Summary: Subclass Layer with build and call, add get_config for saving, and use keras.ops for backend-independent math.