How to convert “tensor” to “numpy” array in tensorflow?

后端 未结 1 1183
有刺的猬
有刺的猬 2021-01-12 10:34

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 runt

相关标签:
1条回答
  • 2021-01-12 10:34

    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:

    def get_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 1 part 2 part 3

    0 讨论(0)
提交回复
热议问题