Keras从两个神经网络模型组成神经网络模型

时间:2018-03-28 17:05:22

标签: python tensorflow neural-network keras

我正在使用Keras和Tensorflow来实现我的模型(M)。 让我们假设我有以下输入功能 F = {x,y,a1,a2,a3,...,an} 我想仅使用x和y构建深度模型(M1)。然后,具有所有剩余特征(a1,a2,...,an)的(M1)的输出将是另一个模型(M2)的输入。

x,y - > M1 - > z,a1,a2,...,an - > M2 - >最终输出

如何在Keras建立这样的模型?

1 个答案:

答案 0 :(得分:1)

使用Keras functional api

我不清楚你是否想要第二个只接受第一个模型输出训练的模型,或者可以让两个模型联合训练的东西。

如果你的意思是分别训练M1和M2,那么假设x, y, a是你的输入ndarray,你可以这样做:

input_x = Input(shape=...)
input_y = Input(shape=...)

...

M1 = ... # your first model
m1_output = M1.output # assuming M1 outputs only one tensor

m2_input = Input(batch_shape=m1_output.shape) # the part that you can feed outputs from M1
m2_output = ...

M2 = Model(inputs=[m2_input,a], outputs=[m2_output])

你也可以同时训练这两个部分,然后it's also covered in Functional API's documentation。您需要像这样定义M2:

M2 = Model(inputs=M1.inputs + [a], outputs=M1.outputs + [m2_output])

当然,你必须相应地计算出损失。