【发布时间】:2020-08-04 21:42:05
【问题描述】:
让我解释一下我的设置。我正在使用 TensorFlow 2.1、TF 附带的 Keras 版本和 TensorFlow Probability 0.9。
我有一个函数get_model,它使用 Keras 和自定义层创建(使用函数式 API)并返回一个模型。在这些自定义层A的__init__方法中,我调用了一个方法A.m,它执行了语句print(tf.executing_eagerly()),但是它返回了False。为什么?
更准确地说,这是我的大致设置
def get_model():
inp = Input(...)
x = A(...)(inp)
x = A(...)(x)
...
model = Model(inp, out)
model.compile(...)
return model
class A(tfp.layers.DenseFlipout): # TensorFlow Probability
def __init__(...):
self.m()
def m(self):
print(tf.executing_eagerly()) # Prints False
tf.executing_eagerly 的文档说
默认情况下启用急切执行,并且此 API 在大多数情况下返回 True。但是,此 API 在以下用例中可能会返回 False。
- 在
tf.function内部执行,除非之前在tf.init_scope或tf.config.experimental_run_functions_eagerly(True)下调用。- 在
tf.dataset的转换函数内部执行。tf.compat.v1.disable_eager_execution()被调用。
但这些情况不是我的情况,所以 tf.executing_eagerly() 在我的情况下应该返回 True,但不是。为什么?
这是一个说明问题的简单完整示例(在 TF 2.1 中)。
import tensorflow as tf
class MyLayer(tf.keras.layers.Layer):
def call(self, inputs):
tf.print("tf.executing_eagerly() =", tf.executing_eagerly())
return inputs
def get_model():
inp = tf.keras.layers.Input(shape=(1,))
out = MyLayer(8)(inp)
model = tf.keras.Model(inputs=inp, outputs=out)
model.summary()
return model
def train():
model = get_model()
model.compile(optimizer="adam", loss="mae")
x_train = [2, 3, 4, 1, 2, 6]
y_train = [1, 0, 1, 0, 1, 1]
model.fit(x_train, y_train)
if __name__ == '__main__':
train()
这个例子打印tf.executing_eagerly() = False。
【问题讨论】:
标签: python tensorflow keras tensorflow2.0 tensorflow-probability