如何在 Tensorflow 中创建当前范围之外的变量? [英] How to create variable outside of current scope in Tensorflow?
本文介绍了如何在 Tensorflow 中创建当前范围之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我有这样的代码:
def test():
v = tf.get_variable('test') # => foo/test
with tf.variable_scope('foo'):
test()
现在我想创建一个超出范围 'foo' 的变量:
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
但它被放置为'foo/bar/test'.我应该在 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?
推荐答案
您可以通过提供现有范围的实例来清除当前变量范围.因此,为了实现这一点,只需引用顶级变量范围并使用它:
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()
输出:
foo/test:0
test:0
这篇关于如何在 Tensorflow 中创建当前范围之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文