错误“您必须在使用模型之前对其进行编译".在Keras中使用LSTM和fit_generator的情况 [英] Error "You must compile your model before using it" in case of LSTM and fit_generator in Keras

查看:1228
本文介绍了错误“您必须在使用模型之前对其进行编译".在Keras中使用LSTM和fit_generator的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了自己的类,该类在其中的一种方法中创建了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'])

在另一种方法中,我尝试使用python生成器作为数据提供者来训练此模型.

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)

这会导致错误:

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

如果我将LSTM层更改为密集层,错误不会上升.我在做什么错了?

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

具有Tensorflow 1.8.0后端的Keras版本2.2.0.

Keras version 2.2.0 with Tensorflow 1.8.0 backend.

推荐答案

在使用fit_generator时,似乎第一个Keras LSTM层仍然需要input_shape,这似乎在Keras文档中丢失了,并导致您必须在使用模型之前对其进行编译"错误.

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.

要解决此问题,请确保在您的第一个LSTM层中有一个input_shape参数,如下例所示:

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')

这篇关于错误“您必须在使用模型之前对其进行编译".在Keras中使用LSTM和fit_generator的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆