Skip to main content
 首页 » 编程设计

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

2025年05月04日25artech

例如我有这样的代码:

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' root 的 'bar/test'?

请您参考如下方法:

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

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