如何创建Tensorflow当前范围内的变量之外?(How to create variable o

2019-09-26 19:41发布

例如,我有这样的代码:

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

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

现在,我要让范围“富”的变量外:

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

但它被放置为“富/酒吧/测试”。 我应该做的测试()身体把它作为不“富”根“酒吧/测试”?

Answer 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


Answer 2:

tf.get_variable()忽略name_scope但不variable_scope 。 如果你想获得“酒吧/测试”,你可以尝试以下方法:

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


文章来源: How to create variable outside of current scope in Tensorflow?