【问题标题】:Keras Model asks for compiling even after compile call即使在编译调用之后,Keras 模型也会要求编译
【发布时间】:2019-03-14 11:32:43
【问题描述】:

我有一个简单的 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。我该如何解决这个错误?

【问题讨论】:

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


    【解决方案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'])
    

    希望这会有所帮助!

    【讨论】:

    • 谢谢,但我得到 AttributeError: 'Tensor' object has no attribute 'compile'
    • 抱歉,刚刚进行了编辑(我忘记粘贴模型步骤),你还有这个吗?
    • 酷!好的,所以这似乎是一个稍微不同的问题;在模型 1 的原始帖子输入中是(无,2048),但您有错误(无,无,2048)。如果后者是正确的,那么连接层可能无法按原样工作,您将不得不重新调整输入以匹配尺寸。如果是前者,那就看看是打字错误还是形状错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2021-08-30
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多