在 tensorflow 中调用 get_variable() 函数时,“reuse”标志的行为在tensorflow api doc 中定义为 AUTO_REUSE:
重用:True、None 或 tf.AUTO_REUSE;...当启用急切执行时,此参数始终强制为 tf.AUTO_REUSE。
但是,当我真正按照网页中的建议运行演示代码时:
tf.enable_eager_execution()
def foo():
with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
v = tf.get_variable("v", [1])
return v
v1 = foo() # Creates v.
v2 = foo() # Gets the same, existing v.
assert v1 == v2
Run Code Online (Sandbox Code Playgroud)
它失败。(如果第一行被删除,它就会通过,正如预期的那样。)
那么如何在 Eager 模式下重用变量呢?这是一个错误还是我遗漏了什么?
In eager mode, things are simpler... except for people that have been brain damaged (like me) by using graphs models for too long.
Eager works in a standard fashion, where variables last only while they are referenced. If you stop referencing them, they are gone.
要进行变量共享,您会做与使用 numpy(或其他任何东西)进行计算时自然会做的相同的事情:将变量存储在一个对象中,然后重用该对象。
这就是为什么eager 与keras API 如此相似的原因,因为keras 主要处理对象。
因此,例如根据 numpy 再次查看您的函数(对于像我这样从图形中恢复的人很有用)。您是否希望两次调用foo
返回相同的数组对象?当然不是。