2017-02-20 335 views
1

有没有办法来垫可变大小的张量给定的形状与特定的填充值?例如,给定张量:TensorFlow - 将未知尺寸张量填充到特定尺寸?

[[1, 2], 
[3, 4]] 

[[1, 2, 3], 
[4, 5, 6]] 

有没有办法让这将需要或者并用价值垫它们的通用操作(比如,与价值,塑造[2, 4]-1)导致:

[[1, 2, -1, -1], 
[3, 4, -1, -1]] 

[[1, 2, 3, -1], 
[4, 5, 6, -1]] 

分别?我的推理(如果有一个更好的解决方案)是,我有从TFRecords文件,其中有一部分具有可变长度的例子。对于处理,静态长度使它们更容易处理。

回答

-1

有一个在TensorFlow没有办法做this.You将不得不对数据进行预处理,并添加-1一套让你需要的长度。例如,通过list[0].append(-1)list[1].append(-1)得到所需长度和循环的长度 - 列表的长度。希望这可以帮助!

0

我遇到了类似的事情。不完全一般,但你可以做类似:

test_a = tf.constant([[1, 2], [3, 4]]) 
test_b = tf.constant([[1, 2, 3], [4, 5, 6]]) 

def pad_second_dim(input, desired_size): 
    padding = tf.tile([[0]], tf.stack([tf.shape(input)[0], desired_size - tf.shape(input)[1]], 0)) 
    return tf.concat([input, padding], 1) 

with tf.Session() as sess: 
    print sess.run(pad_second_dim(test_a, 4)) 
    # [[1 2 0 0] [3 4 0 0]] 
    print sess.run(pad_second_dim(test_b, 4)) 
    # [[1 2 3 0] [4 5 6 0]] 
1

是的。有。如果你不需要改变张量的等级,那很简单。

tf.pad()接受与张量是常规的Python列表。填充格式是在该维度的每一边填充多少对的列表。

例如

t = tf.constant([[1, 2], [3, 4]]) 
paddings = [[0, 0], [0, 4-tf.shape(t)[0]]] 
out = tf.pad(t, paddings, 'CONSTANT', constant_values=-1) 
sess.run(out) 
# gives: 
# array([[ 1, 2, -1, -1], 
#  [ 3, 4, -1, -1]], dtype=int32) 

如果要概括这一个有用的功能,你可以这样做:

def pad_up_to(t, max_in_dims, constant_values): 
    s = tf.shape(t) 
    paddings = [[0, m-s[i]] for (i,m) in enumerate(max_in_dims)] 
    return tf.pad(t, paddings, 'CONSTANT', constant_values=constant_values) 

其中max_in_dims基本上是输出所需要的形状。 注意:如果您在任何维度中提供严格小于t的形状,则此功能将失败。

你可以用它喜欢:

t = tf.constant([[1, 2], [3, 4]]) # shape = [2, 2] 
t_padded = pad_up_to(t, [2, 4], -1) # shape = [2, 4], padded with -1s