复制 Tensorflow 张量的正确方法是什么?在常规 Python 中,非基元赋值 (b = a
) 会创建对同一对象的引用,因此我们使用 deepcopy。 Tensorflow 中是否同样需要 tf.identity
,或者 Tensorflow 是否将 b
视为 b = a
之后的唯一张量?
我的具体需求总结如下。我正在构建一个块中的模型,每个块都获取前一个块的输出,通过层馈送它,然后与前一个块的原始原始输出相加。看到标记为方法 A 和方法 B 的 2 行。哪个是正确的?
for block_num in range(4):
if block_num == 0:
x = inputTensor
x = tf.keras.layers.Dense(100, activation='relu')(x)
if block_num > 0:
x = block_output_tensor + x
# method A - assignment
block_output_tensor = x
# method B - copy
# block_output_tensor = tf.identity(x)
答案 0 :(得分:0)
在您的情况下,简单的赋值 block_output_tensor = x
应该可以正常工作。只需重新排列行,在使用前定义 block_output_tensor
。
然而,在一些更复杂的情况下,使用 tf.identity()
确保正确的图形布局很重要。请参阅讨论的此问题 here at SO。