|TensorFlow 1 version||View source on GitHub|
Wraps a python function and uses it as a TensorFlow op.
Compat aliases for migration
See Migration guide for more details.
tf.numpy_function( func, inp, Tout, name=None )
Used in the notebooks
|Used in the tutorials|
Given a python function
func wrap this function as an operation in a
func must take numpy arrays as its arguments and
return numpy arrays as its outputs.
The following example creates a TensorFlow graph with
np.sinh() as an
operation in the graph:
# x will be a numpy array with the contents of the input to the
y = tf.numpy_function(my_numpy_func, [input], tf.float32)
return y * y
<tf.Tensor: shape=(), dtype=float32, numpy=1.3810978>
tf.numpy_function are very similar, except that
tf.numpy_function takes numpy arrays, and not
tf.Tensors. If you want the
function to contain
tf.Tensors, and have any TensorFlow operations executed
in the function be differentiable, please use
The body of the function (i.e.
func) will not be serialized in a
tf.SavedModel. Therefore, you should not use this function if you need to serialize your model and restore it in a different environment.
The operation must run in the same address space as the Python program that calls
tf.numpy_function(). If you are using distributed TensorFlow, you must run a
tf.distribute.Serverin the same process as the program that calls
tf.numpy_functionyou must pin the created operation to a device in that server (e.g. using
Since the function takes numpy arrays, you cannot take gradients through a numpy_function. If you require something that is differentiable, please consider using tf.py_function.
The resulting function is assumed stateful and will never be optimized.
func: A Python function, which accepts
numpy.ndarrayobjects as arguments and returns a list of
numpy.ndarrayobjects (or a single
numpy.ndarray). This function must accept as many arguments as there are tensors in
inp, and these argument types will match the corresponding
inp. The returns
numpy.ndarrays must match the number and types defined
Tout. Important Note: Input and output
funcare not guaranteed to be copies. In some cases their underlying memory will be shared with the corresponding TensorFlow tensors. In-place modification or storing
funcinput or return values in python datastructures without explicit (np.)copy can have non-deterministic consequences.
inp: A list of
Tout: A list or tuple of tensorflow data types or a single tensorflow data type if there is only one, indicating what
name: (Optional) A name for the operation.
Single or list of