如何在 Keras 中实现具有多个输出的自定义层?

Tas*_*sou 6 python layer output multipleoutputs keras

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

keras.backend.concatenate([out1, out2], axis = 1)
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*ler 4

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]
Run Code Online (Sandbox Code Playgroud)

注意输出形状:

def compute_output_shape(self,inputShape):

    #calculate shapes from input shape    
    return [shape1,shape2,shape3]
Run Code Online (Sandbox Code Playgroud)

使用该层的结果是张量列表。当然,某些类型的 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__)
Run Code Online (Sandbox Code Playgroud)