Tensorflow中variable_scope中的变量初始化

Variable initialization in the variable_scope in the Tensorflow

我一直在尝试了解变量在 Tensorflow 中是如何初始化的。下面,我创建了一个简单的示例,它在一些 variable_scope 中定义了一个变量,并且该过程包含在子函数中。

根据我的理解,此代码在 tf.initialize_all_variables() 阶段在 'test_scope' 中创建了一个变量 'x',之后始终可以使用 tf.get_variable() 访问它。但是此代码在 print(x.eval()) 行以 Attempting to use uninitialized value 错误结束。

我不知道Tensorflow是如何初始化变量的。我能得到什么帮助吗?谢谢。

import tensorflow as tf

def create_var_and_prod_with(y):
    with tf.variable_scope('test_scope'):
        x = tf.Variable(0.0, name='x', trainable=False)
    return x * y

s = tf.InteractiveSession()
y = tf.Variable(1.0, name='x', trainable=False)
create_var_and_prod_with(y)

s.run(tf.initialize_all_variables())

with tf.variable_scope('test_scope'):
    x = tf.get_variable('x', [1], initializer=tf.constant_initializer(0.0), trainable=False)
    print(x.eval())
    print(y.eval())

如果你想重用一个变量,你必须使用 get_variables 声明它,而不是明确要求范围使变量可重用。

如果换行

 x = tf.Variable(0.0, name='x', trainable=False)

与:

x = tf.get_variable('x', [1], trainable=False)

并且您要求作用域使已定义的变量可用:

with tf.variable_scope('test_scope') as scope:
     scope.reuse_variables()
      x = tf.get_variable('x', [1], initializer=tf.constant_initializer(0.0), trainable=False)

那么你可以 运行 print(x.eval(), y.eval()) 没有问题。

如果你想用 tf.get_variable('x') 重用一个变量,必须首先用 tf.get_variable('x').<br> 此外,当您想要检索创建的变量时,您需要在 reuse=True` 的范围内。


您的代码应如下所示:

import tensorflow as tf

def create_var_and_prod_with(y):
    with tf.variable_scope('test_scope'):
        x = tf.get_variable('x', [1], initializer=tf.constant_initializer(0.0), trainable=False)
    return x * y

y = tf.Variable(1.0, name='x', trainable=False)
create_var_and_prod_with(y)

with tf.variable_scope('test_scope', reuse=True):
    x = tf.get_variable('x')  # you only need the name to retrieve x

# Try to put the session only at the end when it is needed
with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    print(x.eval())
    print(y.eval())

您可以在 this tutorial 中阅读更多相关信息。