Skip to content Skip to sidebar Skip to footer

How To Convert "tensor" To "numpy" Array In Tensorflow?

I am trying to convert a tensor to numpy in the tesnorflow2.0 version. Since tf2.0 have eager execution enabled then it should work by default and working too in normal runtime. Wh

Solution 1:

You can't use the .numpy method on a tensor, if this tensor is going to be used in a tf.data.Dataset.map call.

The tf.data.Dataset object under the hood works by creating a static graph: this means that you can't use .numpy() because the tf.Tensor object when in a static-graph context do not have this attribute.

Therefore, the line input_image = random_noise(image.numpy()) should be input_image = random_noise(image).

But the code is likely to fail again since random_noise calls get_noise from the model.utils package. If the get_noise function is written using Tensorflow, then everything will work. Otherwise, it won't work.

The solution? Write the code using only the Tensorflow primitives.

For instance, if your function get_noise just creates random noise with the shee of your input image, you can define it like:

defget_noise(image):
    return tf.random.normal(shape=tf.shape(image))

using only the Tensorflow primitives, and it will work.

Hope this overview helps!

P.S: you could be interested in having a look at the articles "Analyzing tf.function to discover AutoGraph strengths and subtleties" - they cover this aspect (perhaps part 3 is the one related to your scenario): part 1part 2part 3

Solution 2:

In TF2.x version, use tf.config.run_functions_eagerly(True).

Post a Comment for "How To Convert "tensor" To "numpy" Array In Tensorflow?"