【问题标题】:How to connect custom Keras layer with multiple outputs如何将自定义 Keras 层与多个输出连接
【发布时间】:2018-09-07 00:42:27
【问题描述】:

我定义了一个带有两个输出的自定义 Keras 层 custom_layer:output_1 和 output_2。接下来,我希望两个独立的层 A 和 B 分别连接到 output_1 和 output_2。这种网络如何实现?

【问题讨论】:

  • 你的问题不清楚,为什么 output_1 和 output_2 不一样?也许你想在 layerA 之后提取 ouput_1,在 layer b 之后提取 output_2?
  • 你能告诉我们自定义层的定义吗?

标签: keras keras-layer


【解决方案1】:

使用 keras api 模式,您可以创建任何网络架构。 在您的情况下,可能的解决方案是

input_layer = Input(shape=(100,1))
custom_layer = Dense(10)(input_layer)

# layer A model
layer_a = Dense(10, activation='relu')(custom_layer)
output1 = Dense(1, activation='sigmoid')(layer_a)

# layer B model
layer_b = Dense(10, activation='relu')(custom_layer)
output1 = Dense(1, activation='sigmoid')(layer_b)

# define model input and output
model = Model(inputs=input_layer, outputs=[output1, output2])

【讨论】:

    【解决方案2】:

    如果自定义层在应用于一个输入时有两个输出张量(即它返回一个输出张量列表),则:

    custom_layer_output = CustomLayer(...)(input_tensor)
    
    layer_a_output = LayerA(...)(custom_layer_output[0])
    layer_b_output = LayerB(...)(custom_layer_output[1])
    

    但是如果应用于两个不同的输入张量,那么:

    custom_layer = CustomLayer(...)
    out1 = custom_layer(input1)
    out2 = custom_layer(input2)
    
    layer_a_output = LayerA(...)(out1)
    layer_b_output = LayerB(...)(out2)
    
    # alternative way
    layer_a_output = LayerA(...)(custom_layer.get_output_at(0))
    layer_b_output = LayerB(...)(custom_layer.get_output_at(1))
    

    【讨论】:

    • 感谢您的回复。如果custom_layer之前有一些层怎么办?例如custom_layer = CustomLayer(...)(previous_layers)
    • @Tian 为了确保我正确理解您的问题:您的意思是您的自定义层已应用于两个不同的输入张量吗?还是应用于一个输入张量时是否有两个输出?
    • 自定义层之前有一些层,它有两个输出
    【解决方案3】:

    Keras 支持在您的自定义层中有多个输出层。有一个merge,它将很快更新文档。 基本思想是使用列表。您必须在自定义层(如层和形状)中重新输入所有内容,都必须作为它们的列表返回。

    如果您以正确的方式实现自定义层,剩下的就很简单了:

    output_1, output_2 = custom_layer()(input_layer)
    layer_a_output = layer_a()(output_1)
    layer_b_output = layer_b()(output_2)
    

    【讨论】:

      猜你喜欢
      • 2019-12-03
      • 1970-01-01
      • 2019-02-20
      • 2018-04-26
      • 2017-06-28
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多