如何合并两层不同形状的 LSTM 输入?
How to merge two layers of different shapes for an LSTM input?
我想在我的网络中组合 2 个不同层的输出,如下所示:
l1.shape
TensorShape([Dimension(None), Dimension(10), Dimension(100)])
l2.shape
TensorShape([Dimension(None), Dimension(20), Dimension(30)])
我想合并 l1
和 l2
层,然后将它们提供给双 LSTM 层。我尝试了 "Concatenate" 层,但它不起作用。我想要一些可以填充具有较低最后维度的层以获得与另一层相同的维度的东西。即:填充 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 ...
你能举一些例子吗and/or参考文献?
您可以使用 reshape
and ZeroPadding1D
:
的组合
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
)。
我想在我的网络中组合 2 个不同层的输出,如下所示:
l1.shape
TensorShape([Dimension(None), Dimension(10), Dimension(100)])
l2.shape
TensorShape([Dimension(None), Dimension(20), Dimension(30)])
我想合并 l1
和 l2
层,然后将它们提供给双 LSTM 层。我尝试了 "Concatenate" 层,但它不起作用。我想要一些可以填充具有较低最后维度的层以获得与另一层相同的维度的东西。即:填充 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 ...
你能举一些例子吗and/or参考文献?
您可以使用 reshape
and ZeroPadding1D
:
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
)。