如何在Tensorflow中创建当前范围之外的变量?

时间:2018-02-06 19:53:37

标签: python variables tensorflow scope

例如我有这样的代码:

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()体中做什么来将它作为'bar / test'而没有'foo'根?

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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