tf.control_dependencies与tf.identity组合详解

转自:https://blog.csdn.net/winycg/article/details/78820032

参考链接:

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

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

1.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 = x
init = 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())

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值