NumPy Interop & tf.experimental.numpy

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

TensorFlow and NumPy are designed to be used together: a tf.Tensor can be passed to NumPy functions, a NumPy array can be passed to almost any TensorFlow operation, and TensorFlow ships a NumPy-compatible API, tf.experimental.numpy, that runs on accelerators and works under tf.function and tf.GradientTape. This page covers the implicit and explicit conversions, the copy rules, the opt-in NumPy behaviour switch, and the limits of the NumPy API. Tensors themselves are on Tensors, mutable state on Variables, gradients on Automatic Differentiation with GradientTape and compilation on Graphs, tf.function, AutoGraph & Retracing.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is labelled "upcoming" and is not covered), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. For the NumPy side see NumPy interoperability, NumPy type promotion, broadcasting and copies and views. The PyTorch equivalent is NumPy and DLPack Interop.

Three ways to cross the boundary

Direction Mechanism Notes

Tensor to NumPy

t.numpy()

eager tensors only; returns an np.ndarray; may share memory on CPU, so treat it as read-only

Tensor to NumPy

np.asarray(t), np.sum(t) and other NumPy functions

works through the __array__ protocol; a copy is made when needed

NumPy to tensor

tf.convert_to_tensor(a)

explicit; the dtype is taken from the array

NumPy to tensor

passing an array to tf.* ops (for example tf.add(t, a))

implicit conversion; Python floats become float32 here

NumPy to tensor

tf.constant(a)

embeds a constant; use tf.Variable(a) for trainable state

import numpy as np
import tensorflow as tf

a = np.ones((2, 3))                      # float64: NumPy's default float
t = tf.convert_to_tensor(a)              # float64 tensor: the dtype is preserved
print(t.dtype)                           # <dtype: 'float64'>

s = tf.multiply(t, 2)                    # a Python int is converted to the tensor dtype
n = s.numpy()                            # back to an np.ndarray
print(type(n), n.dtype)                  # <class 'numpy.ndarray'> float64

print(np.sum(t))                         # NumPy functions accept tensors; result 6.0
print(tf.add(t, a).shape)                # arrays are accepted by TF ops: (2, 3)

# Python floats follow TensorFlow's defaults, not NumPy's
print(tf.constant(1.0).dtype)            # <dtype: 'float32'>
print(np.asarray(1.0).dtype)             # float64

The most common surprise is the default float width. NumPy creates float64 from Python floats and from np.ones, TensorFlow creates float32. Feeding a float64 array to a Keras layer whose weights are float32 either fails with a dtype mismatch in a hand-written op or is cast silently by Keras layers; cast explicitly with a.astype(np.float32) or tf.cast(t, tf.float32) at the data boundary. Mixed-dtype arithmetic between two tensors is an error in plain TensorFlow (there is no automatic promotion), which is the reason the NumPy-behaviour switch below exists.

When does conversion copy?

  • Tensor.numpy() on a CPU tensor can return an array that shares the tensor’s buffer. Do not write into it; copy first with .numpy().copy() if you need to mutate.

  • Tensors on a GPU or TPU always need a device-to-host copy to become NumPy arrays, and the reverse direction needs a host-to-device copy. The NumPy API documentation states that conversions "can copy data", partly because TensorFlow has stricter memory-alignment requirements than NumPy.

  • Moving data between NumPy and tensors inside a hot training loop is a performance problem: it forces a synchronization with the device. Keep data as tensors, or feed it through tf.data, and call .numpy() only for logging or plotting.

  • Symbolic tensors inside a tf.function or a Keras functional model have no value at trace time, so .numpy() raises there. See Graphs, tf.function, AutoGraph & Retracing.

tf.experimental.numpy

tf.experimental.numpy (conventionally imported as tnp) implements a subset of the NumPy API on top of TensorFlow operations. The module is explicitly experimental, so signatures and coverage may change between releases. Its key design decision is that the ND array type is not a new class: tnp.ndarray is an alias of tf.Tensor. Everything below therefore interoperates with tf.* APIs without copies, and with tf.function, tf.GradientTape and tf.vectorized_map.

import tensorflow as tf
import tensorflow.experimental.numpy as tnp

tnp.experimental_enable_numpy_behavior()          # see the next section

x = tnp.ones([2, 3])
y = tnp.arange(6).reshape(2, 3)                   # NumPy-style methods on tensors
print(x.shape, x.ndim, x.dtype, x.T.shape)        # (2, 3) 2 <dtype: 'float64'> (3, 2)

# Broadcasting follows NumPy rules
z = x + tnp.asarray([10.0, 20.0, 30.0])
print(z.shape)                                    # (2, 3)

# NumPy-style indexing, including boolean and advanced indexing
mask = y > 2
print(y[mask])                                    # tf.Tensor([3 4 5], shape=(3,), dtype=int64)
print(y[:, tnp.newaxis, 1].shape)                 # (2, 1)

# Item assignment is NOT supported (tensors are immutable)
try:
    y[0, 0] = -1
except TypeError as e:
    print("immutable:", type(e).__name__)

# Works inside tf.function and with GradientTape
@tf.function
def f(a):
    return tnp.sum(tnp.maximum(a, 0.0) ** 2)

v = tf.Variable(tnp.asarray([-1.0, 2.0, 3.0]))
with tf.GradientTape() as tape:
    loss = f(v)
print(tape.gradient(loss, v))                     # tf.Tensor([0. 4. 6.], shape=(3,), dtype=float64)

Function names mirror NumPy (tnp.matmul, tnp.sum, tnp.copy, tnp.random.randn and so on), but only a subset of NumPy exists. Check that a function is present before relying on it; for anything missing, fall back to the matching tf.math, tf.linalg or tf.raw_ops operation, or call NumPy outside the graph.

Turning on NumPy behaviour

By default TensorFlow keeps its own rules: literals are inferred as int32 and float32, and mixing dtypes raises an error. Calling tnp.experimental_enable_numpy_behavior() once, near the start of the program, changes TensorFlow globally, not only the tnp module.

Aspect Default TensorFlow After experimental_enable_numpy_behavior()

Python int literal

tf.convert_to_tensor(1) gives int32

tnp.asarray(1) gives int64

Python float literal

tf.convert_to_tensor(1.) gives float32

tnp.asarray(1.) gives float64, or float32 with prefer_float32=True

Mixed dtypes in tnp functions

NumPy promotion, for example int32 plus float32 gives float64

same

Mixed dtypes in plain tf.* ops and operators

error (InvalidArgumentError)

tf.add(a, b) still raises, but the tensor operator a + b promotes (int32 plus float32 gives float64); use tnp functions when you rely on promotion

Tensor attributes such as .T, .reshape, .ravel, .ndim

not available on tf.Tensor

available

Tensor slicing and boolean masks

supported

supported, plus advanced indexing

import tensorflow as tf
import tensorflow.experimental.numpy as tnp

# Keep float literals at 32 bits, which is what models and accelerators want
tnp.experimental_enable_numpy_behavior(prefer_float32=True)
print(tnp.asarray(1.0).dtype)                     # <dtype: 'float32'>

# dtype_conversion_mode: "legacy" (the default), "all" or "safe"
# "all" applies JAX-style promotion; "safe" also rejects unsafe implicit promotions.
tnp.experimental_enable_numpy_behavior(
    prefer_float32=True,
    dtype_conversion_mode="safe",
)

a = tf.constant([1, 2, 3], dtype=tf.int32)
b = tf.constant([0.5, 0.5, 0.5], dtype=tf.float32)
print(tnp.add(a, b).dtype)                        # <dtype: 'float64'>: tnp functions promote by NumPy rules
# In "safe" mode a + b and tf.add(a, b) raise TypeError for int32 plus float32

Cautions when enabling the switch:

  • It is process-wide. A library should not call it on behalf of an application, because it changes the semantics of every other piece of TensorFlow code running in the same process, including third-party Keras layers.

  • The dtype_conversion_mode argument appeared after TensorFlow 2.15. TensorFlow 2.21 accepts "legacy" (the default), "all" and "safe" and raises ValueError for any other string. The mode changes results: for an int32 and a float32 tensor, a + b gives float64 under "legacy", float32 under "all" (where tf.add also promotes) and a TypeError under "safe", while tnp.add gives float64 in every mode.

  • The switch does not turn tf.Tensor into a mutable array. Assignment still raises; use a tf.Variable for state (see Variables) or build a new tensor with tf.tensor_scatter_nd_update.

Differences from NumPy

The official guide lists the features that TensorFlow NumPy does not provide:

  • No mutation of arrays through item assignment.

  • No views: slices are new tensors, so the aliasing behaviour described on NumPy copies and views does not apply, and neither do stride_tricks.

  • No Fortran storage order and no NumPy C API or SWIG integration.

  • Some dtypes are unsupported, for example np.recarray style structured data and object arrays.

  • Only a subset of functions exists.

Interop works both ways because tnp.ndarray implements __array__ (so np.sum(tnp.ones([2, 3])) works), and NumPy inputs to tnp functions are converted with asarray. When a NumPy array and a tnp array meet in an operator, the TensorFlow type wins because its __array_priority__ is higher, so np_array + tnp_array yields a tensor.

Devices and performance

tnp code uses ordinary TensorFlow device placement, so use with tf.device("/device:GPU:0"): to pin work, and tnp.copy inside a device scope to move data. See Devices: CPUs, GPUs & TPUs.

TensorFlow has a larger per-operation dispatch overhead than NumPy, which the guide puts at around 10 microseconds: for operations that small NumPy on the CPU can be faster. TensorFlow wins when arrays are large, when the work is fused under tf.function, or when it runs on an accelerator. The guide’s benchmark example shows eager execution at roughly 2.7 ms against 0.7 ms after wrapping the function in tf.function; treat such numbers as illustrative, not as a guarantee.

import numpy as np
import tensorflow as tf
import tensorflow.experimental.numpy as tnp

def pairwise_sq_dist(a, b):
    # (n, d), (m, d) -> (n, m), written once in NumPy style
    return tnp.sum((a[:, None, :] - b[None, :, :]) ** 2, axis=-1)

fast = tf.function(pairwise_sq_dist)               # compile the NumPy-style code

a = tnp.asarray(np.random.rand(512, 16), dtype=tf.float32)
b = tnp.asarray(np.random.rand(256, 16), dtype=tf.float32)
print(fast(a, b).shape)                            # (512, 256)

# Per-example computation without an explicit batch dimension
def per_example(v):
    return tnp.sum(v ** 2)                         # tnp has no linalg submodule

batched = tf.vectorized_map(per_example, a)
print(batched.shape)                               # (512,)

tf.vectorized_map is the TensorFlow analogue of jax.vmap: it vectorizes a per-example function without a Python loop, and the guide reports it as much faster than tf.map_fn in its example. It is also what makes per-example Jacobians cheap; see the Jacobian section.

Practical guidance

  • Convert at the boundary: read files with NumPy or pandas, then call tf.convert_to_tensor or build a tf.data.Dataset, and cast to float32 once.

  • Use tf.* operations in model code and in tf.function bodies; use tnp only when porting existing NumPy code, since a plain tf.math expression is clearer and better documented.

  • Never call .numpy() inside a function that you intend to trace; use tf.py_function only as a last resort (it runs Python on every call, cannot be saved in a SavedModel and scales poorly in distributed setups).

  • For random numbers, prefer tf.random.Generator or the stateless tf.random.stateless_* ops over tnp.random, so that results stay reproducible across devices (see Tensors).

  • Moving to Keras backend-agnostic code is a different problem: keras.ops mirrors the NumPy API across TensorFlow, JAX and PyTorch backends (see Keras Multi-Backend).

References