包装一个 python 函数并将其用作 TensorFlow 操作。
用法
tf.numpy_function(
func, inp, Tout, name=None
)参数
-
func一个 Python 函数,它接受numpy.ndarray对象作为参数并返回numpy.ndarray对象列表(或单个numpy.ndarray)。此函数必须接受与inp中的张量一样多的参数,并且这些参数类型将匹配inp中相应的tf.Tensor对象。返回的numpy.ndarray必须与定义的数量和类型相匹配Tout。重要提示:func的输入和输出numpy.ndarray不保证是副本。在某些情况下,它们的底层内存将与相应的 TensorFlow 张量共享。在没有显式 (np.) 复制的情况下,在 python 数据结构中就地修改或存储func输入或返回值可能会产生不确定的后果。 -
inptf.Tensor对象的列表。 -
Touttensorflow 数据类型的列表或元组或单个 tensorflow 数据类型(如果只有一个),指示func返回的内容。 -
name(可选)操作的名称。
返回
-
func计算的tf.Tensor的单个或列表。
给定一个 python 函数 func 将此函数包装为 TensorFlow 函数中的一个操作。 func 必须将 numpy 数组作为其参数并返回 numpy 数组作为其输出。
以下示例使用 np.sinh() 作为图中的操作创建 TensorFlow 图:
def my_numpy_func(x):
# x will be a numpy array with the contents of the input to the
# tf.function
return np.sinh(x)
@tf.function(input_signature=[tf.TensorSpec(None, tf.float32)])
def tf_function(input):
y = tf.numpy_function(my_numpy_func, [input], tf.float32)
return y * y
tf_function(tf.constant(1.))
<tf.Tensor:shape=(), dtype=float32, numpy=1.3810978>
与 tf.py_function 的比较:tf.py_function 和 tf.numpy_function 非常相似,除了 tf.numpy_function 采用 numpy 数组,而不是 tf.Tensor s。如果您希望函数包含 tf.Tensors ,并且在函数中执行的任何 TensorFlow 操作都是可微的,请使用 tf.py_function 。
注意:tf.numpy_function 操作具有以下已知限制:
函数体(即
func)不会在tf.SavedModel中序列化。因此,如果您需要序列化模型并在不同的环境中恢复它,则不应使用此函数。该操作必须在与调用
tf.numpy_function()的 Python 程序相同的地址空间中运行。如果您使用分布式 TensorFlow,则必须在与调用tf.numpy_function的程序相同的进程中运行tf.distribute.Server,您必须将创建的操作固定到该服务器中的设备(例如,使用with tf.device():)。由于该函数采用 numpy 数组,因此您不能通过 numpy_function 获取渐变。如果您需要可区分的东西,请考虑使用 tf.py_function。
结果函数被假定为有状态的并且永远不会被优化。
相关用法
- Python tf.nn.embedding_lookup_sparse用法及代码示例
- Python tf.nest.is_nested用法及代码示例
- Python tf.nn.RNNCellResidualWrapper.set_weights用法及代码示例
- Python tf.nn.dropout用法及代码示例
- Python tf.nest.assert_same_structure用法及代码示例
- Python tf.nn.gelu用法及代码示例
- Python tf.nn.RNNCellDeviceWrapper.set_weights用法及代码示例
- Python tf.no_gradient用法及代码示例
- Python tf.nn.embedding_lookup用法及代码示例
- Python tf.nn.RNNCellDeviceWrapper.get_weights用法及代码示例
- Python tf.nn.local_response_normalization用法及代码示例
- Python tf.nn.scale_regularization_loss用法及代码示例
- Python tf.nn.RNNCellResidualWrapper.add_loss用法及代码示例
- Python tf.nn.max_pool用法及代码示例
- Python tf.nn.RNNCellDropoutWrapper.set_weights用法及代码示例
- Python tf.nest.map_structure用法及代码示例
- Python tf.nn.l2_loss用法及代码示例
- Python tf.nn.log_softmax用法及代码示例
- Python tf.nn.weighted_cross_entropy_with_logits用法及代码示例
- Python tf.name_scope用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.numpy_function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
