【问题标题】:How to implement a custom layer wit multiple outputs in Keras?如何在 Keras 中实现具有多个输出的自定义层?
【发布时间】:2018-01-10 19:33:16
【问题描述】:

如标题中所述,我想知道如何让自定义层返回多个张量:out1、out2、...outn?
我试过了

keras.backend.concatenate([out1, out2], axis = 1)

但这仅适用于具有相同长度的张量,而且它必须是另一种解决方案,而不是每次连接两个两个张量,是吗?

【问题讨论】:

  • 你看过keras.io/models/model。使用 keras Model API 而不是 Sequential,将允许您定义多个输出。如果这不是您要查找的内容,您可能需要提供更多描述。

标签: python output keras layer multipleoutputs


【解决方案1】:

在您的层的call 方法中,您执行层计算,您可以返回张量列表:

def call(self, inputTensor):

    #calculations with inputTensor and the weights you defined in "build"
    #inputTensor may be a single tensor or a list of tensors

    #output can also be a single tensor or a list of tensors
    return [output1,output2,output3]

注意输出形状:

def compute_output_shape(self,inputShape):

    #calculate shapes from input shape    
    return [shape1,shape2,shape3]

使用层的结果是张量列表。 自然,某些类型的 keras 层接受列表作为输入,而另一些则不接受。
您必须使用功能 API Model 正确管理输出。在使用Sequential 模型时,您可能会遇到多个输出的问题。

我在我的机器(Keras 2.0.8)上测试了这段代码,它运行良好:

from keras.layers import *
from keras.models import *
import numpy as np

class Lay(Layer):
    def init(self):
        super(Lay,self).__init__()

    def build(self,inputShape):
        super(Lay,self).build(inputShape)

    def call(self,x):
        return [x[:,:1],x[:,-1:]]

    def compute_output_shape(self,inputShape):
        return [(None,1),(None,1)]


inp = Input((2,))
out = Lay()(inp)
print(type(out))

out = Concatenate()(out)
model = Model(inp,out)
model.summary()

data = np.array([[1,2],[3,4],[5,6]])
print(model.predict(data))

import keras
print(keras.__version__)

【讨论】:

  • 当我尝试这个时,我得到:ValueError: Unexpectedly found an instance of type <type 'list'>。需要一个符号张量实例。
  • 您使用的是Sequential 模型吗?你的keras版本是什么?你在这一层之后放了什么层?
  • 如果您要共享更多堆栈跟踪信息(不仅是消息,还有出现此消息的函数和文件),可能更容易找到问题。
  • 我使用的是 keras 版本 2.1.2。我只是用一些 Keras.backend.stack() 行来解决它
猜你喜欢
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 2021-03-12
相关资源
最近更新 更多