我对以下代码感到困惑:y = x
和y = tf.identity(x)
。
更准确地说,当我运行以下代码片段时,我感到困惑:
代码1:
import tensorflow as tf
x = tf.Variable(0.0, name="x")
with tf.control_dependencies([x_plus_1]):
y = x
init = tf.initialize_all_variables()
with tf.Session() as sess:
init.run()
for i in range(5):
print(y.eval())
这将给出输出:0.0 0.0 0.0 0.0 0.0
代码2:
import tensorflow as tf
x = tf.Variable(0.0, name="x")
with tf.control_dependencies([x_plus_1]):
y = tf.identity(x, name='id')
init = tf.initialize_all_variables()
with tf.Session() as sess:
init.run()
for i in range(5):
print(y.eval())
唯一的变化来自 y=x
至y=tf.identity(x)
,但现在结果是1.0 2.0 3.0 4.0 5.0
非常感谢。
最佳答案
x
是一个张量,我们称之为 tensor_1
。当您说 y = x
时,您是在说变量 y
具有张量 tensor_1
的值。当您执行 y = tf.identity(x)
时,您将创建一个新的张量 tensor_2
,其值与 tensor_1
相同。但它是图中的不同节点,因此从 tensor_1
到 tensor_2
的值必须移动。这就是为什么 with tf.control_dependency([x_plus_1])
在第二个代码中执行某些操作,但在第一个代码中执行任何操作。因为在第一个代码中,您没有创建 control_depdendency
可以使用的任何新张量。
综上所述,y = x
使变量 y
指向 x
中的同一个对象,但 y = tf .identity(x)
使用 x
的内容创建一个新对象。
关于python - tensorflow 中的 "y=x"和 y=tf.identity(x) 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49880372/