添加的图层必须是 class 图层的实例

The added layer must be an instance of class Layer

我正在为两个 LSTM 模型合并两个嵌入层,如下所示: Code here in this image

当我构建顺序模型时,它给了我一个错误。

model = Sequential()
merged = Concatenate(axis=1)([s1rnn.output,s2rnn.output])
model.add(merged)
model.add(Dense(1))
model.compile(loss='categorical_crossentropy', optimizer='adam',  metrics=['accuracy'])
model.fit([X1,X2], Y,batch_size=128, nb_epoch=20, validation_split=0.05)

TypeError: The added layer must be an instance of class Layer. Received: layer=KerasTensor(type_spec=TensorSpec(shape=(None, 110, 1), dtype=tf.float32, name=None), name='concatenate/concat:0', description="created by layer 'concatenate'") of type <class 'keras.engine.keras_tensor.KerasTensor'>.

您要在其中添加 Concatenate() 层作为输入的 model 必须是 Functional() 而不是 Sequential() 类型(这是第一步修改你的代码)。

结构应该类似于(注意末尾的括号:如何在函数 API 中添加层):

input_s1rnn= Input(shape=(...))
input_s2rnn= Input(shape=(...))
merged = Concatenate([s1_rnnmodel(input_s1rnn), s2_rnnmodel(input_s2rnn)],axis=1)
layer_1_model = some_layer()(merged)
layer_2_model = some_layer()(layer_1_model)
...
output_layer = Dense(1,activation='sigmoid')(layer_2_model)
model= Model([input_s1rnn, input_s2rnn], output_layer)