Call .numpy() directly on the tf.Tensor (or np.asarray(tensor)) when running in TensorFlow 2.x’s default eager execution mode—which copies GPU tensors back to host RAM automatically and shares zero-copy memory with CPU tensors whenever possible—and if the tensor carries gradient tape history or resides inside a @tf.function / tf.keras.layers.Layer graph where .numpy() raises AttributeError, use tf.make_ndarray(tf.make_tensor_proto(tensor)) for static constant tensors or wrap NumPy logic inside tf.py_function / tf.numpy_function during graph execution.

Basic Example

import numpy as np
import tensorflow as tf

# 1. Recommended in eager execution (TF 2.x default): Call `.numpy()`
tensor = tf.constant([[1.5, 2.5], [3.5, 4.5]], dtype=tf.float32)
arr = tensor.numpy()

print(type(arr), arr.dtype, arr.shape)
# Output: <class 'numpy.ndarray'> float32 (2, 2)

# 2. Works identically on GPU tensors (automatically copies device -> host):
with tf.device("/CPU:0"):
    t_cpu = tf.ones((2, 3))
arr_cpu = np.asarray(t_cpu)  # `np.asarray(tensor)` also works seamlessly in eager mode

# 3. Converting a `tf.Variable` or `tf.RaggedTensor` / `tf.SparseTensor`:
var = tf.Variable([10, 20, 30])
print(var.numpy())                        # array([10, 20, 30], dtype=int32)

sparse = tf.sparse.SparseTensor(indices=[[0, 1], [1, 0]], values=[7, 9], dense_shape=[2, 2])
print(tf.sparse.to_dense(sparse).numpy()) # array([[0, 7], [9, 0]], dtype=int32)

Key Details & Edge Cases

  • Fix AttributeError: 'SymbolicTensor' object has no attribute 'numpy' (inside @tf.function or Keras Functional models):
    • Inside a @tf.function-decorated function or while building a Keras Functional graph (inputs = tf.keras.Input(...)), tensors are symbolic placeholders without concrete values yet, so .numpy() does not exist.
    • Fix A: Move .numpy() outside the @tf.function (call it on the returned eager tf.Tensor).
    • Fix B: If you must run NumPy code mid-graph, wrap the Python function in tf.numpy_function(func, inp=[tensor], Tout=tf.float32) (note: this breaks automatic gradient backpropagation through that step).
    • Fix C: For static constant TensorProto nodes during graph inspection, extract the constant value via tf.make_ndarray(tf.make_tensor_proto(tensor)).
  • Zero-copy shared memory on CPU (tensor.numpy() can share the underlying buffer):
    • When a tf.Tensor lives on CPU and has standard alignment, tensor.numpy() may point directly to TensorFlow’s underlying C++ buffer without copying. Modifying the resulting NumPy array in place (arr[0] = 99) can mutate the tensor’s backing buffer or fail if the buffer is read-only—call tensor.numpy().copy() if you intend to mutate the NumPy array safely.
  • String tensors (tf.string) decode as dtype=object bytes arrays:
    • Calling tf.constant(["hello", "world"]).numpy() returns array([b'hello', b'world'], dtype=object) containing Python bytes, not str. Decode them to Unicode strings via [b.decode("utf-8") for b in t.numpy()] (or t.numpy().astype(str) for ASCII).
  • tf.data.Dataset iteration (dataset.as_numpy_iterator()):
    • Instead of calling .numpy() manually on every batch inside a training/evaluation loop, iterate directly with for batch in dataset.as_numpy_iterator(): to yield pure NumPy arrays cleanly.
  • tf.RaggedTensor conversion (ragged.to_list() vs. .numpy()):
    • Calling .numpy() on a tf.RaggedTensor returns an object array of 1D NumPy arrays (dtype=object) when row lengths differ; use ragged.to_list() for nested Python lists or ragged.to_tensor(default_value=0).numpy() for a padded dense NumPy array.

Comparison of TensorFlow-to-NumPy Conversion Methods

Method Works in Eager Mode? Works Inside @tf.function Graph? Handles GPU Tensors Automatically? Best Used When
tensor.numpy() (Recommended) Yes No (raises AttributeError on SymbolicTensor) Yes (copies GPU $\rightarrow$ CPU automatically) Standard TensorFlow 2.x code, model predictions (model(x).numpy()), and debugging.
np.asarray(tensor) Yes No (NotImplementedError on SymbolicTensor) Yes Writing library-agnostic functions that accept either NumPy arrays or TensorFlow tensors.
dataset.as_numpy_iterator() Yes N/A Yes Iterating over a tf.data.Dataset pipeline directly as NumPy arrays.
tf.numpy_function(fn, [t], Tout) Yes Yes (runs eager Python callback mid-graph) Yes (copies tensors to CPU for callback) Calling external NumPy/SciPy functions inside a @tf.function or tf.data map pipeline.
tf.make_ndarray(tf.make_tensor_proto(t)) Yes Only for constant tensors Yes Extracting constant tensor values when inspecting static graphs or legacy TF 1.x sessions.