以下内容按预期工作:
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
位于自动命名为 layer123_1
的新 variable_scope
中。我该如何防止这种行为?正如预期的那样,在第二个 with
语句中设置 reuse=True
没有帮助。
我想要 w.name == 'layer123/mul:0'
,特别是当乘法运算没有在变量 v 之后立即定义(即不退出作用域)时
已定义。
谢谢!
最佳答案
您可以通过重用作用域对象来做到这一点。例如,
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 .
关于machine-learning - 如何使预先存在的 tensorflow variable_scope应用于操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41024383/