【问题标题】:keras : add layers to another modelkeras:将图层添加到另一个模型
【发布时间】:2020-11-13 03:08:06
【问题描述】:

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

from keras.layers import Dense,Reshape, Input
inp = Input(shape=(15,))
d1 = Dense(224*224*3, activation='linear')(inp)
r1 = Reshape(input_shape)
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)“添加”到新的顶层(即在 reshape_4 之后)。我试过了:

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

它适用于简单的顺序模型(例如,vgg、mobilenet),但对于连接不是严格顺序的更复杂模型(例如,inception、resnet),此代码并不好。 有什么想法吗?

【问题讨论】:

    标签: keras neural-network keras-layer tf.keras


    【解决方案1】:

    您可以使用keras.layers.Concatenate 合并两个模型,如下所示:

    first = Sequential()
    first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
    
    second = Sequential()
    second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
     
    merged = Concatenate([first, second])
    

    (取自:How to concatenate two layers in keras?)

    虽然此示例使用keras.models.Sequential,但它也适用于其他模型或层。

    你也可以看看:https://keras.io/api/layers/merging_layers/concatenate/

    【讨论】:

    • 它不起作用。结果是一个层,而不是一个模型,所以例如我看不到merged.summary() 的结果,因为我获得了'Concatenate' object has no attribute 'summary'
    • 您是否尝试使用该结果层实例化模型?
    猜你喜欢
    • 2012-08-12
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2018-01-27
    • 1970-01-01
    • 2019-04-10
    相关资源
    最近更新 更多