Tensorflow:tf.identity和' ='之间有什么区别?操作者

时间:2018-03-08 13:07:06

标签: python tensorflow graph variable-assignment assignment-operator

我对'='运算符和tf.identity()感到困惑,我认为'='只是引用张量,而标识就是复制,例如,

ref = x
ref = ref*0
sess.run(x)

我将x全部设置为0元素,并使用

copy = tf.identity(x)
copy = ref*0
sess.run(x)

x不会被更改,因为身份会复制,而不是参考,但是通过实验,'='也会复制并且x未设置为0,那么&# 39;区别?

2 个答案:

答案 0 :(得分:2)

区别仅在于张量图布局。 tf.identity在图中创建了一个模拟其参数的 new op ,而纯赋值会添加一个指向同一操作的 new python变量

在这两种情况下(对refx或对copyx),两个操作总是评估为相同的值。但在第二种情况下,tf.get_default_graph().get_operations()将在列表中显示一个名为Identity的新操作。

sess = tf.InteractiveSession()
x = tf.Variable(1.0)
sess.run(x.initializer)

ref = x
copy = tf.identity(x)
print(x.eval(), copy.eval(), ref.eval())  # 1.0 1.0 1.0

sess.run(x.assign(2.0))
print(x.eval(), copy.eval(), ref.eval())  # 2.0 2.0 2.0

print(tf.get_default_graph().get_operations())

你可能想知道,为什么有人想在她完成任务时引入新的操作。有些情况下,分配不起作用,但tf.identity会这样做,因为它会创建一个新的操作,例如在控制流程中。请参阅此问题:How to add control dependency to Tensorflow op

答案 1 :(得分:1)

被接受的答案似乎不再是正确的,至少在急切执行的情况下。 tf.identity将返回具有相同值的不同张量,因此等效于<variable>.read_value()。这是文档中的示例,显示了当前行为:

a = tf.Variable(5)
a_identity = tf.identity(a)
a.assign_add(1)

a.numpy() # 6 

a_identity.numpy() # 5

因此,我们看到对tf.identity返回的张量执行的操作不会影响调用它的张量。

相关问题