keras:在现有模型的开头输入附近插入图层

问题描述

我需要在现有模型的开头添加图层。但是,我需要在“主模型级别”上添加层,也就是说,我不能使用经典的功能方法。例如,如果我使用类似的内容

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,3)       0         
_________________________________________________________________
mobilenet_1.00_224 (Model)   (None,1000)              4253864 

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

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

代码适用于简单的顺序模型(例如vgg,mobilenet),但对于连接没有严格顺序的更复杂的模型(例如inception,resnet),此代码不起作用,因为无法使用{{ add模型的1}}方法。有什么想法吗?

解决方法

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

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