gpt4 book ai didi

python - Tensorflow 动态填充

转载 作者:行者123 更新时间:2023-12-05 06:54:47 25 4
gpt4 key购买 nike

我想填充一个张量。在下面的示例中,我将输入张量展平,然后将其填充到 900 大小。填充 x 在使用文字整数填充时效果很好,例如:

num_units = 900

print('*** inputTensor')
print(inputTensor)

x = tf.keras.layers.Flatten()(inputTensor)
print('*** x before padding')
print(x)

paddings = [[0, 0], [0, 584]] # OK
x = tf.pad(x, paddings)

print('*** x after padding')
print(x)

结果:

*** inputTensor
KerasTensor(type_spec=TensorSpec(shape=(None, 79, 4), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'")
*** x before padding
KerasTensor(type_spec=TensorSpec(shape=(None, 316), dtype=tf.float32, name=None), name='flatten/Reshape:0', description="created by layer 'flatten'")
*** x after padding
KerasTensor(type_spec=TensorSpec(shape=(None, 900), dtype=tf.float32, name=None), name='tf.compat.v1.pad/Pad:0', description="created by layer 'tf.compat.v1.pad'")

但是如果我在运行时计算填充值,它就不起作用了。我已经尝试了多种设置值的方法来替换上面标记为 OK 的行中的 584,但没有任何效果:

paddings = [[0, 0], [0, num_units - tf.shape(x)[1]]] # no good
paddings = [[0, 0], [0, num_units - tf.size(x)]] # no good

以上两种(和其他方法)都将 x 的最终形状更改为 (None, None):

*** x after padding
KerasTensor(type_spec=TensorSpec(shape=(None, None), dtype=tf.float32, name=None), name='tf.compat.v1.pad/Pad:0', description="created by layer 'tf.compat.v1.pad'")

好像tf.pad需要整数值,而计算结果是张量。我错过了什么?

更新

使用 this thread 中的技术让它工作:

num_units = 900
print('inputTensor.shape', inputTensor.shape)
x = tf.keras.layers.Flatten()(inputTensor)
print('after flatten', x.shape)
x = tf.keras.layers.Reshape([-1, 1])(x)
print('after reshape', x.shape)
pad_amount = num_units - x.shape[1]
print('pad_amount', pad_amount)
x = tf.keras.layers.ZeroPadding1D(padding=(0, pad_amount))(x)
print('after padding', x.shape)
x = tf.keras.layers.Reshape([-1])(x)
print('after reshape', x.shape)

输出:

inputTensor.shape (None, 79, 4)
after flatten (None, 316)
after reshape (None, 316, 1)
pad_amount 584
after padding (None, 900, 1)
after reshape (None, 900)

最佳答案

已解决 - 查看添加到原始问题中的技术。

关于python - Tensorflow 动态填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65461355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com