QBoard » Artificial Intelligence & ML » AI and ML - Tensorflow » How can I convert a tensor into a numpy array in TensorFlow?

How can I convert a tensor into a numpy array in TensorFlow?

  • How to convert a tensor into a numpy array when using Tensorflow with Python bindings?
      June 11, 2019 4:19 PM IST
    0
  • Any tensor returned by Session.run or eval is a NumPy array.


    >>>print(type(tf.Session().run(tf.constant([1,2,3]))))
    This post was edited by Raji Reddy A at June 11, 2019 4:30 PM IST
      June 11, 2019 4:29 PM IST
    0
  • To convert back from tensor to numpy array you can simply run .eval() on the transformed tensor.
      June 14, 2019 1:03 PM IST
    0
  • You need to:

    encode the image tensor in some format (jpeg, png) to binary tensor
    evaluate (run) the binary tensor in a session
    turn the binary to stream
    feed to PIL image
    (optional) displaythe image with matplotlib
    Code:

    import tensorflow as tf
    import matplotlib.pyplot as plt
    import PIL

    ...

    image_tensor =
    jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)

    with tf.Session() as sess:
    # display encoded back to image data
    jpeg_bin = sess.run(jpeg_bin_tensor)
    jpeg_str = StringIO.StringIO(jpeg_bin)
    jpeg_image = PIL.Image.open(jpeg_str)
    plt.imshow(jpeg_image)
    This worked for me. You can try it in a ipython notebook. Just don't forget to add the following line:

    %matplotlib inline
      June 14, 2019 1:25 PM IST
    0
  • The Eager Execution of the TensorFlow library can be used to convert a tensor to a NumPy array in Python. With Eager Execution, the behavior of the operations of TensorFlow library changes, and the operations execute immediately. We can also perform NumPy operations on Tensor objects with Eager Execution. The Tensor.numpy() function converts the Tensor to a NumPy array in Python. In TensorFlow 2.0, the Eager Execution is enabled by default. So, this approach works best for the TensorFlow version 2.0. See the following code example.

    import tensorflow as tf
    tensor = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
    print("Tensor = ",tensor)
    array = tensor.numpy()
    print("Array = ",array)​
      November 17, 2021 1:08 PM IST
    0
  • I was searching for days for this command.
    This worked for me outside any session or somthing like this.
    # you get an array = your tensor.eval(session=tf.compat.v1.Session()) an_array = a_tensor.eval(session=tf.compat.v1.Session())
      November 22, 2021 6:20 PM IST
    0
  • I was searching for days for this command.
    This worked for me outside any session or somthing like this.
    # you get an array = your tensor.eval(session=tf.compat.v1.Session()) an_array = a_tensor.eval(session=tf.compat.v1.Session())
      November 22, 2021 6:21 PM IST
    0