Project 22: Custom Linear Layer Builder
ML Engineer
Builds on these lessons
Current Task
Objective
Overriding build() lets a custom layer create its weights lazily, once it knows the actual input shape — the low-level pattern behind every built-in Keras layer.
Task: write a Linear custom layer that creates its own weight in build(), then apply it to a batch of inputs.
index.py
import tensorflow as tf
from tensorflow.keras import layers
class Linear(layers.Layer):
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], 4), initializer='random_normal')
def call(self, inputs):
return tf.matmul(inputs, self.w)
layer = Linear()
output = layer(tf.ones((2, 3)))
print(output.shape)
* Hint: Correct characters turn green, incorrect ones turn red.
Live Preview
🖼️
Verify your code to see the preview