TensorFlow 2.0中tensor.numpy()
的 inside有什么替代方法吗?tf.function
问题是,当我尝试在装饰函数中使用它时,我收到错误消息'Tensor' object has no attribute 'numpy'
,而它在外部运行时没有任何问题。
通常,我会选择类似的东西,tensor.eval()
但它只能在 TF 会话中使用,并且 TF 2.0 中不再有会话。
TensorFlow 2.0中tensor.numpy()
的 inside有什么替代方法吗?tf.function
问题是,当我尝试在装饰函数中使用它时,我收到错误消息'Tensor' object has no attribute 'numpy'
,而它在外部运行时没有任何问题。
通常,我会选择类似的东西,tensor.eval()
但它只能在 TF 会话中使用,并且 TF 2.0 中不再有会话。
如果您有一个未修饰的函数,您可以正确地使用它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/