有没有办法用特定的垫值将一个可变大小的张量填充到给定的形状?例如,鉴于张量:
[[1, 2],
[3, 4]]
Run Code Online (Sandbox Code Playgroud)
和
[[1, 2, 3],
[4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)
有没有办法有一个通用的操作,可以采取任何一个并用一个值填充它们(比如,[2, 4]用值塑造-1)导致:
[[1, 2, -1, -1],
[3, 4, -1, -1]]
Run Code Online (Sandbox Code Playgroud)
和
[[1, 2, 3, -1],
[4, 5, 6, -1]]
Run Code Online (Sandbox Code Playgroud)
分别?我的推理(如果有更好的解决方案)是我有TFRecords文件的示例,其中一部分具有可变长度.对于处理,静态长度使它们更易于使用.
Mul*_*ter 15
是.有.如果您不需要更改张量的等级,则非常简单.
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)
Run Code Online (Sandbox Code Playgroud)
如果你想将它概括为一个有用的函数,你可以这样做:
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)
Run Code Online (Sandbox Code Playgroud)
其中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
Run Code Online (Sandbox Code Playgroud)
要么
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})
Run Code Online (Sandbox Code Playgroud)
尽管尺寸大小是动态计算的,但尺寸数不是,因此请确保max_in_dims元素的数量与t.shape相同.
| 归档时间: |
|
| 查看次数: |
8875 次 |
| 最近记录: |