是的。有。只要你不需要改变张量的秩,就很简单了。
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
或
t = tf.placeholder(tf.float32, [None, None]) # shape = [?, ?]
t_padded = pad_up_to(t, [5,5], -1) # shape = [5, 5], padded with -1s
t_np = np.random.uniform(0, 1, [3,4]) # shape = [3,4], no padding
t_padded_out = sess.run(t_padded, {t: t_np})
t_np2 = np.random.uniform(0, 1, [2,1]) # shape = [2,1], no padding
t_padded_out2 = sess.run(t_padded, {t: t_np2})
虽然维度大小是动态计算的,但维度数量不是,所以要确保max_in_dims与t.shape的元素数量相同。