Tensorflow2.0 - How to convert Tensor to numpy() array

Written by- Aionlinecourse628 times views

Image
You can use the .numpy() method of a Tensor to convert it to a NumPy array. Here's an example:

import tensorflow as tf

# Create a Tensor
tensor = tf.constant([[1, 2], [3, 4]])

# Convert the Tensor to a NumPy array
array = tensor.numpy()

print(array)  # prints [[1 2] [3 4]]
Keep in mind that this method returns a NumPy array with a copy of the data in the Tensor. If you want to avoid the overhead of copying the data, you can use the tf.Tensor.experimental_memory_efficient_forwarding property, which returns a view of the Tensor as a NumPy array without copying the data. Here's an example:
import tensorflow as tf

# Create a Tensor
tensor = tf.constant([[1, 2], [3, 4]])

# Get a view of the Tensor as a NumPy array without copying the data
array = tensor.experimental_memory_efficient_forwarding

print(array)  # prints [[1 2] [3 4]]
Note that this property is experimental and may not always be available.