Home > Backend Development > Python Tutorial > How do I Convert TensorFlow Tensors to NumPy Arrays?

How do I Convert TensorFlow Tensors to NumPy Arrays?

Linda Hamilton
Release: 2024-11-03 19:49:03
Original
754 people have browsed it

How do I Convert TensorFlow Tensors to NumPy Arrays?

Converting Tensor to NumPy Array in TensorFlow

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>
Copy after login

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>
Copy after login

Notes:

  • .numpy() may share memory with the original tensor, so changes to one may affect the other.
  • If you encounter the error "AttributeError: 'Tensor' object has no attribute 'numpy'," ensure TF 2.0 is properly installed, or enable eager execution.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template