TensortFlow 1.x 会话中的依赖

        为了优化计算,在会话中执行图的运算时,并不一定把整个图计算一遍,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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值