为了优化计算,在会话中执行图的运算时,并不一定把整个图计算一遍,TensorFlow会自动根据当前要执行的操作,只计算这个操作所依赖的操作,其他不依赖的操作不会执行。
import tensorflow as tf
x = tf.Variable(0.0, name='x')
x_plus_1 = tf.assign_add(x, 1, name='x_plus')
#tf.control_dependencies()的作用是在其作用域之内的操作依赖于参数中指定的操作,
#在这里就是里面的y依赖于x_plus_1操作,通俗而讲,即在运行y=x时,需要先执行x_plus_1
with tf.control_dependencies([x_plus_1]):
y = x
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
print(y.eval())
summary_writer = tf.summary.FileWriter('./calc_graph')
graph = tf.get_default_graph()
summary_writer.add_graph(graph)
summary_writer.flush()
以上代码执行结果为0.0,0.0,0.0,0.0,0.0
其中y=x并不是一次操作,只是一个内存拷贝,并不是一个op
,而control_dependencies
只有当里面是一个Op
的时候才能起作用。
故x_plus_1不会执行,因此修改代码
import tensorflow as tf
x = tf.Variable(0.0, name='x')
x_plus_1 = tf.assign_add(x, 1, name='x_plus')
with tf.control_dependencies([x_plus_1]):
y = tf.identity(x, name='y')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
print(y.eval())
summary_writer = tf.summary.FileWriter('./calc_graph')
graph = tf.get_default_graph()
summary_writer.add_graph(graph)
summary_writer.flush()
y=x修改为y = tf.identity(x, name='y') ,tf.identity()的作用是返回一个和x相同的值,即将本次作为一次操作,故在执行本次操作之前,需要执行x_plus_1操作,本次代码执行结果为1.0,2.0,3.0,4.0,5.0