控制依赖关系和评估顺序

时间:2017-05-11 12:52:41

标签: tensorflow

请考虑以下代码:

.text(localStorage.length)

输出结果为:

import tensorflow as tf
import numpy as np

with tf.device("gpu:0"):
    sess = tf.InteractiveSession()
    idx = tf.constant(0)
    # 10 iterations
    while_condition = lambda i: tf.less(i, tf.constant(10))        
    acc = tf.Variable(0, dtype=tf.float64)
    # the body of the while adds 1 to acc in each iteration
    def body_accumulator(i):
        mainOp = tf.assign_add(acc, 1.0)
        return tf.tuple([tf.add(i, 1)], control_inputs=[mainOp])
    whileOp = tf.while_loop(while_condition, body_accumulator, [idx])

    # My idea: return acc after evaluating whileOp, whose code modifies acc
    def f(dummy):
        with tf.control_dependencies([whileOp]):
            # with return tf.identity(acc) it works
            return acc
    def g():
        return acc

    sess.run(tf.global_variables_initializer())
    print('"g: return acc .eval()" - this is the only time where I would expect 0')
    print(g().eval())
    print('f(dummy)')
    print(f(1).eval())
    print('whileOp.eval()')
    print(whileOp.eval())
    print('acc value:')
    print(acc.eval())
    print('"g: return acc .eval()"')
    print(g().eval())

我的问题是:

为什么"g: return acc .eval()" - this is the only time where I would expect 0 0.0 f(dummy) 0.0 whileOp.eval() 10 acc value: 10.0 "g: return acc .eval()" 10.0 返回0,即使f(1).eval()存在对修改返回变量whileOp的控件依赖项?

阅读文档后,我希望在返回acc之前评估acc。我应该如何编写函数whileOp以强制评估f(.)

whileOp中,如果我返回f(.)而不是tf.identity(acc),则可以正常工作。

1 个答案:

答案 0 :(得分:1)

由于张量流变量的奇怪混叠模型,您会看到问题。这就是为什么事情与tf.identiy合作但不是没有。

如果启用资源变量(使用tf.get_variable(...,use_resource = True)来创建变量),您将获得所需的行为。