【问题标题】:How to create variable outside of current scope in Tensorflow?如何在 Tensorflow 中创建超出当前范围的变量?
【发布时间】:2018-07-16 23:32:22
【问题描述】:

例如我有这样的代码:

def test():
    v = tf.get_variable('test')  # => foo/test

with tf.variable_scope('foo'):
    test()

现在我想在 'foo' 范围之外创建一个变量:

def test():
    with tf.variable_scope('bar'):
        v = tf.get_variable('test')  # foo/bar/test

但它被放置为“foo/bar/test”。我应该在 test() 正文中做什么以将其放置为没有“foo”根的“bar/test”?

【问题讨论】:

    标签: python variables tensorflow scope


    【解决方案1】:

    您可以通过提供现有范围的实例来清除当前变量范围。因此,为了实现这一目标,只需引用顶级变量范围并使用它:

    top_scope = tf.get_variable_scope()   # top-level scope
    
    def test():
      v = tf.get_variable('test', [1], dtype=tf.float32)
      print(v.name)
    
      with tf.variable_scope(top_scope):  # resets the current scope!
        # Can nest the scopes further, if needed
        w = tf.get_variable('test', [1], dtype=tf.float32)
        print(w.name)
    
    with tf.variable_scope('foo'):
      test()
    

    输出:

    foo/test:0
    test:0
    

    【讨论】:

      【解决方案2】:

      tf.get_variable() 忽略 name_scope 但不忽略 variable_scope。如果你想获取'bar/test',你可以尝试以下方法:

      def test():
          with tf.variable_scope('bar'):
              v = tf.get_variable('test', [1], dtype=tf.float32)
              print(v.name)
      
      with tf.name_scope('foo'):
          test()
      

      完整的解释请参考这个答案:https://stackoverflow.com/a/37534656/8107620

      一种解决方法是直接设置范围名称:

      def test():
          tf.get_variable_scope()._name = ''
          with tf.variable_scope('bar'):
              v = tf.get_variable('test', [1])
      

      【讨论】:

      • 不幸的是,我只能更改 test() 正文。
      猜你喜欢
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2021-10-04
      • 2018-08-23
      • 2019-07-14
      相关资源
      最近更新 更多