Error “You must compile your model before using it

2020-07-06 06:12发布

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.

标签: python keras
2条回答
贪生不怕死
2楼-- · 2020-07-06 06:57

I experience a similar problem. I could resolve it by using:

self.model.compile(optimizer='RMSprop', loss='categorical_crossentropy', metrics=['acc'])

before :

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

in the function where fit_generator() was called.

查看更多
够拽才男人
3楼-- · 2020-07-06 06:59

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')
查看更多
登录 后发表回答