I was trying to understanding the concept of custom layer in tensorflow keras.
When the Simple_dense
Layer was created without activation then the code looked like the below:
class SimpleDense(Layer):
def __init__(self, units=32):
'''Initializes the instance attributes'''
super(SimpleDense, self).__init__()
self.units = units
def build(self, input_shape):
'''Create the state of the layer (weights)'''
# initialize the weights
w_init = tf.random_normal_initializer()
self.w = tf.Variable(name="kernel",
initial_value=w_init(shape=(input_shape[-1], self.units),
dtype='float32'),
trainable=True)
# initialize the biases
b_init = tf.zeros_initializer()
self.b = tf.Variable(name="bias",
initial_value=b_init(shape=(self.units,), dtype='float32'),
trainable=True)
def call(self, inputs):
'''Defines the computation from inputs to outputs'''
return tf.matmul(inputs, self.w) + self.b
But when the activation function was introduced in the code then the code became:
class SimpleDense(Layer):
# add an activation parameter
def __init__(self, units=32, activation=None):
super(SimpleDense, self).__init__()
self.units = units
# define the activation to get from the built-in activation layers in Keras
self.activation = tf.keras.activations.get(activation)
def build(self, input_shape):
w_init = tf.random_normal_initializer()
self.w = tf.Variable(name="kernel",
initial_value=w_init(shape=(input_shape[-1], self.units),
dtype='float32'),
trainable=True)
#input shape is -1 as the last instance of the shape tuple actually consists
# the total neurons in the previous layer you can see in the model summary
b_init = tf.zeros_initializer()
self.b = tf.Variable(name="bias",
initial_value=b_init(shape=(self.units,), dtype='float32'),
trainable=True)
super().build(input_shape)
def call(self, inputs):
# pass the computation to the activation layer
return self.activation(tf.matmul(inputs, self.w) + self.b)
I do understand the changes in __init__
and call
functions what I do not understand is that why we added super().build(input_shape)
in the build
function?
I have seen this in few more places where in inheriting in the build function becomes neccesity for example here(How to build this custom layer in Keras?) it is written that
Be sure to call this at the end