合并CNN和LSTM。 RuntimeError:使用模型之前,必须先对其进行编译

时间:2019-01-28 10:38:15

标签: model keras sequential

我正在构建一个合并CNN和LSTM的模型,但是当我想训练它时,它会弹出一个错误: RuntimeError:您必须先编译模型,然后再使用它。

我在StackOverflow上尝试了很多可能的解决方案,例如 Keras Bidirectional "RuntimeError: You must compile your model before using it." after compilation completedKeras encoder-decoder model RuntimeError: You must compile your model before using it

但它们都不起作用。

我在StackOverflow上尝试了很多可能的解决方案,例如 Keras Bidirectional "RuntimeError: You must compile your model before using it." after compilation completedKeras encoder-decoder model RuntimeError: You must compile your model before using it

但它们都不起作用。

在creat_model.py

def create_model(self, ret_model = False):
    #base_model = VGG16(weights='imagenet', include_top=False, input_shape = (224, 224, 3))
    #base_model.trainable=False
    image_model = Sequential()
    #image_model.add(base_model)
    #image_model.add(Flatten())
    image_model.add(Dense(EMBEDDING_DIM, input_dim = 4096, activation='relu'))

    image_model.add(RepeatVector(self.max_cap_len))

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

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

    print("Model created!")

    if(ret_model==True):
        return model

    model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    return model

...

在train.py

def train_model(weight = None, batch_size=32, epochs = 10):

    cg = caption_generator.CaptionGenerator()
    model = cg.create_model()

    if weight != None:
        model.load_weights(weight)

    counter = 0
    file_name = 'weights-improvement-{epoch:02d}.hdf5'
    checkpoint = ModelCheckpoint(file_name, monitor='loss', verbose=1, save_best_only=True, mode='min')
    callbacks_list = [checkpoint]
    model.fit_generator(cg.data_generator(batch_size=batch_size), steps_per_epoch=cg.total_samples/batch_size, epochs=epochs, verbose=2, callbacks=callbacks_list)
    try:
        model.save('Models/WholeModel.h5', overwrite=True)
        model.save_weights('Models/Weights.h5',overwrite=True)
    except:
        print("Error in saving model.")
    print("Training complete...\n")

0 个答案:

没有答案