来自here
与tf.Variable不同,tf.ResourceVariable具有定义明确的语义。 TensorFlow图中ResourceVariable的每次使用都会向该图添加read_value操作。保证read_value操作返回的Tensor可以看到对变量值的所有修改,这些修改发生在read_value所依赖的任何操作中(直接,间接或通过控件依赖项),并且保证看不到对该变量的任何修改。 read_value操作不依赖的变量的值。例如,如果在单个session.run调用中有一个以上的ResourceVariable赋值,则每个赋值都有一个明确定义的值,如果赋值和读取通过图形中的边连接,则使用变量的值。 / p>
所以我尝试测试该行为。我的代码:
tf.reset_default_graph()
a = tf.placeholder(dtype=tf.float32,shape=(), name='a')
d = tf.placeholder(dtype=tf.float32,shape=(), name='d')
b = tf.get_variable(name='b', initializer=tf.zeros_like(d), use_resource=True)
c=a+b
b_init = tf.assign(b, d)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run([c,b_init,b], feed_dict={a:5.,d:10.}))
这将打印[15.,10.,10。]。根据我对张量流变量c
中的资源变量的理解,不应访问在b
中为其分配的b_init
的值,这意味着输出应为[5 。,10.,0。]。请帮我了解我要去哪里错了
答案 0 :(得分:1)
两句话:
在sess.run
的第一个参数中写入变量/操作的顺序并不意味着这就是执行的顺序。
如果某个步骤可以成功完成,这并不意味着您可以添加并行负载。
问题的答案:
定义中的键为depends on
:a read_value operation are guaranteed to see all modifications on which the read_value depends on
。如果您看下面的图,添加操作实际上包含ReadVariableOp
的{{1}}操作,然后b
也取决于ReadVariableOp
。因此,AssignVariableOp
应该考虑对c
的所有修改。
如果要查看[10.0,5.0,0.0],则必须添加b
,如下所示
tf.control_dependency