非常奇怪的张量流动行为

时间:2018-03-23 08:15:48

标签: python tensorflow machine-learning dependencies control-flow

我有非常简单的线条,会产生非常奇怪的意外行为:

import tensorflow as tf

y = tf.Variable(2, dtype=tf.int32)

a1 = tf.assign(y, y + 1)
a2 = tf.assign(y, y * 2)

with tf.control_dependencies([a1, a2]):
    t = y+0

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(4):
        print('t=%d' % sess.run(t))
        print('y=%d' % sess.run(y))

预期是什么

t=6
y=6
t=14
y=14
t=30
y=30
t=62
y=62

但是第一次跑,我得到了:

t=6
y=6
t=13
y=13
t=26
y=26
t=27
y=27

第二轮,我得到了:

t=3
y=3
t=6
y=6
t=14
y=14
t=15
y=15
第三轮,我得到了:

t=6
y=6
t=14
y=14
t=28
y=28
t=56
y=56

非常荒谬,多次运行产生多个不同的输出序列,很奇怪,有人可以帮忙吗?

编辑:改为

import tensorflow as tf
import os
y = tf.Variable(2, dtype=tf.int32)

a1 = tf.assign(y, y + 1)
a2 = tf.assign(y, y * 2)
a3 = tf.group(a1, a2)
with tf.control_dependencies([a3]):
    t = tf.identity(y+0)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(4):

        print('t=%d' % sess.run(t))
        print('y=%d' % sess.run(y))

......仍然无法正常工作。

这段代码仍然很奇怪:

a1 = tf.assign(y, y + 1)
with tf.control_dependencies([a1]):
  a2 = tf.assign(y, y * 2)
  with tf.control_dependencies([a2]):
    t = tf.identity(y)

...正常工作,但只需将a2移至之前

a1 = tf.assign(y, y + 1)
a2 = tf.assign(y, y * 2)
with tf.control_dependencies([a1]):
  with tf.control_dependencies([a2]):
    t = tf.identity(y)

......它没有。

1 个答案:

答案 0 :(得分:1)

您的方法存在的问题是,a1a2的顺序也很重要:您希望在a1之前评估a2tf.control_dependencies([a1, a2])保证在ta1之后执行a2,但它们本身可以按任何顺序进行评估。

我明确依赖于:

y = tf.Variable(2, dtype=tf.int32)
a1 = tf.assign(y, y + 1)
with tf.control_dependencies([a1]):
  a2 = tf.assign(y, y * 2)
  with tf.control_dependencies([a2]):
    t = tf.identity(y)

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  for i in range(4):
    print('t=%d' % sess.run(t))
    print('y=%d' % sess.run(y))

输出:

t=6
y=6
t=14
y=14
t=30
y=30
t=62
y=62