Home > Article > Backend Development > How to Convert TensorFlow Tensors to NumPy Arrays?
How to Convert Tensors to NumPy Arrays in TensorFlow
In Python bindings for TensorFlow, converting tensors into NumPy arrays is a necessary step for further data manipulation or integration with third-party libraries.
In TensorFlow 2.x:
TensorFlow 2.x enables eager execution by default, allowing you to simply call .numpy() on the Tensor object. This method returns a NumPy array:
<code class="python">import tensorflow as tf a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) a.numpy() # [array([[1, 2], [3, 4]], dtype=int32)] b.numpy() # [array([[2, 3], [4, 5]], dtype=int32)]</code>
In TensorFlow 1.x:
Eager execution is not enabled by default. To convert a tensor to a NumPy array in TensorFlow 1.x:
<code class="python">a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) with tf.Session() as sess: out = sess.run([a, b]) # out[0] contains the NumPy array representation of a # out[1] contains the NumPy array representation of b</code>
<code class="python">a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) out = tf.compat.v1.numpy_function(lambda x: x.numpy(), [a, b]) # out[0] contains the NumPy array representation of a # out[1] contains the NumPy array representation of b</code>
Note: The NumPy array may share memory with the Tensor object. Any changes to one may be reflected in the other.
The above is the detailed content of How to Convert TensorFlow Tensors to NumPy Arrays?. For more information, please follow other related articles on the PHP Chinese website!