8

Is there any alternative to tensor.numpy() inside of a tf.function in TensorFlow 2.0? The problem is that when I try to use it in the decorated function, I get the error message 'Tensor' object has no attribute 'numpy' while outside it runs without any problem.

Normally, I would go for something like tensor.eval() but it can be used only in a TF session and there are no sessions anymore in TF 2.0.

1 Answer 1

6

If you have a non decorated function, you correctly can use numpy() to extract the value of a tf.Tensor

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

When you decorate the function, the tf.Tensor object changes semantic, becoming a Tensor of a computational Graph (the plain old tf.Graph object), therefore the .numpy() method disappear and if you want to get the value of the tensor, you just have to use it:

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

Hence, you can't simply decorate an eager function but you have to rewrite it thinking as in Tensorflow 1.x.

I suggest you to read this article (and part 1) for a better understanding of how tf.function works: https://pgaleone.eu/tensorflow/tf.function/2019/04/03/dissecting-tf-function-part-2/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. For sure it is explaining, but the problem is that tf.print doesn't really extract the value, which is what I need. I need to extract the value in order to insert it to a numpy.array which I would like to assign to the original tensor later, because tf.assign doesn't work for items of a tensor.
If you post the code I can give you more help. I just given a generic answer because of a generic question :) If you want you can open a new question showing the code after marking this question as solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.