简体   繁体   English

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

[英]How to implement a custom layer wit multiple outputs in Keras?

Like stated in the title, I was wondering as to how to have the custom layer returning multiple tensors: out1, out2,...outn? 就像标题中所述,我想知道如何让自定义图层返回多个张量:out1,out2,... outn?
I tried 我试过了

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

But this does only work for tensors having the same length, and it has to be another solution rather than concatenating two by two tensors every time, is it? 但这只适用于具有相同长度的张量,它必须是另一种解决方案,而不是每次连接两个张量,是吗?

In the call method of your layer, where you perform the layer calculations, you can return a list of tensors: 在图层的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]

Take care of the output shapes: 注意输出形状:

def compute_output_shape(self,inputShape):

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

The result of using the layer is a list of tensors. 使用该层的结果是张量列表。 Naturally, some kinds of keras layers accept lists as inputs, others don't. 当然,某些类型的keras层接受列表作为输入,而其他类型则不接受。
You have to manage the outputs properly using a functional API Model . 您必须使用功能API Model正确管理输出。 You're probably going to have problems using a Sequential model while having multiple outputs. 在具有多个输出时,您可能会遇到使用Sequential模型的问题。

I tested this code on my machine (Keras 2.0.8) and it works perfectly: 我在我的机器上测试了这段代码(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__)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM