在tensorflow中调用get_variable()函数时,“重用”标志的行为在要自动重用的tensorflow api doc中定义:
reuse: True, None, or tf.AUTO_REUSE; ... When eager execution is enabled, this argument is always forced to be 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
它失败了。(如果第一行如预期的那样被删除,则通过。)
那么如何在急切模式下重用变量呢?这是虫子还是我遗漏了什么?在
在渴望模式下,事情更简单。。。除了那些因为长时间使用图形模型而大脑受损的人(比如我)。在
Eager以一种标准的方式工作,变量只有在被引用时才持续。如果你停止引用它们,它们就会消失。在
为了实现变量共享,您可以做同样的事情,如果您要使用numpy(或者其他任何东西)来进行计算,您将变量存储在一个对象中,然后重用这个对象。在
这就是为什么eager与kerasapi有如此密切的关系,因为keras主要处理对象。在
所以再看看你的函数,比如numpy(对于像我这样从图中恢复的人来说很有用)。您希望对
foo
进行两次调用以返回相同的数组对象吗?当然不是。在我发现在急切执行中重用变量最简单的方法是简单地传递对同一变量的引用:
输出为:
因此,我们有一个维度3的共享权重参数},总共有5个可训练参数。代码是独立运行的,所以可以随意使用它。在
my_model/A
,以及维度1的两个偏差参数my_model/my_layer/B
和{tensorflow/python/ops/variable_scope.py中的文档似乎已更新。在
从line 310:
从line 2107:
相关问题 更多 >
编程相关推荐