如何使预先存在的tensorflow variable_scope适用于ops?

时间:2016-12-07 18:08:26

标签: machine-learning tensorflow deep-learning

以下按预期方式工作:

import tensorflow as tf
with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))
    w = v * 2

print(v.name)    # Prints layer123/v:0
print(w.name)    # Prints layer123/mul:0

然而,当我尝试以下方式时:

with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))

# There might be some code here (perhaps even a different function), but not necessarily

with tf.variable_scope('layer123'):
    w = v * 2

print(v.name)    # Prints layer123/v:0
print(w.name)    # Prints layer123_1/mul:0

此处,变量w位于新的variable_scope自动命名的layer123_1中。我该如何防止这种行为?正如预期的那样,在第二个reuse=True语句中设置with并没有帮助。

我想拥有w.name == 'layer123/mul:0',特别是当未定义乘法运算后(即不退出范围)时,定义了变量v

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以通过重用范围对象来完成此操作。例如,

with tf.variable_scope('layer123') as scope:
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))
with tf.variable_scope(scope):
    w = v * 2

有关详细信息,请参阅documentation on sharing variables