Yes “build” method is not compulsory. You can check this link, I have mentioned this.
When you define a custom layer in TensorFlow using the
tf.keras.layers.Layer
class, specify theinput_shape
in the constructor to inform the expected shape of the input data. To pass the input shape to a custom model in TensorFlow, you can either specify the input shape when creating an instance of the model or use thetf.keras.Input
layer to define the input shape dynamically.
You have the option to provide the input_shape
parameter during the instantiation of your custom layer. This parameter is not mandatory but proves useful when designing the layer’s architecture, particularly if the layer’s functionality relies on characteristics of the input data shape.
TensorFlow automatically invokes the build
method the first time the layer is utilized, providing the real input shape as an argument. If you omitted the input_shape
in the constructor, you can obtain the input shape by extracting it from the input_shape
argument within the build
method.
Within the build
method, you can leverage the input_shape
details to appropriately initialize the layer’s weights. For example, in the case of a dense layer, the quantity of units in the output would be contingent on the final dimension of the input shape.