tensorflow版本的Torch nn.DepthConcat

时间:2016-08-16 21:54:14

标签: tensorflow torch

Torch的函数nn.DepthConcat类似于nn.Concat,除了用零填充以使所有非通道调光大小相同。我一直试图通过一点运气来实现这一点。如果我在图形构建时知道所有张量的大小,这似乎有效:

    def depthconcat(inputs):
        concat_dim = 3
        shapes = []
        for input_ in inputs:
            shapes.append(input_.get_shape())
        shape_tensor = tf.pack(shapes)
        max_dims = tf.reduce_max(shape_tensor, 0)

        padded_inputs = []
        for input_ in inputs:
            paddings = max_dims - input_.get_shape()
            padded_inputs.append(tf.pad(input_, paddings))
        return tf.concat(concat_dim, padded_inputs)

但是,如果在运行时确定形状,则会出现以下错误:

    Tensors in list passed to 'values' of 'Pack' Op have types [<NOT CONVERTIBLE TO TENSOR>, <NOT CONVERTIBLE TO TENSOR>, <NOT CONVERTIBLE TO TENSOR>, <NOT CONVERTIBLE TO TENSOR>] that don't all match.

如果它在图形构建时完全定义,它似乎能够将TensorShape对象转换为张量。有什么建议?感谢。

编辑: 从input_.get_shape()更改为tf.shape(input_)解决了图创建时模糊形状的问题。现在我得到ValueError: Shape (4,) must have rank 2

1 个答案:

答案 0 :(得分:0)

我希望这可以帮助其他人尝试构建具有不同输出大小的初始模块。

def depthconcat(inputs):
    concat_dim = 3
    shapes = []
    for input_ in inputs:
        shapes.append(tf.to_float(tf.shape(input_)[:3]))
    shape_tensor = tf.pack(shapes)
    max_dims = tf.reduce_max(shape_tensor, 0)

    padded_inputs = []
    for idx, input_ in enumerate(inputs):
        mean_diff = (max_dims - shapes[idx])/2.0
        pad_low = tf.floor(mean_diff)
        pad_high = tf.ceil(mean_diff)
        paddings = tf.to_int32(tf.pack([pad_low, pad_high], axis=1))
        paddings = tf.pad(paddings, paddings=[[0, 1], [0, 0]])
        padded_inputs.append(tf.pad(input_, paddings))

     return tf.concat(concat_dim, padded_inputs, name=name)