Keras 序列模型的多个输入 [英] Multiple inputs to Keras Sequential model

查看:38
本文介绍了Keras 序列模型的多个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并来自两个模型的输出,并将它们作为使用 keras 序列模型的第三个模型的输入.模型 1:

I am trying to merge output from two models and give them as input to the third model using keras sequential model. Model1 :

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

模型 1:

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

模型 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'))

到这里为止,我的理解是,两个模型的输出作为 x 和 y 被合并并作为输入给第三个模型.但是当我适应这一切时,

Till here, my understanding is that, output from two models as x and y are merged and given as input to the third model. But when I fit this all like,

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

in1 和 in2 是两个维度为 10000*750 的 numpy ndarray,其中包含我的训练数据,np_res_array 是相应的目标.
这给了我错误,因为list"对象没有属性shape" 据了解,这就是我们给模型提供多个输入的方式,但是这个错误是什么?我该如何解决?

in1 and in2 are two numpy ndarray of dimention 10000*750 which contains my training data and np_res_array is the corresponding target.
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? How do I resolve it?

推荐答案

您无法使用 Sequential API 执行此操作.这是因为两个原因:

You can't do this using Sequential API. That's because of two reasons:

  1. 序列模型,顾名思义,是一系列层,其中每一层都直接与其前一层相连,因此它们不能有分支(例如合并层、多个输入/输出层、跳过连接等).).

  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 (e.g. merge layers, multiple input/output layers, skip connections, etc.).

Sequential API 的 add() 方法接受一个 Layer 实例作为它的参数,而不是一个 Tensor 实例.在您的示例中,merged 是一个张量(即连接层的输出).

The add() method of Sequential API accepts a Layer instance as its argument and not a Tensor instance. In your example merged is a Tensor (i.e. concatenation layer's output).

另外,Concatenate层的正确使用方法是这样的:

Further, the correct way of using Concatenate layer is like this:

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

但是,您也可以使用 concatenate(注意小写的c"),它的等效功能接口,如下所示:

However, you can also use concatenate (note the lowercase "c"), its equivalent functional interface, like this:

merged = concatenate([x, y])

最后,为了能够构建第三个模型,您还需要使用 functionalAPI.

Finally, to be able to construct that third model you also need to use the functional API.

这篇关于Keras 序列模型的多个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆