是的。有。如果你不需要改变张量的等级,那很简单。
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