【问题标题】:Understanding ResourceVariables in tensorflow理解 tensorflow 中的 ResourceVariables
【发布时间】:2019-08-06 12:24:30
【问题描述】:

来自here

与 tf.Variable 不同,tf.ResourceVariable 具有明确定义的语义。在 TensorFlow 图中每次使用 ResourceVariable 都会向图中添加一个 read_value 操作。 read_value 操作返回的张量保证可以看到对变量值的所有修改,这些修改发生在 read_value 依赖的任何操作中(直接、间接或通过控制依赖),并保证看不到对变量的任何修改read_value 操作不依赖的变量的值。例如,如果在单个 session.run 调用中对 ResourceVariable 有多个赋值,则每个操作都有一个明确定义的值,如果赋值和读取通过图中的边连接,则使用变量的值。

所以我尝试测试行为。我的代码:

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.]。根据我对 tensorflow 变量 c 中资源变量的理解,不应访问在 b_init 中分配给它的 b 的值,这意味着输出应该是 [5.,10.,0 .]。请帮助我了解我哪里出错了

【问题讨论】:

    标签: python tensorflow deep-learning


    【解决方案1】:

    两个备注:

    1. sess.run 的第一个参数中写入变量/操作的顺序并不意味着执行顺序。

    2. 如果某件事在一个步骤中起作用,并不意味着如果您添加大量并行性它就会起作用。

    问题的答案:

    定义中的键是depends on : a read_value operation are guaranteed to see all modifications on which the read_value depends on。如果你看下图,添加操作实际上包含了bReadVariableOp 操作,然后ReadVariableOp 也依赖于AssignVariableOp。因此,c 应考虑对b 的所有修改。

    除非我在混合一些东西,但我听起来对自己很有说服力。 :)

    如果您想查看 [10.0, 5.0, 0.0],您必须添加 tf.control_dependency,如下所示

    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
    with tf.control_dependencies([c]):
      b_init = tf.assign(b, d)
    
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())   
        print(sess.run([b_init,c,b], feed_dict={a:5.,d:10.})) 
    

    然后图形会发生一点变化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多