TensorFlow provides a convenient method, .numpy(), to convert tensors into NumPy arrays.
TensorFlow 2.x
Enabling eager execution makes TensorFlow operations immediately executable, allowing you to call .numpy() directly on tensors:
<code class="python">import tensorflow as tf a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) print(a.numpy()) # array([[1, 2], # [3, 4]], dtype=int32) print(b.numpy()) # array([[2, 3], # [4, 5]], dtype=int32)</code>
TensorFlow 1.x
If eager execution is disabled in TensorFlow 1.x, you can create a graph and execute it to obtain the NumPy array:
<code class="python">a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) out = tf.multiply(a, b) with tf.compat.v1.Session() as sess: print(sess.run(out)) # array([[ 2, 6], # [12, 20]], dtype=int32)</code>
Notes:
The above is the detailed content of How do I Convert TensorFlow Tensors to NumPy Arrays?. For more information, please follow other related articles on the PHP Chinese website!