简体   繁体   English

Python Keras 多输入层 - 如何连接/合并?

[英]Python Keras Multiple Input Layers - How to Concatenate/Merge?

In python, I am trying to build a neural network model using Sequential in keras to perform binary classification.在python中,我试图在keras中使用Sequential构建一个神经网络模型来执行二进制分类。 Note that X is a numpy array of time series data 59x1000x3 (samples x timesteps x features) and D is a numpy array of 59x100 (samples x auxillary features).请注意,X 是时间序列数据 59x1000x3(样本 x 时间步长 x 特征)的 numpy 数组,而 D 是 59x100(样本 x 辅助特征)的 numpy 数组。 I want to pass the time series through an lstm layer, and then augment at a later layer with the accompanying features (ie concatenate two layers).我想通过 lstm 层传递时间序列,然后在后面的层中增加伴随的特征(即连接两个层)。

My code to fit the model is below:我适合模型的代码如下:

def fit_model(X, y, D, neurons, batch_size, nb_epoch):
    model = Sequential()
    model.add(LSTM(units = neurons, input_shape = (X.shape[1], X.shape[2]))
    model.add(Dropout(0.1))
    model.add(Dense(10))
    input1 = Sequential()
    d = K.variable(D)
    d_input = Input(tensor=d)
    input1.add(InputLayer(input_tensor=d_input))
    input1.add(Dropout(0.1))
    input1.add(Dense(10))
    final_model = Sequential()
    merged = Concatenate([model, input1])
    final_model.add(merged)
    final_model.add(Dense(1, activation='sigmoid'))
    final_model.compile(loss = 'binary_crossentropy', optimizer = 'adam')
    final_model.fit(X, y, batch_size = batch_size, epochs = nb_epoch)
    return final_model

I get the following error:我收到以下错误:

ValueError: A Concatenate layer should be called on a list of at least 2 inputs ValueError:应在至少 2 个输入的列表上调用Concatenate

I tried using various permutations of merge/concatenate/the functional api/not the functional api, but I keep landing with some sort of error.我尝试使用合并/连接/功能 api/而不是功能 api 的各种排列,但我一直遇到某种错误。 I've seen answers using Merge from keras.engine.topology.我已经看到使用来自 keras.engine.topology 的 Merge 的答案。 However, it seems to now be deprecated.但是,它现在似乎已被弃用。 Any suggestions to fix the error when using Sequential or how to convert the code to the functional API would be appreciated.任何在使用 Sequential 或如何将代码转换为功能 API 时修复错误的建议将不胜感激。 Thanks.谢谢。

You are incorrectly passing a Model and an Input as parameters of the Concatenate layer:您错误地将模型和输入作为 Concatenate 层的参数传递:

merged = Concatenate([model, input1])

Try passing another Input layer instead:尝试传递另一个输入层:

merged = Concatenate([input1, input2])

Concatenate takes only one argument which is axis of concatenation. Concatenate仅采用一个参数,即串联轴。 To call the layer on another tensors you should call concatenate layer object on list of tensors. 要在另一个张量上调用该层,应在张量列表上调用连接的层对象。

merged = Concatenate(axis=-1)([model, input1])

This should fix your problem. 这应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM