TensorFlow学习笔记之control_dependencies(control_inputs)函数理解

参数:操作或者张量(tensor)的列表
返回:返回一个上下文管理器,控制上下文中所有操作的控制依赖
函数的功能:上下文中的所有操作(注意:必须是操作operation)会在参数list中所有操作完成以后才开始执行
 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 import tensorflow as tf
 4 
 5 """
 6 control_dependencies(control_inputs)
 7 Args:
 8     control_inputs: A list of `Operation` or `Tensor` objects which
 9       must be executed or computed before running the operations
10       defined in the context.  
11 Returns:
12     A context manager that specifies control dependencies for all
13     operations constructed within the context.
14 
15 参数:操作或者张量(tensor)的列表
16 返回:返回一个上下文管理器,控制上下文中所有操作的控制依赖
17 函数的功能:上下文中的所有操作(注意:必须是操作operation)会在参数list中所有操作完成以后才开始执行
18 """
19 
20 # 本例中,with结构(上下文)内的变量y不是operation,所有它不会在参数中的操作执行之前进行,相反,z是一个操作
21 
22 x = tf.Variable(1.0)
23 y = tf.Variable(0.0)
24 #返回一个op,表示给变量x加1的操作
25 x_plus_1 = tf.assign_add(x, 1)
26 
27 #control_dependencies的意义是,在执行with包含的内容(在这里就是 y = x)前,
28 #先执行control_dependencies参数中的内容(在这里就是 x_plus_1)
29 with tf.control_dependencies([x_plus_1]):
30     # y = x
31     z = tf.identity(x)  # tf.identity()就是返回参数本身,这里相当于z=x
32 
33 init = tf.initialize_all_variables()
34 
35 with tf.Session() as session:
36     init.run()
37     for i in range(5):
38         # 相当于sess.run(y),按照我们的预期,由于control_dependencies的作用,
39         # 所以应该执行print前都会先执行x_plus_1,但是这种情况会出问题
40         # print(y.eval())
41         print(z.eval())

运行结果:执行print(y.eval()),输出的全是1;执行print(z.eval()),输出的是2,3,4,5,6

这是因为y=x只是赋值语句,算不上是一个operation,而z = tf.identity(x)是一个operation,TensorFlow会在计算图中为z添加一个节点(对应操作z),在执行上下文中的操作之前会先执行control_dependencies(control_inputs)的参数control_inputs中的操作,再执行上下文中z的操作。所以会先计算x_plus_1,再计算z;反之,y不是一个操作,TensorFlow不会为它创建节点,因此,y也就不需要在x_plus_1计算完成后在计算。

猜你喜欢

转载自www.cnblogs.com/huwj/p/10753048.html