无法向保存的 Keras 模型添加图层.“模型"对象没有属性“添加" [英] Cannot add layers to saved Keras Model. 'Model' object has no attribute 'add'
问题描述
我使用 model.save()
保存了一个模型.我正在尝试重新加载模型并添加几层并调整一些超参数,但是,它引发了 AttributeError.
I have a saved a model using model.save()
. I'm trying to reload the model and add a few layers and tune some hyper-parameters, however, it throws the AttributeError.
使用 load_model()
加载模型.
我想我不明白如何将图层添加到保存的图层.如果有人能在这里指导我,那就太好了.我是深度学习和使用 keras 的新手,所以我的要求可能很愚蠢.
I guess I'm missing understanding how to add layers to saved layers. If someone can guide me here, it will be great. I'm a novice to deep learning and using keras, so probably my request would be silly.
片段:
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() 模型,但我们如何添加到现有保存的模型中?
I know adding layers works on new Sequential() model, but how do we add to existing saved models?
推荐答案
add
方法仅存在于 顺序模型 (顺序
class),这是一个更强大但更复杂的函数模型的简单接口(Model
类).load_model
将始终返回一个 Model
实例,这是最通用的类.
The add
method is present only in sequential models (Sequential
class), which is a simpler interface to the more powerful but complicated functional model (Model
class). load_model
will always return a Model
instance, which is the most generic class.
您可以查看示例以了解如何组合不同的模型,但最终的想法是,Model
的行为与任何其他层非常相似.所以你应该能够做到:
You can look at the example to see how you can compose different models, but the idea is that, in the end, a Model
behaves pretty much like any other layer. So you should be able to do:
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(...)
这篇关于无法向保存的 Keras 模型添加图层.“模型"对象没有属性“添加"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!