在您链接的答案中,由于所述原因,您不能使用Sequential API。您应该使用Model API,它也称为功能 API。在架构上,您需要在模型中定义如何将输入与 Dense 层相结合,即您希望如何创建中间层,即。合并/添加或减去等/构建嵌入层等),或者您可能想要 2 个神经网络,每个输入 1 个,并且只想在最后一层合并输出。以上各项的代码都会有所不同。
这是一个可行的解决方案,假设您要将输入合并为形状为 672 的向量,然后在该输入上构建一个神经网络:
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam, RMSprop
import numpy as np
input1 = Input(shape=(336,))
input2 = Input(shape=(336,))
input = Concatenate()([input1, input2])
x = Dense(2)(input)
x = Dense(1)(x)
model = Model(inputs=[input1, input2], outputs=x)
model.summary()
您会注意到此模型合并或连接两个输入,然后在此之上构建一个神经网络:
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) (None, 336) 0
__________________________________________________________________________________________________
input_2 (InputLayer) (None, 336) 0
__________________________________________________________________________________________________
concatenate (Concatenate) (None, 672) 0 input_1[0][0]
input_2[0][0]
__________________________________________________________________________________________________
dense (Dense) (None, 2) 1346 concatenate[0][0]
__________________________________________________________________________________________________
dense_1 (Dense) (None, 1) 3 dense[0][0]
==================================================================================================
Total params: 1,349
Trainable params: 1,349
Non-trainable params: 0
如果您有其他首选方法来创建中间层,则应将代码中的Concatenate 行替换为该行。
然后您可以编译并拟合模型:
model.compile(
optimizer = RMSprop(lr=0.02,rho=0.9,epsilon=None,decay=0),
loss = 'mean_squared_error'
)
x1, x2 = np.random.randn(100, 336),np.random.randn(100, 336,)
y = np.random.randn(100, 1)
model.fit([x1, x2], y)