我有一些非常简单的线条,可以产生非常奇怪的意外行为:
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
至之前as
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)
。。。事实并非如此。