如标题所述,我想知道如何让自定义层返回多个张量: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/