Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "You must compile your model before using it" in case of LSTM and fit_generator in Keras

Tags:

python

keras

I create my own class which create a Keras model inside one of its methods.

self.model = Sequential()
self.model.add(LSTM(32))
self.model.add(Dense(2, activation='relu'))
self.model.compile(optimizer='RMSprop', loss='categorical_crossentropy', metrics=['acc'])

In other method i try to train this model using python generator as data provider.

self.model.fit_generator(my_gen(), steps=10, epochs=1, verbose=1)

This causes an error:

raise RuntimeError('You must compile your model before using it.')
RuntimeError: You must compile your model before using it.

Error does not rises if i change LSTM layer to Dense layer. What am i doing wrong?

Keras version 2.2.0 with Tensorflow 1.8.0 backend.

like image 531
Andrey Noskov Avatar asked Jul 03 '18 08:07

Andrey Noskov


1 Answers

It seems the first Keras LSTM layer still requires an input_shape when using fit_generator which seems to be missing in the Keras documentation and results in the "You must compile your model before using it" error.

To solve make sure you have an input_shape parameter in your first LSTM layer as shown by the example below:

model.add(LSTM(100, input_shape=(n_timesteps, n_dimensions), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(100, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(10, activation='tanh'))

model.compile(loss='mse', optimizer='adam')
like image 64
Jakob Avatar answered Nov 07 '22 05:11

Jakob