【问题标题】:keras: Use one model output as another model inputkeras:使用一个模型输出作为另一个模型输入
【发布时间】:2018-05-20 13:25:59
【问题描述】:

我在 InceptionResNetV2 模型之前添加了一个密集层(预训练) 这是 InceptionResNetV2 输出

model_base = InceptionResNetV2(include_top=True, weights='imagenet')
x = model_base.get_layer('avg_pool').output
x = Dense(3, activation='softmax')(x)

这是要添加的图层

input1 = Input(shape=input_shape1)
pre1 = Conv2D(filters=3, kernel_size=(5, 5), padding='SAME', 
input_shape=input_shape1, name='first_dense')(input1)
pre = Model(inputs=input1, outputs=pre1)

这是结合两个模型

 after = Model(inputs=pre.output, outputs=x)

 model = Model(inputs=input1, outputs=after.output)

 model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

使用

pre.output

作为

after.input

但它不起作用。我该如何解决?

【问题讨论】:

    标签: model computer-vision deep-learning keras keras-2


    【解决方案1】:

    首先让我们从 model_base 创建一个新模型,因为您想获得更早的输出。

    您的代码:

    model_base = InceptionResNetV2(include_top=True, weights='imagenet')
    x = model_base.get_layer('avg_pool').output
    x = Dense(3, activation='softmax')(x)
    

    model_base:

    model_base = Model(model_base.input, x)
    

    现在,将输出 pre1 传递给这个模型很重要:

    base_out = model_base(pre1)     
    

    就是这样:

    model = Model(input1, base_out)
    

    【讨论】:

    • 我还有一个问题。如果我想用我自己的层 'pre1' 代替 model_base 第一层,我该如何解决呢?谢谢!
    • 我的答案的第一部分变成了short_base = Model(base_model.get_layer('theFirstYouWantToKeep').input, base_model.get_layer('avg_pool')) --- 其余的都是一样的。
    • 我试过了,但我得到了错误:TypeError: Input layers to a Model must be InputLayer objects。接收到的输入:Tensor("conv2d_1/convolution:0", shape=(?, ?, ?, 32), dtype=float32)。
    • 我认为您将不得不逐层调用......类似于out = base_model.layers[2](pre1)。然后是从第 3 层到结束的循环:out = model.layers[i](out)。然后根据您的第一个输入创建一个模型到这个out
    • @Moondra,当我们在它前面使用(pre1) 时,我们正在“调用”model_base。这意味着我们得到一个“输出”base_out,给定一个“输入”pre1
    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 2018-11-22
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2020-05-28
    相关资源
    最近更新 更多