【问题标题】:Tensorflow: How can I use tf.roll without wrapping?Tensorflow:如何在不包装的情况下使用 tf.roll?
【发布时间】:2020-08-10 20:55:07
【问题描述】:

我想独立移动二维张量的列或行,例如:

a = tf.constant([[1,2,3], [4,5,6]])
shift = tf.constant([2, -1])
b = shift_fn(a, shift)

这给了我:

b = [[0, 0, 1], [5, 6, 0]]

我发现tf.roll() 可以做类似的事情,但会包装元素。如何使用它填充零?

【问题讨论】:

  • 澄清一下,你想要每行(或列)独立的循环移位吗?
  • 不,对于每一行或每一列,都有一个指定的班次。但我不希望它是循环的。

标签: python tensorflow tensor


【解决方案1】:

一个不太好的解决方案是首先使用tf.pad 填充张量,然后在tf.map_fn 中使用tf.roll 来独立移动填充张量的每一行(或列) .最后,您可以从结果中提取适当的部分。例如:

a = tf.constant([[1,2,3], [4,5,6]])
shift = tf.constant([2, -1])

cols = a.shape[1]
paddings = tf.constant([[0, 0], [cols, cols]])
padded_a = tf.pad(a, paddings)

tf.map_fn(
    lambda x: tf.roll(x[0], x[1], axis=-1),
    elems=(padded_a, shift),
    # The following argument is required here
    fn_output_signature=a.dtype
)[:,cols:cols*2]

"""
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[0, 0, 1],
       [5, 6, 0]], dtype=int32)>
"""

另外,为了节省一些内存,填充和切片都可以在传递给tf.map_fnfn 函数内完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多