如何使用 Keras 合并或连接两个顺序模型?

Moi*_*Dey 1 nlp artificial-intelligence deep-learning keras

我有一个包含两个文本字段的数据集,在标记化之后,我制作了两个连续模型,我试图组合或合并它们,但在合并时遇到错误。

我已经构建了两个顺序模型,并且正在尝试在不使用 Keras 功能 API 的情况下合并它们。

# define the model
model1 = Sequential()
model1.add(Embedding(vocabulary_size_1, embedding_size, input_length=MAXLEN))
model1.add(Flatten())
model1.add(Dense(op_units, activation='softmax'))

# define the model
model2 = Sequential()
model2.add(Embedding(vocabulary_size_2, embedding_size, input_length=MAXLEN))
model2.add(Flatten())
model2.add(Dense(op_units, activation='softmax'))

merged = concatenate(axis=1)
merged_model=merged([model1.output, model2.ouput])

TypeError                                 Traceback (most recent call last)
<ipython-input-76-79cf08fec6fc> in <module>
----> 1 merged = concatenate(axis=1)
      2 merged_model=merged([model1.output, model2.ouput])

TypeError: concatenate() missing 1 required positional argument: 'inputs'
Run Code Online (Sandbox Code Playgroud)

我期待一种不使用 Keras 功能 API 的方法

Ash*_*'Sa 5

这些concatenate()函数要求您指定要连接的模型。

merged = concatenate([model1,model2],axis=1)。但是,轴必须是 axis=-1 (您可以使用适合您情况的任何内容。)

您的代码可以进一步以函数方式编写,如下所示:

inputs = Input(shape=(vocabulary_size,embedding_size), dtype='float32')

model1=Embedding(vocabulary_size, embedding_size)(inputs)
model1=Flatten()(model1)
model1=Dense(op_units, activation='softmax')(model1)

model2=Embedding(vocabulary_size, embedding_size)(inputs)
model2=Flatten()(model2)
model2=Dense(op_units,activation='softmax')(model2)

merged = concatenate([model1,model2],axis=-1)

model=Model(inputs=inputs,outputs=merged)
Run Code Online (Sandbox Code Playgroud)