2015-12-07 117 views
7

有没有一种方法来重塑张量和用零填充任何溢出?我知道ndarray.reshape这样做,但据我所知,将张量转换为ndarray需要在GPU和CPU之间进行触发。 Tensorflow的reshape()文档说TensorShapes需要有相同数量的元素,所以也许最好的方法是pad()然后重塑()?Tensorflow张量重塑和零填充

我想要实现:

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

回答

7

Tensorflow现在提供其在许多方面对张进行填充(如用于数组opencv2的填充功能)垫功能:

# '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]] 
:从上面的文档

https://www.tensorflow.org/versions/r0.8/api_docs/python/array_ops.html#pad

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

示例

10

据我所知,没有内置运营商做这个(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(0, [a_as_vector, zero_padding]) 

# Reshape the padded vector to the desired shape. 
result = tf.reshape(a_padded, [2, 3])