简体   繁体   English

Keras 序列模型的多个输入

[英]Multiple inputs to Keras Sequential model

I am trying to merge output from two models and give them as input to the third model using keras sequential model.我正在尝试合并来自两个模型的输出,并使用 keras 顺序模型将它们作为第三个模型的输入。 Model1 :型号 1 :

inputs1 = Input(shape=(750,))
x = Dense(500, activation='relu')(inputs1)
x = Dense(100, activation='relu')(x)

Model1 :型号 1 :

inputs2 = Input(shape=(750,))
y = Dense(500, activation='relu')(inputs2)
y = Dense(100, activation='relu')(y)

Model3 :型号3:

merged = Concatenate([x, y])
final_model = Sequential()
final_model.add(merged)
final_model.add(Dense(100, activation='relu'))
final_model.add(Dense(3, activation='softmax'))

Till here, my understanding is that, output from two models as x and y are merged and given as input to the third model.到这里为止,我的理解是,两个模型的输出作为 x 和 y 被合并并作为输入给第三个模型。 But when I fit this all like,但是当我适应这一切时,

module3.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
module3.fit([in1, in2], np_res_array)

in1 and in2 are two numpy ndarray of dimention 10000*750 which contains my training data and np_res_array is the corresponding target. in1 和 in2 是两个维度为 10000*750 的 numpy ndarray,其中包含我的训练数据,np_res_array 是相应的目标。
This gives me error as 'list' object has no attribute 'shape' As far as know, this is how we give multiple inputs to a model, but what is this error?这给了我错误,因为 'list' 对象没有属性 'shape'据我们所知,这就是我们向模型提供多个输入的方式,但这个错误是什么? How do I resolve it?我该如何解决?

You can't do this using Sequential API.您不能使用 Sequential API 执行此操作。 That's because of two reasons:这是因为两个原因:

  1. Sequential models, as their name suggests, are a sequence of layers where each layer is connected directly to its previous layer and therefore they cannot have branches (eg merge layers, multiple input/output layers, skip connections, etc.).顺序模型,顾名思义,是一系列层,其中每一层都直接连接到其前一层,因此它们不能有分支(例如合并层、多个输入/输出层、跳过连接等)。

  2. The add() method of Sequential API accepts a Layer instance as its argument and not a Tensor instance. Sequential API 的add()方法接受一个Layer实例作为它的参数,而不是一个Tensor实例。 In your example merged is a Tensor (ie concatenation layer's output).在您的示例中, merged是张量(即连接层的输出)。

Further, the correct way of using Concatenate layer is like this:此外, Concatenate层的正确使用方法是这样的:

merged = Concatenate()([x, y])

However, you can also use concatenate (note the lowercase "c"), its equivalent functional interface, like this:但是,您也可以使用concatenate (注意小写的“c”),它的等效功能接口,如下所示:

merged = concatenate([x, y])

Finally, to be able to construct that third model you also need to use the functional API .最后,为了能够构建第三个模型,您还需要使用功能 API

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

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