Python 3.x 如何在tensorflow的根作用域中获取或创建变量?
我在写函数,它创建了一些神经网络块。每个函数都从Python 3.x 如何在tensorflow的根作用域中获取或创建变量?,python-3.x,tensorflow,neural-network,Python 3.x,Tensorflow,Neural Network,我在写函数,它创建了一些神经网络块。每个函数都从 with tf.variable_scope(name): 因此,它使用一些命名范围创建所有节点 但有时我需要根范围中的变量,比如is\u trainingvariable,以便在不同的块中不时使用它 那么,如何在某些嵌套范围内访问/创建此变量呢?这里有一种方法来处理此问题。您可以在一个地方初始化所有要在其他作用域中使用的变量,如变量字典 根据Tensorflow网站 共享变量的一种常见方法是在单独的代码段中创建它们,并将它们传递给使用它们的函
with tf.variable_scope(name):
因此,它使用一些命名范围创建所有节点
但有时我需要根范围中的变量,比如is\u training
variable,以便在不同的块中不时使用它
那么,如何在某些嵌套范围内访问/创建此变量呢?这里有一种方法来处理此问题。您可以在一个地方初始化所有要在其他作用域中使用的变量,如变量字典 根据Tensorflow网站 共享变量的一种常见方法是在单独的代码段中创建它们,并将它们传递给使用它们的函数。例如,使用字典: 。。。。
可能还有其他方法(如创建类等),但这应该可以解决您的基本问题 我面临着同样的问题,目前正在使用一种“肮脏”的解决方案 带有tf.variable\u scope(name\u或\u scope)函数的
不仅接受类型为str
的name
,还接受类型为VariableScope
的scope
下面的代码显示了技巧:
root_scope = tf.get_variable_scope()
with tf.variable_scope(root_scope):
x0 = tf.get_variable('x', [])
with tf.variable_scope(root_scope, reuse=True):
x1 = tf.get_variable('x', [])
with tf.variable_scope('scope_1'):
x2 = tf.get_variable('x', [])
with tf.variable_scope(root_scope):
y = tf.get_variable('y', [])
print('x0:', x0)
print('x1:', x1)
print('x2:', x2)
print('y:', y)
产出是:
x0: <tf.Variable 'x:0' shape=() dtype=float32_ref>
x1: <tf.Variable 'x:0' shape=() dtype=float32_ref>
x2: <tf.Variable 'scope_1/x:0' shape=() dtype=float32_ref>
y: <tf.Variable 'y:0' shape=() dtype=float32_ref>
x0:
x1:
x2:
y:
通过这种方式,您可以共享根范围的变量(x0
和x1
),并在其他嵌套范围内创建根范围的变量(如y
)
如果我们使用一个模块级全局变量来存储root\u scope
,并在程序入口附近初始化它,我们可以方便地随时随地访问它
然而,这种方法需要使用全局变量,这可能不是一个好的选择。我还在想是否有更好的解决办法。我不明白问题出在哪里。你不能简单地在根范围中声明is\u training
变量,然后在需要的地方使用它吗?假设我这样做了。现在我如何从任意位置访问它?tensorflow中的变量有一些相对或绝对的“路径”吗?我想类似于'tf.get\u default\u graph().get\u tensor\u by\u name(“您节点的路径”)之类的东西可能会起作用
root_scope = tf.get_variable_scope()
with tf.variable_scope(root_scope):
x0 = tf.get_variable('x', [])
with tf.variable_scope(root_scope, reuse=True):
x1 = tf.get_variable('x', [])
with tf.variable_scope('scope_1'):
x2 = tf.get_variable('x', [])
with tf.variable_scope(root_scope):
y = tf.get_variable('y', [])
print('x0:', x0)
print('x1:', x1)
print('x2:', x2)
print('y:', y)
x0: <tf.Variable 'x:0' shape=() dtype=float32_ref>
x1: <tf.Variable 'x:0' shape=() dtype=float32_ref>
x2: <tf.Variable 'scope_1/x:0' shape=() dtype=float32_ref>
y: <tf.Variable 'y:0' shape=() dtype=float32_ref>