无法将层添加到已保存的 Keras 模型。 'Model' 对象没有属性 'add'

Cannot add layers to saved Keras Model. 'Model' object has no attribute 'add'

我使用 model.save() 保存了一个模型。我正在尝试重新加载模型并添加几层并调整一些超参数,但是,它会抛出 AttributeError。

使用 load_model().

加载模型

我想我不了解如何向保存的图层添加图层。如果有人可以在这里指导我,那就太好了。我是深度学习和使用 keras 的新手,所以我的要求可能很愚蠢。

片段:

prev_model = load_model('final_model.h5') # loading the previously saved model.

prev_model.add(Dense(256,activation='relu'))
prev_model.add(Dropout(0.5))
prev_model.add(Dense(1,activation='sigmoid'))

model = Model(inputs=prev_model.input, outputs=prev_model(prev_model.output))

它抛出的错误:

Traceback (most recent call last):
  File "image_classifier_3.py", line 39, in <module>
    prev_model.add(Dense(256,activation='relu'))
AttributeError: 'Model' object has no attribute 'add'

我知道添加层适用于新的 Sequential() 模型,但我们如何添加到现有的已保存模型?

这是因为加载的模型是函数式的,而不是Sequential模型。因此,您将必须按照此处所述使用函数 API:(https://keras.io/getting-started/functional-api-guide/)。

归根结底,正确的函数是这样的:

fc = Dense(256,activation='relu')(prev_model)
drop = Dropout(0.5)(fc)
fc2 = Dense(1,activation='sigmoid')(drop)

model = Model(inputs=prev_model.input, outputs=fc2)

add 方法仅存在于 sequential models (Sequential class), which is a simpler interface to the more powerful but complicated functional model (Model class)。 load_model 将始终 return 一个 Model 实例,这是最通用的 class.

您可以查看示例以了解如何组合不同的模型,但想法是,最终 Model 的行为与任何其他层非常相似。所以你应该能够做到:

prev_model = load_model('final_model.h5') # loading the previously saved model.

new_model = Sequential()
new_model.add(prev_model)
new_model.add(Dense(256,activation='relu'))
new_model.add(Dropout(0.5))
new_model.add(Dense(1,activation='sigmoid'))

new_model.compile(...)