tf.assign_add() tf.control_dependencies tf.identify()

先解释tf.identify():

import tensorflow as tf
a = tf.Variable([10, 20])
b = tf.assign_add(a, [1,2])
c = tf.identity(a)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(a))
    print(sess.run(b))
    print(sess.run(a))
    print(sess.run(c))

out:
[10 20]   # 正常输出
[11 22]  # 运行op b的结果 
[11 22]  # tf.assign_add实现a自增
[11 22]  # op tf.identity() 产生一个新的一模一样的tensor

tf.control_dependencies:

下面程序的功能是,做5次循环,每次循环给x加1,赋值给y,然后打印出来,所以我们预期达到的效果是输出2,3,4,5,6。

x = tf.Variable(1.0)
y = tf.Variable(0.0)


x_plus_1 = tf.assign_add(x, 1)


with tf.control_dependencies([x_plus_1]):
    y = x
init = tf.initialize_all_variables()

with tf.Session() as session:
    init.run()
    for i in xrange(5):
        print(y.eval())

这个打印的是1,1,1,1,1 。可以看到,没有达到我们预期的效果,y只被赋值了一次。

如果改成这样:

x = tf.Variable(1.0)
y = 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.initialize_all_variables()

with tf.Session() as session:
    init.run()
    for i in xrange(5):
        print(y.eval())

这时候打印的是2,3,4,5,6

解释:对于control_dependencies这个管理器,只有当里面的操作是一个op(tf.identity())时,才会生效,也就是先执行传入的参数x_plus,再执行里面的op。而y=x仅仅是tensor的一个简单赋值,不是op,所以在图中不会形成一个节点,这样该管理器就失效了,即x_plus op是不执行的。

  op :  tf.identity是返回一个一模一样新的tensor,这会增加一个新节点到gragh中,这时control_dependencies就会生效,所以第二种情况的输出符合预期。

整体展示:

import tensorflow as tf
x = tf.Variable(1.0)
x_plus_1 = tf.assign_add(x, 1)

with tf.control_dependencies([x_plus_1]):
    y = x
    z=tf.identity(x,name='x')
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for i in range(4):
        print(sess.run(x))
        print(sess.run(y))
        print(sess.run(z))

out:

1.0  #由于没有执行z,所以不会触发op x_plus_1执行,所以x是初始值
1.0  #由于y=x不是op,所以不会触发op x_plus_1执行,所以y=x=1
2.0  #由于z是op,所以会触发op x_plus_1的执行,先执行op x_plus_1,在执行op z. 
2.0  
2.0
3.0
3.0
3.0
4.0

猜你喜欢

转载自blog.csdn.net/biubiubiu888/article/details/82055905
tf
今日推荐