'Tensor' 对象在 TF 2.0 的 tf.function 中没有属性 'numpy'

pes*_*on2 7 python tensorflow2.0

TensorFlow 2.0 中tensor.numpy()的 a 内部是否有其他选择tf.function?问题是,当我尝试在装饰函数中使用它时,我收到错误消息,'Tensor' object has no attribute 'numpy'而在外部运行时却没有任何问题。

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

nes*_*uno 6

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

def f():
    a = tf.constant(10)
    tf.print("a:", a.numpy())
Run Code Online (Sandbox Code Playgroud)

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

@tf.function
def f():
    a = tf.constant(10)
    tf.print("a:", a)
Run Code Online (Sandbox Code Playgroud)

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

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

  • 谢谢。它肯定是在解释,但问题是 `tf.print` 并没有真正提取值,这正是我需要的。我需要提取该值以便将其插入到我想稍后分配给原始张量的 `numpy.array` 中,因为 `tf.assign` 不适用于张量的项目。 (2认同)