【问题标题】:Cannot add layers to saved Keras Model. 'Model' object has no attribute 'add'无法将图层添加到已保存的 Keras 模型。 “模型”对象没有属性“添加”
【发布时间】:2018-01-27 01:03:40
【问题描述】:

我使用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() 模型,但我们如何添加到现有的已保存模型?

【问题讨论】:

    标签: python deep-learning keras keras-layer


    【解决方案1】:

    add 方法仅存在于sequential models (Sequential class) 中,它是更强大但更复杂的functional model (Model class) 的更简单接口。 load_model 将始终返回一个 Model 实例,这是最通用的类​​。

    您可以查看示例以了解如何组合不同的模型,但最终的想法是,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(...)
    

    【讨论】:

      【解决方案2】:

      这是因为加载的模型是函数类型而不是顺序模型。因此,您必须使用此处描述的功能 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)
      

      【讨论】:

      • 感谢您出色的解决方法!但是我觉得fc = Dense(256,activation='relu')(prev_model)应该改成fc = Dense(256,activation='relu')(prev_model.output)不然会有ValueError: Layer conv2d_308 was called with an input that isn't a symbolic tensor. Received type: &lt;class 'keras.engine.training.Model'&gt;. Full input: [&lt;keras.engine.training.Model object at 0x2282c7c50&gt;]. All inputs to the layer should be tensors.
      • @keineahnung2345 确实在寻找这个解决方案好几个小时
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2017-07-27
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多