如何在张量流的根范围内获取或创建变量



我正在编写函数,它创建了一些神经网络块。此函数中的每一个都从

with tf.variable_scope(name):

因此,它会在某个命名范围内创建所有节点。

但有时我需要根作用域中的一个变量,比如is_training变量,才能在不同的块中不时使用它。

那么,如何在一些嵌套范围内访问/创建这个变量呢?

我遇到了同样的问题,目前正在使用一种"肮脏"的解决方案。

with tf.variable_scope(name_or_scope)函数不仅接受类型strname,还接受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>

通过这种方式,您可以共享根作用域的变量(x0x1(,并在其他嵌套作用域(如y(中创建根作用域的变量。

如果我们使用模块级全局变量来存储 root_scope ,并在程序入口附近初始化它,我们可以轻松地在任何地方访问它。

但是,此方法需要使用全局变量,这可能不是一个好的选择。我仍然想知道是否有更好的解决方案。

这是处理此问题的一种方法。您可以在一个地方初始化要在其他作用域中使用的所有变量 - 例如变量字典。

根据Tensorflow网站

共享变量的常用方法是在单独的代码段中创建它们,并将它们传递给使用它们的函数。例如,通过使用字典:

variables_dict = {
     "conv1_weights": tf.Variable(tf.random_normal([5, 5, 32, 32]),
      name="conv1_weights")
     "conv1_biases": tf.Variable(tf.zeros([32]), name="conv1_biases")
     ... etc. ...
}

........

result1 = my_image_filter(image1, variables_dict)
result2 = my_image_filter(image2, variables_dict)

可能还有其他方法(如创建类等(,但这应该可以解决您的基本问题。

最新更新