为什么tf.executing_eagerly()在TensorFlow 2中返回False?

问题描述 投票:0回答:1

让我解释一下我的设置。我正在使用TensorFlow 2.1,TF随附的Keras版本和TensorFlow Probability 0.9。

我有一个函数get_model,该函数创建(使用函数API)并使用Keras和自定义层返回模型。在这些自定义层__init__A方法中,我调用方法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.executing_eagerlytf.function下调用,否则在tf.init_scope内部执行。
  • tf.config.experimental_run_functions_eagerly(True)的转换函数内执行。
  • tf.dataset被调用。

但是这些情况不是我的情况,因此,在我的情况下,tf.compat.v1.disable_eager_execution()应该返回tf.executing_eagerly(),但没有。为什么?

这是一个简单的完整示例(在TF 2.1中说明了此问题。

True

此示例打印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
1个回答
0
投票

据我所知,当自定义图层的输入是符号输入时,该图层将以图形(非急切)模式执行。但是,如果您对自定义层的输入是一个急切张量(如下面的示例#1,则自定义层将在急切模式下执行。因此,模型的输出为the related Github issue。)>

示例1

tf.executing_eagerly() = False

这里是Keras功能API的另一个示例,其中使用了自定义层(与您类似)。该模型在图形模式下执行,并根据您的情况打印from tensorflow.keras import layers class Linear(layers.Layer): def __init__(self, units=32, input_dim=32): super(Linear, self).__init__() w_init = tf.random_normal_initializer() self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units), dtype='float32'), trainable=True) b_init = tf.zeros_initializer() self.b = tf.Variable(initial_value=b_init(shape=(units,), dtype='float32'), trainable=True) def call(self, inputs): print("tf.executing_eagerly() =", tf.executing_eagerly()) return tf.matmul(inputs, self.w) + self.b x = tf.ones((1, 2)) # returns tf.executing_eagerly() = True #x = tf.keras.layers.Input(shape=(2,)) #tf.executing_eagerly() = False linear_layer = Linear(4, 2) y = linear_layer(x) print(y) #output in graph mode: Tensor("linear_9/Identity:0", shape=(None, 4), dtype=float32) #output in Eager mode: tf.Tensor([[-0.03011466 0.02563028 0.01234017 0.02272708]], shape=(1, 4), dtype=float32)

tf.executing_eagerly() = False
© www.soinside.com 2019 - 2024. All rights reserved.