【问题标题】:Tensorflow Tensor reshape and pad with zerosTensorflow 张量重塑并用零填充
【发布时间】:2016-03-12 12:28:21
【问题描述】:

有没有办法重塑张量并用零填充任何溢出?我知道 ndarray.reshape 会这样做,但据我了解,将张量转换为 ndarray 需要在 GPU 和 CPU 之间进行翻转。

Tensorflow 的 reshape() 文档说 TensorShapes 需要具有相同数量的元素,所以最好的方法可能是 pad() 然后 reshape()?

我正在努力实现:

a = tf.Tensor([[1,2],[3,4]])
tf.reshape(a, [2,3])
a => [[1, 2, 3],
      [4, 0 ,0]]

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    据我所知,没有内置的运算符可以做到这一点(如果形状不匹配,tf.reshape() 会给你一个错误)。但是,您可以使用几个不同的运算符实现相同的结果:

    a = tf.constant([[1, 2], [3, 4]])
    
    # Reshape `a` as a vector. -1 means "set this dimension automatically".
    a_as_vector = tf.reshape(a, [-1])
    
    # Create another vector containing zeroes to pad `a` to (2 * 3) elements.
    zero_padding = tf.zeros([2 * 3] - tf.shape(a_as_vector), dtype=a.dtype)
    
    # Concatenate `a_as_vector` with the padding.
    a_padded = tf.concat([a_as_vector, zero_padding], 0)
    
    # Reshape the padded vector to the desired shape.
    result = tf.reshape(a_padded, [2, 3])
    

    【讨论】:

    • 最近一次 TensorFlow 更新,现在是 a_padded = tf.concat([a_as_vector, zero_padding],0)
    【解决方案2】:

    Tensorflow 现在提供 pad 函数,它以多种方式在张量上执行填充(如 opencv2 的数组填充函数): https://www.tensorflow.org/api_docs/python/tf/pad

    tf.pad(tensor, paddings, mode='CONSTANT', name=None)
    

    来自上述文档的示例:

    # 't' is [[1, 2, 3], [4, 5, 6]].
    # 'paddings' is [[1, 1,], [2, 2]].
    # rank of 't' is 2.
    pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],
                                      [0, 0, 1, 2, 3, 0, 0],
                                      [0, 0, 4, 5, 6, 0, 0],
                                      [0, 0, 0, 0, 0, 0, 0]]
    
    pad(t, paddings, "REFLECT") ==> [[6, 5, 4, 5, 6, 5, 4],
                                     [3, 2, 1, 2, 3, 2, 1],
                                     [6, 5, 4, 5, 6, 5, 4],
                                     [3, 2, 1, 2, 3, 2, 1]]
    
    pad(t, paddings, "SYMMETRIC") ==> [[2, 1, 1, 2, 3, 3, 2],
                                       [2, 1, 1, 2, 3, 3, 2],
                                       [5, 4, 4, 5, 6, 6, 5],
                                       [5, 4, 4, 5, 6, 6, 5]]
    

    【讨论】:

    • 如果我们想做这样的事情怎么办[1,pad,2,pad,3,pad,5,pad,pad,6,pad]如何使用零填充和遮罩层。请问你有什么想法吗。
    • @DINATAKLIT 可以像 Pad with PaddingConfig 这样的东西帮助完成您正在寻找的东西吗?我在我不熟悉的 TF XLA 中发现了这个……有人知道在原版 TF 中这样做的方法吗?这是来源(注图片):tensorflow.org/xla/operation_semantics#pad
    • 回答这个问题而不是复制/过去文档会很棒
    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2016-10-18
    • 1970-01-01
    • 2023-03-29
    • 2020-10-31
    • 1970-01-01
    • 2016-02-15
    • 2019-10-09
    相关资源
    最近更新 更多