Keras Model甚至在编译调用后仍要求进行编译

时间:2019-03-14 11:32:43

标签: python python-3.x machine-learning keras deep-learning

我有一个简单的Keras模型:

model_2 = Sequential()
model_2.add(Dense(32, input_shape=(500,)))
model_2.add(Dense(4))
#answer = concatenate([response, question_encoded])

model_1 = Sequential()
model_1.add(LSTM(32, dropout_U = 0.2, dropout_W = 0.2, return_sequences=True, input_shape=(None, 2048)))
model_1.add(LSTM(16, dropout_U = 0.2, dropout_W = 0.2, return_sequences=False))
#model.add(LSTM(16, return_sequences=False))

merged = Merge([model_1, model_2])
model = Sequential()
model.add(merged)
model.add(Dense(8, activation='softmax'))

#model.build()

#print(model.summary(90))
print("Compiled")
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

代码在调用fit()时失败并显示错误:

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

很显然,我已经调用了compile。我该如何解决错误?

1 个答案:

答案 0 :(得分:1)

问题似乎在于您正在创建3个Sequential模型实例,但仅编译第3个实例(合并的实例)。 在多模式网络中使用其他结构可能会更容易:

input_2 = Input(shape=(500,))
model_2 = Dense(32)(input_2 )
model_2 = Dense(4)(model_2)

input_1 = Input(shape=(None, 2048))
model_1 = LSTM(32, dropout_U = 0.2, dropout_W = 0.2, return_sequences=True)(input_1 )
model_1 = LSTM(16, dropout_U = 0.2, dropout_W = 0.2, return_sequences=False)(model_1)

merged = concatenate([model_2, model_1])
merged = Dense(8, activation='softmax')(merged)

model = Model(inputs=[input_2 , input_1], outputs=merged)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

希望这会有所帮助!