tf.control_dependencies的一点理解
程序员文章站
2022-05-25 16:13:16
...
先看一段代码:来源:https://blog.csdn.net/*new/article/details/80611165
import tensorflow as tf
a = tf.Variable(2)
selfAdd = tf.Variable(0)
# selfAddition = tf.assign_add(selfAdd, 3)
selfSub = tf.Variable(0)
# selfSubtraction1 = tf.assign_sub( selfSub , 2 )
# print('op 1:', selfSubtraction1 )
with tf.control_dependencies([tf.assign_add(selfAdd, 3)]):
tf.assign_sub(selfSub, 2)
selfSubtraction = tf.no_op()#tf.assign_sub(selfSub, 2)
print('op:', selfSubtraction)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(20):
sess.run(selfSubtraction)
print("selfAdd:", sess.run(selfAdd))
print('selfSub:', sess.run(selfSub))
ra = sess.run(selfAdd)
print('@end selfAdd:', ra)
rs = sess.run(selfSub)
print('@end selfSub:', rs)
控制依赖关系主要用来解决某些操作在执行(sess.run())的时候无法被执行的情况,比如assign操作,在没有返回值的情况下若有多条控制流则无法被正确执行。
-------------------------------------------------一点点感悟,到时候忘了可以来看看。