python - 如何在 Keras 中组合两个具有不同输入大小的 LSTM 层?

标签 python keras deep-learning classification lstm

我有两种类型的输入序列,其中 input1 包含 50 个值,input2 包含 25 个值。我尝试在函数式 API 中使用 LSTM 模型来组合这两种序列类型。然而,由于我的两个输入序列的长度不同,我想知道我当前所做的是否是正确的方法。我的代码如下:

input1 = Input(shape=(50,1))
x1 = LSTM(100)(input1)
input2 = Input(shape=(25,1))
x2 = LSTM(50)(input2)

x = concatenate([x1,x2])
x = Dense(200)(x)
output = Dense(1, activation='sigmoid')(x)

model = Model(inputs=[input1,input2], outputs=output)

更具体地说,我想知道如何组合两个具有不同输入长度的 LSTM 层(即在我的例子中为 50 和 25)。如果需要,我很乐意提供更多详细信息。

最佳答案

实际上,在 NLP 这样的任务中,你的问题很正常,因为序列的长度不同。在您的评论中,您使用 return_sequences=False 丢弃了之前的所有输出,这在我们的实践中并不常见,通常会导致性能较低的模型。

注意:神经网络架构设计没有终极解决方案

这是我的建议。

方法 1(无需自定义图层)

您可以在两个 LSTM 中使用相同的潜在维度,并将它们堆叠在二维中,并将它们视为一个大的隐藏层张量。

input1 = Input(shape=(50,1))
x1 = LSTM(100, return_sequences=True)(input1)
input2 = Input(shape=(25,1))
x2 = LSTM(100, return_sequences=True)(input2)
x = concatenate([x1,x2], axis=1)

# output dimension = (None, 75, 100)

如果你不想拥有相同的潜在维度,其他人所做的就是添加 1 个以上的部分,我们通常称之为映射层,它由密集层的堆叠组成。这种方法有更多的变量,这意味着模型更难训练。

input1 = Input(shape=(50,1))
x1 = LSTM(100, return_sequences=True)(input1)
input2 = Input(shape=(25,1))
x2 = LSTM(50, return_sequences=True)(input2)

# normally we have more than 1 hidden layer
Map_x1 = Dense(75)(x1)
Map_x2 = Dense(75)(x2)
x = concatenate([Map_x1 ,Map_x2 ], axis=1)

# output dimension = (None, 75, 75)

或者压平输出(两者)

input1 = Input(shape=(50,1))
x1 = LSTM(100, return_sequences=True)(input1)
input2 = Input(shape=(25,1))
x2 = LSTM(50, return_sequences=True)(input2)

# normally we have more than 1 hidden layer
flat_x1 = Flatten()(x1)
flat_x2 = Flatten()(x2)
x = concatenate([flat_x1 ,flat_x2 ], axis=1)

# output (None, 2650)

方法 2(需要自定义层)

创建自定义层并使用注意力机制来生成注意力向量,并使用该注意力向量作为 LSTM 输出张量的表示。其他人所做的并获得更好的性能是使用 LSTM 的最后一个隐藏状态(仅在模型中使用)和注意向量作为表示。

注意:根据研究,不同类型的注意力几乎具有相同的性能,因此我推荐“缩放点积注意力”,因为它的计算速度更快。

input1 = Input(shape=(50,1))
x1 = LSTM(100, return_sequences=True)(input1)
input2 = Input(shape=(25,1))
x2 = LSTM(50, return_sequences=True)(input2)

rep_x1 = custom_layer()(x1)
rep_x2 = custom_layer()(x2)
x = concatenate([rep_x1 ,rep_x2], axis=1)

# output (None, (length rep_x1+length rep_x2))

关于python - 如何在 Keras 中组合两个具有不同输入大小的 LSTM 层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60679680/

相关文章:

python - 通过匹配列表的字符串列表获取列表索引

python - 在 Python 中解调 FSK 信号

python - 在 TensorFlow 上使用 Inception 时出错(所有图片的输出相同)

python - Keras - 用于文本分析的自动编码器

tensorflow - TF2 - GradientTape 与 Model.fit() - 为什么 GradientTape 不起作用?

python - 如何使用 Python 获取具有最大值的行?

python - 无法从子进程解析 xml。Python 中的 Popen 输出

python - Keras:test_on_batch 和 predict_on_batch 之间的区别

python - 从保存的模型进行预测时,测试数据预测会产生随机结果

opencv - 如何从收据中提取相关信息