Python 如何在Tensorflow中创建当前范围之外的变量?
例如,我有如下代码:Python 如何在Tensorflow中创建当前范围之外的变量?,python,variables,tensorflow,scope,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/
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”。我应该在测试体中做些什么来将它放置为没有“foo”根的“bar/test” tf.get\u variable忽略名称\u scope,但不忽略变量\u 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()
有关完整的解释,请参阅此答案:
解决方法是直接设置作用域名称:
def test():
tf.get_variable_scope()._name = ''
with tf.variable_scope('bar'):
v = tf.get_variable('test', [1])
tf.get_variable忽略名称_scope,但不忽略变量_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()
有关完整的解释,请参阅此答案:
解决方法是直接设置作用域名称:
def test():
tf.get_variable_scope()._name = ''
with tf.variable_scope('bar'):
v = tf.get_variable('test', [1])
通过提供现有范围的实例,可以清除当前变量范围。因此,为了实现这一点,只需引用顶级变量范围并使用它: top\u scope=tf.get\u variable\u scope顶级范围 def测试: v=tf.get_变量'test',[1],dtype=tf.float32 printv.name 使用tf.variable_scopetop_scope:重置当前范围! 如果需要,可以进一步嵌套作用域 w=tf.get_变量'test',[1],dtype=tf.float32 printw.name 使用tf.variable_作用域'foo': 测验 输出: foo/test:0 测试:0
通过提供现有范围的实例,可以清除当前变量范围。因此,为了实现这一点,只需引用顶级变量范围并使用它: top\u scope=tf.get\u variable\u scope顶级范围 def测试: v=tf.get_变量'test',[1],dtype=tf.float32 printv.name 使用tf.variable_scopetop_scope:重置当前范围! 如果需要,可以进一步嵌套作用域 w=tf.get_变量'test',[1],dtype=tf.float32 printw.name 使用tf.variable_作用域'foo': 测验 输出: foo/test:0 测试:0
不幸的是,我只能更改测试体。不幸的是,我只能更改测试体。