如何为LSTM输入合并两个不同形状的图层?

时间:2019-01-25 15:49:01

标签: python-3.x merge keras-layer

我想在网络中合并2个不同层的输出,如下所示:

l1.shape
TensorShape([Dimension(None), Dimension(10), Dimension(100)])
l2.shape
TensorShape([Dimension(None), Dimension(20), Dimension(30)])

我想合并l1l2层,然后将它们馈送到bi-LSTM层。我尝试了“连接”层,但是它不起作用。我希望某些东西可以填充较低的最后一个尺寸的图层,以获得与其他图层相同的尺寸。即:将l2的最后一个维度填充两个值:

l2_padded = some_function(l2, axis=-1, dim=l1.shape[-1])
l2_padded.shape
TensorShape([Dimension(None), Dimension(20), Dimension(100)])

然后执行串联,

c = Concatenate(axis=1)([l1, l2_padded])
c.shape
TensorShape([Dimension(None), Dimension(30), Dimension(100)])
bilstm = Bidirectional(LSTM(100))(c)
# other layers ...

您能举一些例子和/或参考吗?

1 个答案:

答案 0 :(得分:1)

您可以结合使用reshapeZeroPadding1D

import tensorflow.keras.backend as K
from tensorflow.keras.layers import ZeroPadding1D

x1 = Input(shape=(10, 100))
x2 = Input(shape=(20, 30))
x2_padded = K.reshape(
    ZeroPadding1D((0, x1.shape[2] - x2.shape[2]))(
        K.reshape(x2, (-1, x2.shape[2], x2.shape[1]))
    ),
    (-1, x2.shape[1], x1.shape[2])
)

它看起来有些笨拙,但不幸的是ZeroPadding1D不允许指定填充轴,并且将始终使用axis=1。与K.transpose相同,与Numpy不同,它没有提供指定应该交换的轴的方法(因此使用reshape)。

相关问题