How to create variable outside of current scope in Tensorflow?

ε祈祈猫儿з 提交于 2019-12-24 16:04:27

问题


For example I have code like this:

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

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

Now I want to make a variable outside of scope 'foo':

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

But it is placed as 'foo/bar/test'. What should I do in test() body to place it as 'bar/test' without 'foo' root?


回答1:


You can clear the current variable scope by providing an instance of an existing scope. So in order to pull this off, just make a reference to the top-level variable scope and use it:

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()

Output:

foo/test:0
test:0



回答2:


tf.get_variable() ignores the name_scopebut not variable_scope. If you want to obtain 'bar/test', you can try the following:

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()

Refer to this answer for a complete explanation: https://stackoverflow.com/a/37534656/8107620

A workaround would be to set the scope name directly:

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


来源:https://stackoverflow.com/questions/48650889/how-to-create-variable-outside-of-current-scope-in-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!