【问题标题】:How to merge two layers of different shapes for an LSTM input?如何为 LSTM 输入合并两层不同形状的层?
【发布时间】:2019-01-25 15:49:01
【问题描述】:

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

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

我想将层 l1l2 组合起来,然后将它们提供给双 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 ...

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

【问题讨论】:

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


    【解决方案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=1K.transpose 相同,与 Numpy 不同,它不提供指定应交换的轴的方法(因此使用 reshape)。

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2020-08-31
      • 2019-01-22
      • 2019-09-11
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多