Home  >  Article  >  Backend Development  >  How to Convert TensorFlow Tensors to NumPy Arrays?

How to Convert TensorFlow Tensors to NumPy Arrays?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 17:54:30634browse

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:

  • Use .eval() method within a session:
<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>
  • Use tf.compat.v1.numpy_function:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn