How do I convert a Tensorflow Tensor to a NumPy Array?

Barbara Streisand
Release: 2024-11-03 21:23:03
Original
778 people have browsed it

How do I convert a Tensorflow Tensor to a NumPy Array?

Convert a Tensor to Numpy Array in Tensorflow

In Tensorflow, converting a tensor into a numpy array is straightforward. Here's how:

<code class="python">import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)

a_numpy = a.numpy()  # Convert tensor 'a' to numpy array
b_numpy = b.numpy()  # Convert tensor 'b' to numpy array

print(a_numpy)
# [[1 2]
#  [3 4]]
print(b_numpy)
# [[2 3]
#  [4 5]]</code>
Copy after login

Notes:

  • In Tensorflow 2.x, Eager Execution is enabled by default. So, you can simply call .numpy() on the tensor object.
  • If you're getting an AttributeError about the .numpy() attribute, make sure that TF 2.0 is installed correctly and Eager Execution is enabled.
  • Numpy arrays share memory with their corresponding tensors. Changes made to one are reflected in the other.
  • If Eager Execution is disabled, you can build a graph and use tf.compat.v1.Session to execute it.

The above is the detailed content of How do I convert a Tensorflow Tensor to a NumPy Array?. 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