【问题标题】:Tensorflow: what is the difference between tf.identity and '=' operatorTensorflow:tf.identity和'='运算符有什么区别
【发布时间】:2018-08-16 20:24:23
【问题描述】:

我对@9​​87654321@ 运算符和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,那么有什么区别?

【问题讨论】:

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


    【解决方案1】:

    区别仅在于 tensorlfow 图形布局。 tf.identity 在图中创建一个 new op 来模仿其参数,而纯赋值添加一个 new python 变量 指向同一个 op。

    在这两种情况下(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

    【讨论】:

      【解决方案2】:

      接受的答案似乎不再正确,至少在急切的执行中是这样。 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 返回的张量上执行的操作不会影响调用它的张量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-10
        • 2012-10-10
        • 1970-01-01
        • 2010-11-15
        • 2011-02-12
        • 2021-04-19
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多