概述:
在tensorflow学习中,经常会用到identity这个操作,一直不知道原因,这里留下一点学习记录。直接上代码。
代码功能:我们想完成tensorflow下的自增计算操作,也就是x += 1,这要在计算图上完成并没有想象的简单。
import tensorflow as tf
x = tf.Variable(0.0)
#tensor加操作,自身x也增1
x_plus_1 = tf.assign_add(x, 1)
#control_dependencies 在调用ops时控制依赖关系
with tf.control_dependencies([x_plus_1]):
y = x
init = tf.global_variables_initializer()
with tf.Session() as session:
#参数初始化
init.run()
for i in xrange(5):
print(session.run(y))#相当于sess.run(y),由于control_dependencies的所以执行print前都会先执行x_plus_one
output:
0.0
0.0
0.0
0.0
0.0
上述Bug:以上代码是自增+1操作,但是结果确都是0。
分析原因: y=x为一个非tf的op操作,该操作不受限于control_dependencies,所以每次y的执行不会调用x_plus_one。
import tensorflow as tf
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.global_variables_initializer()
with tf.Session() as session:
#参数初始化
init.run()
for i in xrange(5):
print(session.run(y))
train_writer.close()
output:
1.0
2.0
3.0
4.0
5.0
分析:上述y=identity(x)为一个tf的op操作,类似于C语言的指针,但是它受限于control_dependencies,调用x_plus_one,所以能正常完成+1操作。
额外一个小例子:
import tensorflow as tf
x = tf.Variable(0.0)
x_plus_1 = tf.assign_add(x, 1)
with tf.control_dependencies([x_plus_1]):
y = x
sum_y = tf.summary.scalar('y', y)
init = tf.global_variables_initializer()
with tf.Session() as session:
#参数初始化
init.run()
train_writer = tf.summary.FileWriter('Summaries/zfy_test', session.graph)
for i in xrange(5):
print(session.run(y))
summary = session.run(sum_y)
train_writer.add_summary(summary, i)
train_writer.close()
output:
0.0
1.0
2.0
3.0
4.0
分析:这里是比较能体会计算图的一个例子,summary这里是引入的可视化的操作(假设大家知道了),该操作也受限于control_dependencies。分析可以看出结果存在一个单位的延迟。