tf.control_dependencies与tf.identity组合详解

来源:互联网 发布:免费网络加速器 编辑:程序博客网 时间:2024/05/01 15:10

参考链接:

http://blog.csdn.net/m0_37041325/article/details/76943364

https://stackoverflow.com/questions/34877523/in-tensorflow-what-is-tf-identity-used-for


tf.control_dependencies(self, control_inputs)

arguments:control_inputs: A list of `Operation` or `Tensor` objects which must be executed or computed before running the operations defined in the context. (注意这里control_inputs是list)
return:  A context manager that specifies control dependencies for all operations constructed within the context.(返回所有在环境中的控制依赖的上下文管理器)

该方法可以控制操作(op)执行的顺序,不能为tensor

tf.identity(input, name=None) 

Args:
input: A Tensor.
name: A name for the operation (optional).

Returns:A tensor with the same shape and contents as the input tensor or value.


源于StackOverFlow有个关于两者使用的例子:

x = tf.Variable(0.0)x_plus_1 = tf.assign_add(x, 1)with tf.control_dependencies([x_plus_1]):    y = xinit = tf.global_variables_initializer()with tf.Session() as session:    init.run()    for i in range(5):        print(y.eval())


针对此程序,输出结果为:0.0 0.0 0.0 0.0 0.0

输出变量x,结果也为0.0

说明x_plus_1操作并没有被执行,我认为虽然tf.control_dependencies参数中的op列表会在with包含的操作op执行之前先执行,但是y=x这个语句并不是一个op,而是一个tensor,所以执行y=x时,并不会执行tf.control_dependencies参数中的操作op。

所以可以将  y=x 修改为 y=tf.identity(x),此时这个语句就是一个操作op,要先执行tf.control_dependencies参数中的op列表,再执行y=tf.identity(x)操作,最终输出结果为1.0 2.0 3.0 4.0 5.0,最终变量x的结果也为5.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.global_variables_initializer()with tf.Session() as session:    init.run()    for i in range(5):        print(y.eval())    print(x.eval())





原创粉丝点击