How to create variable outside of current scope in

2019-07-31 01:59发布

问题:

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