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.
The easiest[A] way to evaluate the actual value of a Tensor object is to pass it to the Session. run() method, or call Tensor. eval() when you have a default session (i.e. in a with tf. Session(): block, or see below).
Create a tensor of n-dimensionYou begin with the creation of a tensor with one dimension, namely a scalar. Each tensor is displayed by the tensor name. Each tensor object is defined with tensor attributes like a unique label (name), a dimension (shape) and TensorFlow data types (dtype).
A Keras tensor is a symbolic tensor-like object, which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model. For instance, if a , b and c are Keras tensors, it becomes possible to do: model = Model(input=[a, b], output=c) Arguments.
Eager execution is a powerful execution environment that evaluates operations immediately. It does not build graphs, and the operations return actual values instead of computational graphs to run later. With Eager execution, TensorFlow calculates the values of tensors as they occur in your code.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With