I’m trying to build a custom model by subclassing the Model class, as shown in the videos, but when I call model.summary(), I keep getting 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.
and I cannot train either.
I suspect it has to do with passing input shape to the custom model, which I haven’t seen Laurence doing in the resnet video. I tried adding Input layer in the init() function, in the call() function, adding ‘input_shape’ parameter and using build function, but nothing works. Can someone please help me with this?
Here is my code:
from tensorflow.keras.layers import Conv2D, Dense, Input, MaxPooling2D
class CustomModel(tf.keras.Model):
def __init__(self, filters, kernel_size, pool_size, num_layers, input_shape, **kwargs):
super().__init__(**kwargs)
self.shape = input_shape
self.conv = [Conv2D(filters=filters, kernel_size=kernel_size, activation='relu') for layer in range(num_layers)]
self.pool = [MaxPooling2D(pool_size=pool_size) for layer in range(num_layers)]
# self.conv.insert(0, Conv2D(filters=filters, kernel_size=kernel_size, input_shape=self.shape, activation='relu')) didn't work
self.input_layer = Input(shape=self.shape)
# def build(self, input_shape):
# super().build(input_shape)
def call(self, x):
x = self.input_layer(x)
for conv, pool in zip(self.conv, self.pool):
x = conv(x)
x = pool(x)
return x
model = CustomModel(32, 3, 2, 2, (28, 28, 1))
# model.build((None, 28, 28, 1))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.summary()