【问题标题】:Custom reshaping layer return Tensor with shape (?,?,?)自定义重塑层返回形状为 (?,?,?) 的张量
【发布时间】:2019-05-13 12:52:55
【问题描述】:

我需要一个层将 4D 张量从形状为 (None, 3, 3, 2048) 的卷积层重塑为形状为 (None, 9, 2048) 的 3D 张量,以输入 LSTM,其中 9 是时间步长维度的大小。

当我使用层本身时它可以工作,但是当我在顺序模型中使用它时,下一层从我的自定义层的输出中获取 (?,?,?) input_shape

您可以在下面找到我的代码:

class Conv2LSTM(Layer):

    '''The :class:`Conv2LSTM` is a custom layer that reshapes the input tensor collapsing the width and height dimensions to a single dimension that represents the sequence accepted by the LSTM.
    '''

    def __init__(self, **kwargs):
        super(Conv2LSTM, self).__init__(**kwargs)

    def build(self, input_shape):
        self.input_spec = [InputSpec(shape=input_shape)]
        super(Conv2LSTM, self).build(input_shape)

    def call(self, x, mask=None):

        '''Overrides the :class:`keras.engine.topology.Layers` method. It collapses the second and third dimension of the tensor into a single dimension.

        :param x: input tensor
        :param mask: tensor mask
        :return: re-ordered tensor
        '''

        return K.reshape(x, (K.shape(x)[0],) + (K.shape(x)[1]*K.shape(x)[2], K.shape(x)[3]))

    def get_config(self):
        base_config = super(Conv2LSTM, self).get_config()
        return dict(list(base_config.items()))

    def compute_output_shape(self, input_shape):
        return (input_shape[0],) + (input_shape[1]*input_shape[2], input_shape[3])

如果我在层内打印形状是正确的,如果我创建一个具有该单层的模型,它如何工作,但与连续的层结合,它会返回一个 NoneType 形状,这怎么可能?

【问题讨论】:

    标签: tensorflow keras conv-neural-network lstm reshape


    【解决方案1】:

    由于某些原因,在其他类似问题的每个答案中,建议使用K.shape(x) 来检索输入张量的形状,在这种情况下,错误是由它引起的。

    K.shape(x)[i] 替换为x.shape[i].value 就足够了。

    call 的新实现是:

    return K.reshape(x, (-1, x.shape[1].value * x.shape[2].value, x.shape[3].value))

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多