Keras submodel needs to be built

I am creating a python class that inherits from a keras model.

class MyModel(tf.keras.models.Model):

    def __init__(self, size, input_shape):
        super(MyModel, self).__init__()
        self.layer = tf.keras.layers.Dense(size, input_shape=(input_shape,))

    def call(self, inputs):
        return self.layer(inputs)

model = MyModel(5, 30)
model.summary()

This gives me this error:

ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.

It is fixed if I add one line after creating the model:

model = MyModel(5, 30)
model(tf.keras.layers.Input((30,)))
model.summary()

But it doesn't look the best way of doing this. How can I fix it?

Upvotes: 1

Views: 861

Answers (1)

Stewart_R
Stewart_R

Reputation: 14485

You can call self.build() in the constructor.

Something like this:

class MyModel(tf.keras.models.Model):

    def __init__(self, size, input_shape):
        super(MyModel, self).__init__()
        self.layer = tf.keras.layers.Dense(size, input_shape=(input_shape,))
        self.build(input_shape)

    def call(self, inputs):
        return self.layer(inputs)

model = MyModel(2, (5, 30))
model.summary()

Upvotes: 1

Related Questions