1) 不是真的。但是我不确定您在该图中到底想要什么。 (让我们看看下面的 Keras 循环层是如何工作的)
2) 是的,可以将每一层连接到每一层,但你不能为此使用Sequential,你必须使用Model。
这个答案可能不是您想要的。你到底想达到什么目的?你有什么样的数据,你期望什么样的输出,模型应该做什么?等等……
1 - 循环层如何工作?
Documentation
keras 中的循环层使用“输入序列”,可以输出单个结果或序列结果。它的 recurrency 完全包含在其中,不与其他层交互。
您应该有形状为(NumberOrExamples, TimeStepsInSequence, DimensionOfEachStep) 的输入。这意味着input_shape=(TimeSteps,Dimension)。
循环层将在每个时间步内部工作。循环一步一步发生,这种行为是完全不可见的。该层似乎与任何其他层一样工作。
这似乎不是你想要的。除非您有要输入的“序列”。我知道是否在 Keras 中使用与您的图形相似的循环层的唯一方法是当您有一段序列并想要预测下一步时。如果是这种情况,请通过在 Google 中搜索“预测下一个元素”来查看 examples。
2 - 如何使用模型连接层:
不要将层添加到顺序模型(始终遵循直线),而是从输入张量开始独立使用层:
from keras.layers import *
from keras.models import Model
inputTensor = Input(shapeOfYourInput) #it seems the shape is "(2,)", but we must see your data.
#A dense layer with 2 outputs:
myDense = Dense(2, activation=ItsAGoodIdeaToUseAnActivation)
#The output tensor of that layer when you give it the input:
denseOut1 = myDense(inputTensor)
#You can do as many cycles as you want here:
denseOut2 = myDense(denseOut1)
#you can even make a loop:
denseOut = Activation(ItsAGoodIdeaToUseAnActivation)(inputTensor) #you may create a layer and call it with the input tensor in just one line if you're not going to reuse the layer
#I'm applying this activation layer here because since we defined an activation for the dense layer and we're going to cycle it, it's not going to behave very well receiving huge values in the first pass and small values the next passes....
for i in range(n):
denseOut = myDense(denseOut)
如果您尊重形状规则,这种用法允许您创建任何类型的模型,包括分支、替代方式、从任何地方到任何地方的连接。对于这样的循环,输入和输出必须具有相同的形状。
最后,您必须定义一个从一个或多个输入到一个或多个输出的模型(您必须有训练数据来匹配您选择的所有输入和输出):
model = Model(inputTensor,denseOut)
但请注意,此模型是静态的。如果要更改周期数,则必须创建一个新模型。
在这种情况下,就像重复循环步骤denseOut = myDense(denseOut) 并创建另一个model2=Model(inputTensor,denseOut) 一样简单。
3 - 尝试创建如下图所示的内容:
我假设 C 和 F 将参与所有迭代。如果没有,
由于有四个实际输入,我们将分别处理它们,让我们创建 4 个输入来代替,都像 (1,)。
你的输入数组应该被分成 4 个数组,都是 (10,1)。
from keras.models import Model
from keras.layers import *
inputA = Input((1,))
inputB = Input((1,))
inputC = Input((1,))
inputF = Input((1,))
现在层 N2 和 N3,将只使用一次,因为 C 和 F 是恒定的:
outN2 = Dense(1)(inputC)
outN3 = Dense(1)(inputF)
现在是循环层 N1,还没有给它张量:
layN1 = Dense(1)
对于循环,让我们创建 outA 和 outB。它们从实际输入开始,将被提供给 N1 层,但在循环中它们将被替换
outA = inputA
outB = inputB
现在在循环中,让我们“通过”:
for i in range(n):
#unite A and B in one
inputAB = Concatenate()([outA,outB])
#pass through N1
outN1 = layN1(inputAB)
#sum results of N1 and N2 into A
outA = Add()([outN1,outN2])
#this is constant for all the passes except the first
outB = outN3 #looks like B is never changing in your image....
现在的模型:
finalOut = Concatenate()([outA,outB])
model = Model([inputA,inputB,inputC,inputF], finalOut)