7

TensorFlow 2.0中tensor.numpy()的 inside有什么替代方法吗?tf.function问题是,当我尝试在装饰函数中使用它时,我收到错误消息'Tensor' object has no attribute 'numpy',而它在外部运行时没有任何问题。

通常,我会选择类似的东西,tensor.eval()但它只能在 TF 会话中使用,并且 TF 2.0 中不再有会话。

4

1 回答 1

6

如果您有一个未修饰的函数,您可以正确地使用它numpy()来提取 a 的值tf.Tensor

def f():
    a = tf.constant(10)
    tf.print("a:", a.numpy())

当你装饰函数时,tf.Tensor对象改变语义,成为计算图的张量(普通的旧tf.Graph对象),因此.numpy()方法消失了,如果你想获得张量的值,你只需要使用它:

@tf.function
def f():
    a = tf.constant(10)
    tf.print("a:", a)

因此,您不能简单地装饰一个 Eager 函数,而是必须像在 Tensorflow 1.x 中那样重新编写它。

我建议您阅读这篇文章(和第 1 部分),以更好地了解其tf.function工作原理:https ://pgaleone.eu/tensorflow/tf.function/2019/04/03/dissecting-tf-function-part-2/

于 2019-04-09T16:29:57.767 回答