简体   繁体   English

如何使用 Keras 构建具有多个输入和单个 output 的 model

[英]How to build a model having multiple inputs and a single output using Keras

I am trying to use the functional api of Keras to build a model having multiple inputs and a single output.我正在尝试使用 Keras 的功能 api 来构建具有多个输入和单个 Z78E6221F6393D14CEDZD8CZ 的 model。 The goal is to combine each row of each input to predict the corresponding output (either 1 or 0).目标是结合每个输入的每一行来预测对应的 output(1 或 0)。
for example concatenate(inputs_1[0], and inputs_2[0]) and predict output outputs[0]例如concatenate(inputs_1[0], and inputs_2[0])并预测output outputs[0]

My data structure looks like this:我的数据结构如下所示:

inputs_1 = [[[-18.73, 8.98, 0.29, 0.23],[58.50, 28.31, 45.89, -1.62], [48.70, 21.31, 25.89, 1.62]], 
           [[-18.73, 8.98, 0.29, 0.65],[58.50, 28.31, 45.89, -1.62], [48.70, 21.31, 25.89, 1.62]],
           [[-18.73, 8.98, 0.29, 9,3],[58.50, 28.31, 45.89, -1.62], [48.70, 21.31, 25.89, 1.62]],
            ...
            [[-18.73, 8.98, 0.29, 8.93],[58.50, 28.31, 45.89, -1.62], [48.70, 21.31, 25.89, 1.62]]]
            

inputs_2 = [[[0.29, 0.23], [28.31, -1.62]], 
           [[8.98, 0.65], [21.31, 1.62]],
           [[18.50, -1.62], [25.89, 1.62]],
            ...
            [[-48.73, 8.98], [48.70, 1.62]]]

outputs = [1,
           1, 
           0, 
           ...
           0]

I am having some difficulties building the model, the first one arises when I want to reshape the data.我在构建 model 时遇到了一些困难,当我想重塑数据时会出现第一个困难。

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()

# scale our data set so that every observation is between 0 and 1
training_data = scaler.fit_transform(inputs_1.reshape(-1, 1))

But list object has no attribute reshape但是list object 没有属性reshape

I have read this functional api doc but it didn't help me much.我已阅读此功能性 api 文档,但对我没有多大帮助。 However, I now know that I will merge all available features into a single large vector via concatenation.但是,我现在知道我将通过串联将所有可用特征合并到一个大向量中。 How to do so with these nested arrays?如何使用这些嵌套的 arrays 执行此操作?
Another difficulty was to split the data into train, validation, and test.另一个困难是将数据拆分为训练、验证和测试。 Articles I have found do it based on a single input data.我发现的文章是基于单个输入数据进行的。 Is there a way to spit multiple inputs of data?有没有办法吐出多个数据输入?

How could I define the layer, for this case to build the model?我如何定义层,在这种情况下构建 model?
How could I use the api to build my model?我如何使用 api 来构建我的 model?
Any hints or a model's skeleton will be welcome.欢迎任何提示或模型的骨架。
Thank you in advance.先感谢您。

There are a ton of questions you are asking which is usually not inline with SO guidelines .您会问很多问题,这些问题通常不符合SO 准则 It would be better to tackle (search first, ask later if not found) each question separately.最好分别处理(先搜索,如果没有找到后问)每个问题。

Still, just to help you get started, I'll try to answer them in order you asked.不过,为了帮助您入门,我会尝试按照您的要求回答它们。 First, there are few issues with your code -首先,您的代码几乎没有问题 -

  1. You have to first convert inputs_1 and inputs_2 into a numpy array before using reshape .在使用reshape之前,您必须首先将inputs_1inputs_2转换为 numpy 数组。 Use inputs_1 = np.array(inputs_1) and same for input_2.使用inputs_1 = np.array(inputs_1)和 input_2 相同。

  2. Next, you want to apply min max scaler, but you use reshape(-1,1) .接下来,您想应用 min max 缩放器,但您使用reshape(-1,1) This doesn't make sense, since min-max scaling is for each feature independent to the other.这是没有意义的,因为最小-最大缩放对于每个特征都是相互独立的。 I have shown how you can reshape for proper min-max scaling.我已经展示了如何重塑适当的最小-最大缩放。

  3. You also ask about train-test split.您还询问有关训练测试拆分的问题。 You can simply use sklearn's train_test_split the way you usually use it with more inputs.您可以简单地使用 sklearn 的train_test_split ,就像您通常使用更多输入的方式一样。

  4. Lastly, you ask about the multi-input Keras functional API.最后,您询问多输入 Keras 功能 API。 The documentation is really really well done (in fact that is the philosophy of the author of keras as well, to make deep learning easy to learn and implement).文档确实做得很好(实际上这也是 keras 的作者的理念,让深度学习易于学习和实施)。 I have added an example below -我在下面添加了一个示例 -

#Dummy data (USE YOUR OWN DATA HERE AS NUMPY ARRAYS
import numpy as np
X1 = np.random.random((1000, 3, 4))
X2 = np.random.random((1000, 2, 2))
y = np.random.randint(0, 2, (1000,))

Scaling using min-max scaler使用 min-max 缩放器进行缩放

#Scaling individual features by respective min max for 3D tensors
from sklearn.preprocessing import MinMaxScaler

#Have separate scaler objects for each input data
scaler1 = MinMaxScaler()
scaler2 = MinMaxScaler()

#Ensure that in reshape to 2D matrix, you keep the number of features separate
#as min-max scaler works on each feature's respective min-max values
#Then, reshape it back to the 3D dataset

X1_scaled = scaler1.fit_transform(X1.reshape(-1,X1.shape[-1])).reshape(X1.shape)
X2_scaled = scaler1.fit_transform(X2.reshape(-1,X2.shape[-1])).reshape(X2.shape)

print(X1_scaled.shape, X2_scaled.shape)
(1000, 3, 4) (1000, 2, 2)

Train test split for multiple inputs/outputs训练多个输入/输出的测试拆分

from sklearn.model_selection import train_test_split

X1_train, X1_test, X2_train, X2_test, y_train, y_test = train_test_split(X1_scaled, X2_scaled, y, test_size=0.2)

[i.shape for i in (X1_train, X1_test, X2_train, X2_test, y_train, y_test)]
[(800, 3, 4), (200, 3, 4), (800, 2, 2), (200, 2, 2), (800,), (200,)]

Keras functional API with 2 inputs and 1 output Keras 功能 API 带 2 个输入和 1 个 output

from tensorflow.keras import layers, Model, utils

inp1 = layers.Input((3,4))
inp2 = layers.Input((2,2))
x1 = layers.Flatten()(inp1)
x2 = layers.Flatten()(inp2)
x = layers.concatenate([x1, x2])
x = layers.Dense(32)(x)
out = layers.Dense(1, activation='sigmoid')(x)

model = Model([inp1, inp2], out)

utils.plot_model(model, show_layer_names=False, show_shapes=True)

在此处输入图像描述

Training the multi-input model训练多输入 model

model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit([X1_train, X2_train], y_train, epochs=4)
Epoch 1/4
25/25 [==============================] - 0s 674us/step - loss: 0.7310
Epoch 2/4
25/25 [==============================] - 0s 753us/step - loss: 0.7198
Epoch 3/4
25/25 [==============================] - 0s 842us/step - loss: 0.7147
Epoch 4/4
25/25 [==============================] - 0s 2ms/step - loss: 0.7079

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

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