model.summary error for RNN. This model has not yet been built

Viewed 784

I am using the following code:

model = Sequential()
model.add(Conv2D(filters=96, kernel_size=(11,11), strides=(11, 3),input_shape=(input_length,input_features,1), activation='relu'))
model.add(Dense(5, activation="softmax"))
model.compile(loss='categorical_crossentropy', metrics=["accuracy"], optimizer=optimizer(lr))
model.summary()

del model
model = Sequential()

model.add(Bidirectional(LSTM(128, return_sequences=True, input_shape=(input_length,input_features))))
model.add(Dense(5, activation="softmax"))
model.compile(loss='categorical_crossentropy', metrics=["accuracy"], optimizer=optimizer(lr))
model.summary()
exit()

And getting the following output:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 55, 55, 96)        11712     
_________________________________________________________________
dense (Dense)                (None, 55, 55, 5)         485       
=================================================================
Total params: 12,197
Trainable params: 12,197
Non-trainable params: 0
_________________________________________________________________
Traceback (most recent call last):
  File "Convert2hdf5.py", line 28, in <module>
    model.summary()
  File "/home/erez/projects/Journal/VE/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 2376, in summary
    raise ValueError('This model has not yet been built. '
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.

Why is it enough for the Conv2D layer to specify the input using input_shape and for LSTM it is not enough? Am I doing something wrong here?

1 Answers

You have wrapped your LSTM layer with a Bidirectional layer. Thus, you should pass the input_shape parameter to the Bidirectional and not the LSTM layer. Change according to the following:

model.add(Bidirectional(LSTM(128, return_sequences=True), input_shape=(nput_length, input_features)))

The model then compiles without problems.

Related