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

EmJ*_*EmJ 2 python classification deep-learning lstm keras

我有两种类型的输入序列,其中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)
Run Code Online (Sandbox Code Playgroud)

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

Ron*_* W. 5

实际上,在像 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)
Run Code Online (Sandbox Code Playgroud)

如果你不想拥有相同的潜在维度,其他人所做的就是添加 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)
Run Code Online (Sandbox Code Playgroud)

或者展平输出(两者)

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)
Run Code Online (Sandbox Code Playgroud)

方法2(需要自定义图层)

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

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

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))
Run Code Online (Sandbox Code Playgroud)