numpy Tensorflow Tensor整形并填充零

qoefvg9y  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(77)

有没有一种方法可以重塑Tensor并用零填充任何溢出?我知道ndarray.reshape可以做到这一点,但据我所知,将Tensor转换为ndarray需要在GPU和CPU之间进行翻转。
Tensorflow的reshape()文档说TensorFlow需要有相同数量的元素,所以也许最好的方法是pad()然后reshape()?
我在努力实现:

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

hfwmuf9z1#

据我所知,没有内置的操作符可以做到这一点(如果形状不匹配,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])
njthzxwz

njthzxwz2#

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

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

从上面的docs示例:

# '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]]

相关问题