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

标签 python output keras layer multipleoutputs

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

keras.backend.concatenate([out1, out2], axis = 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__)

关于python - 如何在 Keras 中实现具有多个输出的自定义层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48194802/

相关文章:

python - 如何在 Mac 上将 Python3 设置为默认的 python 版本?

java - Java 中的 UNO 游戏早期阶段问题

c - 我的 C 程序的输出不是预期的

javascript - input.value=<variable> 返回静态值 [Javascript]

python - 在python中将所有列表值连接到一个数组

python - 变量替换在 Sphinx 中无法正常工作

python - ValueError:层激活_1调用的输入不是符号张量

python - 属性错误: 'NoneType' object has no attribute 'fit_generator'

machine-learning - 如何防止懒惰的卷积神经网络?

python - Jupyter 笔记本,错误的 sys.path 和 sys.executable