tf.identity的意义以及用例

最近在学习tensorflow,学到ExponentialMovingAverage时,里面有一个tf.identity操作,在Stack Overflow上看到一个很好的解释,记录一下。 
原地址 : https://stackoverflow.com/questions/34877523/in-tensorflow-what-is-tf-identity-used-for

下面程序要做的是,5次循环,每次循环给x加1,赋值给y,然后打印出来

x = tf.Variable(0.0)
#返回一个op,表示给变量x加1的操作
x_plus_1 = tf.assign_add(x, 1)

#control_dependencies的意义是,在执行with包含的内容(在这里就是 y = x)前
#先执行control_dependencies中的内容(在这里就是 x_plus_1)
with tf.control_dependencies([x_plus_1]):
    y = x
init = tf.initialize_all_variables()

with tf.Session() as session:
    init.run()
    for i in xrange(5):
        print(y.eval())#相当于sess.run(y),由于control_dependencies的所以执行print前都会先执行x_plus_1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这个打印的是0,0,0,0,0 。也就是说没有达到我们预期的效果

如果改成这样:

x = tf.Variable(0.0)
x_plus_1 = tf.assign_add(x, 1)

with tf.control_dependencies([x_plus_1]):
    y = tf.identity(x)#修改部分
init = tf.initialize_all_variables()

with tf.Session() as session:
    init.run()
    for i in xrange(5):
        print(y.eval())
This works: it prints 1, 2, 3, 4, 5.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这时候打印的是1,2,3,4,5

解释: 

tf.identity是返回了一个一模一样新的tensor,再control_dependencies的作用块下,需要增加一个新节点到gragh中。有待更新。。。


From: http://blog.csdn.net/u014595019/article/details/52805444

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值