如何处理两个神经网络的两个输入

时间:2019-07-26 08:27:13

标签: python tensorflow keras neural-network anaconda

我想在Keras中建立这样的架构。

此处,一维CNN(展平)的输出将作为ANN的输入,其他一些附加输入也将提供给ANN。因此,整个模型将在两个位置进行输入。如何在Keras中处理此问题?在model.fit函数中,我们通常使用一个输入。我在Tensorflow后端上使用Keras,并使用Anaconda Python 3.7.3。

(这里的ANN表示正常的神经网络)

1 个答案:

答案 0 :(得分:2)

Keras完全支持multi-input models

您的方法是使用fucntional API并在模型中放置两个Input层。使用功能性API构建架构的其余部分,然后定义具有两个输入的Model。在训练过程中,您需要记住同时输入model.fit()中的两个输入。

在您的情况下,它看起来像这样:

from keras.layers import Input, Conv1D, Flatten, Concatenate, Dense
from keras.models import Model

input1 = Input(shape=(...))  # add the shape of your input (excluding batch dimension)

conv = Conv1D(...)(input1)   # add convolution parameters (e.g. filters, kernel, strides)
flat = Flatten()(conv)

input2 = Input(shape=(...))  # add the shape of your secondary input

ann_input = Concatenate()([flat, input2])  # concatenate the two inputs of the ANN
ann = Dense(2)(ann_input)  # 2 because you are doing binary classification

model = Model(inputs=[input1, input2], outputs=[ann])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# assuming x1 and x2 are numpy arrays with the data for 'input1' and 'input2' 
# respectively and y is a numpy array containing the labels

model.fit([x1, x2], y)