我该如何禁用TensorFlow的即时执行?

81

我正在学习TensorFlow。目前,我正在使用占位符。当我尝试创建占位符时,出现了错误:RuntimeError: tf.placeholder()与急切执行不兼容,这是有道理的,因为占位符不能立即执行。

那么,我该如何关闭急切执行?

我一开始从未开启过急切执行,所以我不确定它是如何发生的。是否有tf.disable_eager_execution()的相反操作呢?


这似乎不对,急切执行不应该默认启用(尽管在 TensorFlow 2.x 中似乎会改变)。我认为没有什么可以禁用急切执行,因为它应该在程序开始时启用或根本不使用。你的程序中一定有某个东西启用了它,可能是一些导入的模块。你可以使用 tf.executing_eagerly()(例如在每个导入之后)来尝试找到它何时被启用的点。 - jdehesa
4个回答

109

假设您正在使用默认启用急切执行的Tensorflow 2.0预览版。 在v1 API中有一个 disable_eager_execution(),您可以将其放在代码前面,例如:

import tensorflow as tf
    
tf.compat.v1.disable_eager_execution()

另一方面,如果您没有使用2.0预览版,请检查是否意外启用了急切执行。


29

我假设你正在使用TensorFlow 2.0。在TF2中,急切模式默认开启。然而,在TensorFlow 2.0.0-alpha0中有一个disable_eager_execution()函数,但它被深深地隐藏起来,无法直接从顶级模块命名空间(即tf命名空间)访问。

您可以这样调用该函数:

import tensorflow as tf
from tensorflow.python.framework.ops import disable_eager_execution

disable_eager_execution()

a = tf.constant(1)
b = tf.constant(2)
c = a + b
print(c)

>>>张量("add:0",形状=(),数据类型=int32)

print(disable_eager_execution.__doc__) 

>>>禁用急切执行。 该函数只能在创建任何图形、操作或张量之前调用。它可以在程序开头用于从TensorFlow 1.x迁移到2.x的复杂迁移项目。


framework.ops is framework_ops in tensorflow==2.0.0rc0 - bers

21
在TensorFlow 2.3+中,您可以使用以下方法随时禁用急切执行模式:
import tensorflow as tf

tf.config.run_functions_eagerly(False)

3
不,这完全没有影响! - Thư Sinh
7
在2.6.0版本中似乎没有任何影响。 - hyperspasm
1
在Tensorflow 2.9.2中无法工作。 - richar8086

11

您可以通过以下方式禁用TensorFlow v2行为:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接