python - 如何在急切执行模式下重用 tensorflow 变量?

标签 python tensorflow

在 tensorflow 中调用 get_variable() 函数时,“重用”标志的行为定义在 tensorflow api doc 中成为 AUTO_REUSE:

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模式下重用一个变量呢?这是错误还是我遗漏了什么?

最佳答案

在 eager 模式下,事情变得更简单......除了那些因使用图形模型时间过长而脑部受损的人(比如我)。

Eager 以标准方式工作,变量仅在被引用时存在。如果您停止引用它们,它们就会消失。

要进行变量共享,您要做的事情与您使用 numpy(或其他任何东西)进行计算时自然会做的事情相同:将变量存储在一个对象中,然后重用该对象。

这就是为什么 eager 与 keras API 有如此密切关系的原因,因为 keras 主要处理对象。

因此,再看看您的函数,例如 numpy(对于像我这样从图形中恢复的人很有用)。您是否期望对 foo 的两次调用返回相同的数组对象?当然不是。

关于python - 如何在急切执行模式下重用 tensorflow 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50853010/

相关文章:

python - Keras - 如何为每个输入神经元构建一个共享的 Embedding() 层

python - 我想使用用户在一个屏幕上在其他屏幕上输入的文本作为标题(按钮或标签)

python - 从 python 运行 nohup 和 eval

python - UserDict 类的优点?

python - 凯拉斯/ tensorflow : Combined Loss function for single output

python - 在 tf.Estimator 设置中使用 tf.metrics.precision/recall 计算 F1 分数

python - 如何在自定义包中运行Python代码?

python - 使用 numpy 和 matplotlib 在 3 维中可视化多元正态分布

python - 适用于 Windows 上的 Python 的 TensorRT

tensorflow - 在 keras 的 CPU 上并行训练多个神经网络