gpt4 book ai didi

python - Keras 中的 LSTM 和 fit_generator 错误 "You must compile your model before using it"

转载 作者:太空狗 更新时间:2023-10-30 01:04:30 25 4
gpt4 key购买 nike

我创建了自己的类,它在其中一个方法中创建了一个 Keras 模型。

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 生成器作为数据提供者来训练这个模型。

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 层更改为密集层,错误不会增加。我做错了什么?

带有 Tensorflow 1.8.0 后端的 Keras 2.2.0 版。

最佳答案

似乎第一个 Keras LSTM 层在使用 fit_generator 时仍然需要 input_shape,这在 Keras 文档中似乎缺失并导致“你必须编译你的模型在使用它之前”错误。

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

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

关于python - Keras 中的 LSTM 和 fit_generator 错误 "You must compile your model before using it",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51150468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com