首页 > 解决方案 > Keras 编码器-解码器模型 RuntimeError: You must compile your model before using it

问题描述

我正在尝试重现图像字幕模型的结果,但出现此错误。两种模型的代码如下:

image_model = Sequential()
image_model.add(Dense(EMBEDDING_DIM, input_dim=4096, activation='relu'))
image_model.add(RepeatVector(self.max_length))

lang_model = Sequential()
lang_model.add(Embedding(self.vocab_size, 256, input_length=self.max_length))
lang_model.add(LSTM(256, return_sequences=True))
lang_model.add(TimeDistributed(Dense(EMBEDDING_DIM)))

model = Sequential()
model.add(Concatenate([image_model, lang_model]))
model.add(LSTM(1000, return_sequences=False))
model.add(Dense(self.vocab_size))
model.add(Activation('softmax'))

print ("Model created!")
model.compile(loss='categorical_crossentropy', 
optimizer='rmsprop', metrics=['accuracy'])

然后由以下代码调用模型:

sd = SceneDesc.scenedesc()
model = sd.create_model()
batch_size = 512
model.fit_generator(sd.data_process(batch_size=batch_size), 
    steps_per_epoch=sd.no_samples/batch_size, epochs=epoch, verbose=2, 
    callbacks=None)

但是,当fit_generator调用 时,会引发特定错误。模型的串联有什么问题吗?

标签: pythonkerasencoder-decoder

解决方案


在 keras 中,有一个概念叫做编译你的模型。

基本上,这会配置损失函数并为您要训练的模型设置优化器。

例如,model.compile(loss='mse',optimizer='Adam')将您的模型配置为使用mse损失函数,并使用Adam优化算法。您使用什么来代替这些将在很大程度上取决于问题的类型。

您的代码抛出错误的原因是模型无法训练,因为您没有使用该compile方法配置损失函数和优化器。使用您选择的损失函数和优化器进行简单调用model.compile(),然后您将能够训练您的模型。


推荐阅读