【问题标题】:How to get or create variable in root scope in tensorflow?如何在张量流的根范围内获取或创建变量?
【发布时间】:2017-11-18 19:22:23
【问题描述】:

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

开始
with tf.variable_scope(name):

因此它创建了所有具有某个命名范围的节点。

但有时我需要根范围内的变量,例如is_training 变量,以便不时在不同的块中使用它。

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

【问题讨论】:

  • 我不明白问题出在哪里。难道你不能简单地在根范围内声明is_training 变量,然后在需要的地方使用它吗?
  • 假设我做到了。现在如何从任意位置访问它?张量流中的变量是否有一些相对或绝对的“路径”?
  • 我猜像 `tf.get_default_graph().get_tensor_by_name("path_of_your_node")` 可以工作

标签: python-3.x tensorflow neural-network


【解决方案1】:

我面临同样的问题,目前使用一种“肮脏”的解决方案。

with tf.variable_scope(name_or_scope) 函数不仅接受类型为strname,还接受类型为scopescope

下面的代码展示了诀窍:

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,并在程序入口附近对其进行初始化,我们可以轻松地在任何地方访问它。

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

【讨论】:

    【解决方案2】:

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

    根据 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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2016-06-25
      相关资源
      最近更新 更多