I built a simple custom layer in Keras and was surprised to find that the parameters were not set to trainable by default. I can get it to work by explicitly setting the trainable attribute. I can't explain why this is by looking at documentation or code. Is this how it is supposed to be or I am doing something wrong which is making the parameters non-trainable by default? Code:
import tensorflow as tf
class MyDense(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(MyDense, self).__init__(kwargs)
self.dense = tf.keras.layers.Dense(2, tf.keras.activations.relu)
def call(self, inputs, training=None):
return self.dense(inputs)
inputs = tf.keras.Input(shape=10)
outputs = MyDense()(inputs)
model = tf.keras.Model(inputs=inputs, outputs=outputs, name='test')
model.compile(loss=tf.keras.losses.MeanSquaredError())
model.summary()
Output:
Model: "test"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 10)] 0
_________________________________________________________________
my_dense (MyDense) (None, 2) 22
=================================================================
Total params: 22
Trainable params: 0
Non-trainable params: 22
_________________________________________________________________
If I change the custom layer creation like this:
outputs = MyDense(trainable=True)(inputs)
the output is what I expect (all parameters are trainable):
=================================================================
Total params: 22
Trainable params: 22
Non-trainable params: 0
_________________________________________________________________
then it works as expected and makes all the parameters trainable. I don't understand why that is needed though.