如何使Keras接收多个输入(keras多输入多输出)

网友投稿 404 2022-08-30


如何使Keras接收多个输入(keras多输入多输出)

Keras 能够通过其功能 API 处理多个输入(甚至多个输出)。功能 API 与顺序 API(您之前几乎可以肯定通过 Sequential 类使用过)相反,可用于定义更复杂的非顺序模型,包括:

多输入模型多输出型号既是多输入又是多输出的模型有向无环图具有共享层的模型

例如,我们可以将一个简单的顺序神经网络定义为:

model = Sequential()model.add(Dense(8, input_shape=(10,), activation="relu"))model.add(Dense(4, activation="relu"))model.add(Dense(1, activation="linear"))

该网络是一个简单的前馈神经网络,没有 10 个输入,第一个隐藏层有 8 个节点,第二个隐藏层有 4 个节点,最后一个输出层用于回归。

我们可以使用功能 API 定义示例神经网络:

inputs = Input(shape=(10,))x = Dense(8, activation="relu")(inputs)x = Dense(4, activation="relu")(x)x = Dense(1, activation="linear")(x)model = Model(inputs, x)

请注意我们如何不再依赖 Sequential 类。要查看 Keras 函数 API 的强大功能,请考虑以下代码,其中我们创建了一个接受多个输入的模型:

# define two sets of inputsinputA = Input(shape=(32,))inputB = Input(shape=(128,))# the first branch operates on the first inputx = Dense(8, activation="relu")(inputA)x = Dense(4, activation="relu")(x)x = Model(inputs=inputA, outputs=x)# the second branch opreates on the second inputy = Dense(64, activation="relu")(inputB)y = Dense(32, activation="relu")(y)y = Dense(4, activation="relu")(y)y = Model(inputs=inputB, outputs=y)# combine the output of the two branchescombined = concatenate([x.output, y.output])# apply a FC layer and then a regression prediction on the# combined outputsz = Dense(2, activation="relu")(combined)z = Dense(1, activation="linear")(z)# our model will accept the inputs of the two branches and# then output a single valuemodel = Model(inputs=[x.input, y.input], outputs=z)

在这里,您可以看到我们为 Keras 神经网络定义了两个输入:

inputA:32-diminputB:128-dim

第 2行使用 Keras 的功能 API 定义了一个简单的 32-8-4 网络。同样,第3 行定义了一个 128-64-32-4 网络。然后我们在第 17行合并 x 和 y 的输出。x 和 y 的输出都是 4-dim,所以一旦我们将它们连接起来,我们就有一个 8-dim 向量。然后,我们在第 21 行和第 22 行应用两个全连接层。第一层有 2 个节点,然后是 ReLU 激活,而第二层只有一个具有线性激活的节点(即我们的回归预测)。构建多输入模型的最后一步是定义一个 Model 对象,该对象:

接受我们的两个输入将输出定义为最终的 FC 层集(即 z )。

如果您要使用 Keras 来可视化模型架构,它将如下所示:

注意我们的模型有两个不同的分支。第一个分支接受我们的 128 维输入,而第二个分支接受 32 维输入。 这些分支相互独立运行,直到它们被连接起来。 从那里从网络输出一个值。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot 整合canal实现示例解析
下一篇:mybatisPlus实现倒序拼接字符串
相关文章

 发表评论

暂时没有评论,来抢沙发吧~