我有以下代码,定义了一个嵌套的 tf.variable_scope()
。
def function(inputs):
with tf.variable_scope("1st") as scope:
# 在这里使用 tf.get_variable() 定义一些变量
with tf.variable_scope("2nd") as scope:
# 在这里使用 tf.get_variable() 定义一些变量
my_wanted_variable = tf.get_variable('my_wanted_variable', [dim0, dim1], tf.float32, tf.constant_initializer(0.0))
在另一个类中,我想获取 my_wanted_variable
,我使用
with tf.variable_scope("function/2nd", reuse=True):
got_my_wanted_variable = tf.get_variable("my_wanted_variable")
我被告知
ValueError: 变量 function/2nd/my_wanted_variable 不存在,或者不是用 tf.get_variable() 创建的。你是否打算在 VarScope 中设置 reuse=None?
如果我在获取 my_wanted_variable
时设置 reuse=None
,那么
ValueError: 新变量 (function/2nd/my_wanted_variable) 的形状必须完全定义,但实际上是未定义的。
那么,如何在嵌套作用域中按名称获取变量(或张量)呢?
添加调试信息:我使用 print(xxx.name)
来查看它们的名称和作用域,确实发现虽然它们的作用域是正确的,例如 xxx/function/2nd
。但是在作用域 1st
和 2nd
中定义的所有变量都没有使用指定的名称,例如,my_wanted_variable
的名称是 xxx/function/2nd/sub:0
。
回答:
:0
对于每个变量来说是正常的(它象征着端点)。名称 sub
并不奇怪,它只是表明你没有明确命名变量,所以它给张量赋予了你所使用的操作的名称(可能是 tf.sub()
)。
明确使用参数 name="my_wanted_variable"
。先尝试不使用作用域以确保它被正确命名。然后使用 print(nn.name)
或检查 graph_def
对象的节点来验证。