【问题标题】:keras: insert layers to the beginning (near the input) of an existing modelkeras:在现有模型的开头(靠近输入)插入层
【发布时间】:2020-09-21 09:13:03
【问题描述】:

我需要在现有模型的开头添加层。但是,我需要在“主模型级别”添加层,即我不能使用经典的功能方法。例如,如果我使用类似的东西:

from keras.layers import Dense,Reshape, Input
inp = Input(shape=(15,))
d1 = Dense(224*224*3, activation='linear')(inp)
r1 = Reshape((224,224,3))
from keras import Model
model_mod = r1(d1)
model_mod = mobilenet(model_mod) 
model_mod = Model(inp, model_mod)

我得到:

Layer (type)                 Output Shape              Param #   
=================================================================
input_5 (InputLayer)         (None, 15)                0         
_________________________________________________________________
dense_4 (Dense)              (None, 150528)            2408448   
_________________________________________________________________
reshape_4 (Reshape)          (None, 224, 224, 3)       0         
_________________________________________________________________
mobilenet_1.00_224 (Model)   (None, 1000)              4253864 

因此,我获得了一个带有嵌套 mobilenet_1.00_224 (Model) 子模型的模型。相反,我希望嵌套子模型的层以层的形式而不是(子)模型的形式“添加”在新的顶层之后(即“reshape_4”之后)。换句话说,会是这样的:

modelB_input = modelB.input
for layer in modelB.layers:
    if layer == modelB_input:
        continue
    modelA.add(layer) 

此代码适用于简单的顺序模型(例如 vgg、mobilenet),但对于具有非严格顺序连接的更复杂模型(例如 inception、resnet)此代码不起作用,因为无法使用 @987654324 重新连接层sequential 模型的 @ 方法。有什么想法吗?

【问题讨论】:

    标签: python keras keras-layer tf.keras


    【解决方案1】:

    也许你必须添加 model_mod.input 作为参数:

    model_mod = r1(d1)
    base_out = mobilenet(model_mod) 
    out =Flatten()(base_out)
    model_mod = Model(inp, out)
    

    【讨论】:

    • 我明白了 ---> model_mod = Model(inp, model_mod.input) AttributeError: 'Tensor' object has no attribute 'input'
    • 我已经使用 Flatten() 解决了问题,但我无法准确重现您的代码。很抱歉,如果我没有帮助你
    猜你喜欢
    • 2018-03-16
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 2017-11-21
    • 2020-08-19
    • 2021-01-27
    相关资源
    最近更新 更多