This name was deprecated and removed in TF2, but tf.numpy_function is a
near-exact replacement, just drop the stateful argument (all
tf.numpy_function calls are considered stateful). It is compatible with
eager execution and tf.function.
tf.py_function is a close but not an exact replacement, passing TensorFlow
tensors to the wrapped function instead of NumPy arrays, which provides
gradients and can take advantage of accelerators.
Given a python function func, which takes numpy arrays as its
arguments and returns numpy arrays as its outputs, wrap this function as an
operation in a TensorFlow graph. The following snippet constructs a simple
TensorFlow graph that invokes the np.sinh() NumPy function as a operation
in the graph:
defmy_func(x):# x will be a numpy array with the contents of the placeholder belowreturnnp.sinh(x)input=tf.compat.v1.placeholder(tf.float32)y=tf.compat.v1.py_func(my_func,[input],tf.float32)
The body of the function (i.e. func) will not be serialized in a
GraphDef. 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.compat.v1.py_func(). If you are using distributed
TensorFlow, you
must run a tf.distribute.Server in the same process as the program that
calls
tf.compat.v1.py_func() and you must pin the created operation to a device
in that
server (e.g. using with tf.device():).
A Python function, which accepts ndarray objects as arguments and
returns a list of ndarray objects (or a single ndarray). This function
must accept as many arguments as there are tensors in inp, and these
argument types will match the corresponding tf.Tensor objects in inp.
The returns ndarrays must match the number and types defined Tout.
Important Note: Input and output numpy ndarrays of func are not
guaranteed to be copies. In some cases their underlying memory will be
shared with the corresponding TensorFlow tensors. In-place modification or
storing func input or return values in python datastructures without
explicit (np.)copy can have non-deterministic consequences.
inp
A list of Tensor objects.
Tout
A list or tuple of tensorflow data types or a single tensorflow data
type if there is only one, indicating what func returns.
stateful
(Boolean.) If True, the function should be considered stateful. If
a function is stateless, when given the same input it will return the same
output and have no observable side effects. Optimizations such as common
sub-expression elimination are only performed on stateless operations.
name
A name for the operation (optional).
Returns
A list of Tensor or a single Tensor which func computes.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-04-26 UTC."],[],[],null,["# tf.compat.v1.py_func\n\n\u003cbr /\u003e\n\n|------------------------------------------------------------------------------------------------------------------------------|\n| [View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/ops/script_ops.py#L781-L797) |\n\nWraps a python function and uses it as a TensorFlow op. \n\n tf.compat.v1.py_func(\n func, inp, Tout, stateful=True, name=None\n )\n\n\u003cbr /\u003e\n\nMigrate to TF2\n--------------\n\n\u003cbr /\u003e\n\n| **Caution:** This API was designed for TensorFlow v1. Continue reading for details on how to migrate from this API to a native TensorFlow v2 equivalent. See the [TensorFlow v1 to TensorFlow v2 migration guide](https://www.tensorflow.org/guide/migrate) for instructions on how to migrate the rest of your code.\n\nThis name was deprecated and removed in TF2, but [`tf.numpy_function`](../../../tf/numpy_function) is a\nnear-exact replacement, just drop the `stateful` argument (all\n[`tf.numpy_function`](../../../tf/numpy_function) calls are considered stateful). It is compatible with\neager execution and [`tf.function`](../../../tf/function).\n\n[`tf.py_function`](../../../tf/py_function) is a close but not an exact replacement, passing TensorFlow\ntensors to the wrapped function instead of NumPy arrays, which provides\ngradients and can take advantage of accelerators.\n\nBefore: \n\n def fn_using_numpy(x):\n x[0] = 0.\n return x\n tf.compat.v1.py_func(fn_using_numpy, inp=[tf.constant([1., 2.])],\n Tout=tf.float32, stateful=False)\n \u003ctf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)\u003e\n\nAfter: \n\n tf.numpy_function(fn_using_numpy, inp=[tf.constant([1., 2.])],\n Tout=tf.float32)\n \u003ctf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nDescription\n-----------\n\n### Used in the notebooks\n\n| Used in the tutorials |\n|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| - [TensorFlow Probability Case Study: Covariance Estimation](https://www.tensorflow.org/probability/examples/TensorFlow_Probability_Case_Study_Covariance_Estimation) |\n\nGiven a python function `func`, which takes numpy arrays as its\narguments and returns numpy arrays as its outputs, wrap this function as an\noperation in a TensorFlow graph. The following snippet constructs a simple\nTensorFlow graph that invokes the `np.sinh()` NumPy function as a operation\nin the graph: \n\n def my_func(x):\n # x will be a numpy array with the contents of the placeholder below\n return np.sinh(x)\n input = tf.compat.v1.placeholder(tf.float32)\n y = tf.compat.v1.py_func(my_func, [input], tf.float32)\n\n| **Note:** The [`tf.compat.v1.py_func()`](../../../tf/compat/v1/py_func) operation has the following known limitations:\n\n- The body of the function (i.e. `func`) will not be serialized in a\n `GraphDef`. Therefore, you should not use this function if you need to\n serialize your model and restore it in a different environment.\n\n- The operation must run in the same address space as the Python program\n that calls [`tf.compat.v1.py_func()`](../../../tf/compat/v1/py_func). If you are using distributed\n TensorFlow, you\n must run a [`tf.distribute.Server`](../../../tf/distribute/Server) in the same process as the program that\n calls\n [`tf.compat.v1.py_func()`](../../../tf/compat/v1/py_func) and you must pin the created operation to a device\n in that\n server (e.g. using `with tf.device():`).\n\n| **Note:** It produces tensors of unknown shape and rank as shape inference does not work on arbitrary Python code. If you need the shape, you need to set it based on statically available information.\n\nE.g. \n\n import tensorflow as tf\n import numpy as np\n\n def make_synthetic_data(i):\n return np.cast[np.uint8](i) * np.ones([20,256,256,3],\n dtype=np.float32) / 10.\n\n def preprocess_fn(i):\n ones = tf.py_function(make_synthetic_data,[i],tf.float32)\n ones.set_shape(tf.TensorShape([None, None, None, None]))\n ones = tf.image.resize(ones, [224,224])\n return ones\n\n ds = tf.data.Dataset.range(10)\n ds = ds.map(preprocess_fn)\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `func` | A Python function, which accepts `ndarray` objects as arguments and returns a list of `ndarray` objects (or a single `ndarray`). This function must accept as many arguments as there are tensors in `inp`, and these argument types will match the corresponding [`tf.Tensor`](../../../tf/Tensor) objects in `inp`. The returns `ndarray`s must match the number and types defined `Tout`. Important Note: Input and output numpy `ndarray`s of `func` are not guaranteed to be copies. In some cases their underlying memory will be shared with the corresponding TensorFlow tensors. In-place modification or storing `func` input or return values in python datastructures without explicit (np.)copy can have non-deterministic consequences. |\n| `inp` | A list of `Tensor` objects. |\n| `Tout` | A list or tuple of tensorflow data types or a single tensorflow data type if there is only one, indicating what `func` returns. |\n| `stateful` | (Boolean.) If True, the function should be considered stateful. If a function is stateless, when given the same input it will return the same output and have no observable side effects. Optimizations such as common sub-expression elimination are only performed on stateless operations. |\n| `name` | A name for the operation (optional). |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ------- ||\n|---|---|\n| A list of `Tensor` or a single `Tensor` which `func` computes. ||\n\n\u003cbr /\u003e"]]