Why does the call method gets called at build time in Keras layers

Viewed 1553

So I'm trying to implement my own layer in Keras, using the provided example:

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel', 
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        return K.dot(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

I noticed that what's in call gets called at build time when I do:

model.add(MyLayer(4, input_dim=(1))

This happens without calling fit, train, predict, etc...

Why?

1 Answers
Related