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

标签 python tensorflow keras tensorflow2.0 tensorflow-probability

让我解释一下我的设置。我使用的是 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 的文档说

Eager execution is enabled by default and this API returns True in most of cases. However, this API might return False in the following use cases.

  • Executing inside tf.function, unless under tf.init_scope or tf.config.experimental_run_functions_eagerly(True) is previously called.
  • Executing inside a transformation function for tf.dataset.
  • tf.compat.v1.disable_eager_execution() is called.

但这些情况不是我的情况,因此在我的情况下,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

参见the related Github issue .

最佳答案

据我所知,当自定义图层的输入是符号输入时,该图层将以图形(非渴望)模式执行。但是,如果您对自定义层的输入是急切张量(如下面的示例 #1 所示),则自定义层将以急切模式执行。因此您的模型的输出 tf.executing_eagerly() = False 预计。

示例#1

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)

这是 Keras 功能 API 的另一个示例,其中使用了自定义层(与您类似)。该模型以图形模式执行,并按照您的情况打印 tf.executing_eagerly() = False

from tensorflow import keras
from tensorflow.keras import layers
class CustomDense(layers.Layer):
  def __init__(self, units=32):
    super(CustomDense, self).__init__()
    self.units = units

  def build(self, input_shape):
    self.w = self.add_weight(shape=(input_shape[-1], self.units),
                             initializer='random_normal',
                             trainable=True)
    self.b = self.add_weight(shape=(self.units,),
                             initializer='random_normal',
                             trainable=True)

  def call(self, inputs):
    print("tf.executing_eagerly() =", tf.executing_eagerly())
    return tf.matmul(inputs, self.w) + self.b


inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)

model = keras.Model(inputs, outputs) 

关于python - 为什么 tf.executing_eagerly() 在 TensorFlow 2 中返回 False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61355474/

相关文章:

python - 通过opencv Python检测图像中是否存在灰色

python Selenium 元素不可见

python - 使用 1) StandardScaler & Classifier vs 2) Pipeline(Scalar, Classifier) 是否相同?

tensorflow - Tensorboard 解析元数据或获取 Sprite 图像需要永远

android - 没有 OpKernel Tensorflow Mobile Android。如何调试?

python - 我在使用 Tensorflow 2.0 运行 RNN LSTM 模型时遇到错误

python - random.randint 不生成随机值

python - Tensorflow 对象检测中的输入张量与 Python 签名不兼容

r - 试图解决keras中的数据维度不匹配

python - 在 Keras 中制作采样层