如何在 Tensorflow 2.0 中做到这一点?

How to do this in Tensorflow 2.0?

我第一次尝试 Tensorflow 2.0。 这是惯用语吗?

@tf.function
def add(a,b):
    return a+b

if __name__=="__main__":

    result=add(1.0,2.0)
    print(result)
    print(tf.keras.backend.get_value(result))

但是,我收到与添加功能相关的警告:

WARNING:tensorflow:Entity <function add at 0x7ff34781a2f0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: 

这是什么意思? 我该如何纠正?

我在最新的 tf-nightly (2.1.0-dev20200104) 中没有收到警告。但是关于你的代码有两条建议,

  1. 正如@thushv89 所指出的,传递 Tensor 对象通常是个好主意 当调用由 @tf.function 装饰的函数时。在某些情况下,通过 纯 Python 数据类型(如 floats 和 ints)可能会导致函数 成为 "recompiled",大大降低了性能。它不会发生 在这种情况下。不过总的来说还是小心点好。

  2. 在 TF2 的急切执行中,tf.keras.backend.get_value(result) 是一个空操作。 你可以省略那个电话。 result 是 Tensor 值本身,它包含 具体值。