Tensorflow:tf.identity和'='运算符有什么区别 [英] Tensorflow: what is the difference between tf.identity and '=' operator

查看:185
本文介绍了Tensorflow:tf.identity和'='运算符有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对'='运算符和 tf.identity()感到困惑,我认为'='只是为了张量的参考,并且身份是要复制的内容,例如使用

I'm confused about '=' operator, and tf.identity(), I thought '=' is to just make a reference of the tensor, and identity is to make a copy, e.g., with

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

我将把 x 都设置为0个元素,并且使用

I will get x all been set to 0 element-wise, and with

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

x 不会更改,因为身份会复制而不是引用,但通过实验,'='也会复制并生成 x 未设置为0,有什么区别?

x would not be changed, since identity make copy, not a reference, but with experiment, '=' also make a copy and x is not set to 0, so what's the difference?

推荐答案

不同之处仅在于张量图布局. tf.identity 创建一个新op 在模拟其参数的图形中,而纯赋值会添加一个新的python变量,该变量指向相同的op.

The difference is only in tensorlfow graph layout. tf.identity creates a new op in the graph that mimics its argument, while pure assignment adds a new python variable that points to the same op.

在两种情况下( ref x 对或 copy x 对),两个操作都总是求出相同的值.但是在第二种情况下, tf.get_default_graph().get_operations()将在列表中显示一个名为 Identity 的新操作.

In both cases (the pair ref and x or the pair copy and x), both ops always evaluate to the same value. But in the second case, tf.get_default_graph().get_operations() will reveal a new operation in the list called 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 起作用,正是因为它创建了一个新的操作,例如在控制流中.看到以下问题:如何将控件依赖项添加到Tensorflow op .

You may wonder, why would anyone want to introduce a new op when she can simply make an assignment. There cases when assignment doesn't work, but tf.identity does, exactly because it creates a new op, e.g. in control flow. See this question: How to add control dependency to Tensorflow op.

这篇关于Tensorflow:tf.identity和'='运算符有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆