如果谓词 pred 为真,则返回 true_fn() 否则 false_fn() 。
用法
tf.cond(
pred, true_fn=None, false_fn=None, name=None
)参数
-
pred一个标量,确定是否返回true_fn或false_fn的结果。 -
true_fn如果 pred 为真,则要执行的调用。 -
false_fn如果 pred 为假,则要执行的可调用。 -
name返回的张量的可选名称前缀。
返回
-
调用
true_fn或false_fn返回的张量。如果可调用对象返回单例列表,则从列表中提取元素。
抛出
-
TypeError如果true_fn或false_fn不可调用。 -
ValueError如果true_fn和false_fn不返回相同数量的张量,或者返回不同类型的张量。
true_fn 和 false_fn 都返回输出张量的列表。 true_fn 和 false_fn 必须具有相同的非零数量和类型的输出。
警告:无论在运行时选择哪个分支,在 true_fn 和 false_fn 之外创建的任何张量或操作都将被执行。
尽管这种行为与 TensorFlow 的数据流模型是一致的,但它经常让那些期待更惰性语义的用户感到惊讶。考虑以下简单程序:
z = tf.multiply(a, b)
result = tf.cond(x < y, lambda:tf.add(x, z), lambda:tf.square(y))
如果 x < y ,将执行 tf.add 操作,而不会执行 tf.square 操作。由于cond 的至少一个分支需要z,因此始终无条件地执行tf.multiply 操作。
注意cond调用true_fn和false_fn 恰好一次(在调用内cond, 并且在Session.run())。cond将在创建过程中创建的图形片段缝合在一起true_fn和false_fn调用一些额外的图节点,以确保根据值执行正确的分支pred.
tf.cond 支持在 tensorflow.python.util.nest 中实现的嵌套结构。 true_fn 和 false_fn 都必须返回相同的(可能是嵌套的)列表、元组和/或命名元组的值结构。单例列表和元组是唯一的异常:当 true_fn 和/或 false_fn 返回时,它们被隐式解包为单个值。
注意:"directly" 使用在其外部的 cond 分支内创建的张量是非法的,例如通过在 python 状态中存储对分支张量的引用。如果您需要使用在分支函数中创建的张量,则应将其作为分支函数的输出返回,并改用 tf.cond 的输出。
例子:
x = tf.constant(2)
y = tf.constant(5)
def f1():return tf.multiply(x, 17)
def f2():return tf.add(y, 23)
r = tf.cond(tf.less(x, y), f1, f2)
# r is set to f1().
# Operations in f2 (e.g., tf.add) are not executed.
相关用法
- Python tf.config.list_logical_devices用法及代码示例
- Python tf.config.experimental.get_memory_usage用法及代码示例
- Python tf.config.list_physical_devices用法及代码示例
- Python tf.config.get_logical_device_configuration用法及代码示例
- Python tf.config.experimental.get_memory_info用法及代码示例
- Python tf.concat用法及代码示例
- Python tf.config.run_functions_eagerly用法及代码示例
- Python tf.config.experimental.enable_tensor_float_32_execution用法及代码示例
- Python tf.convert_to_tensor用法及代码示例
- Python tf.config.experimental_connect_to_cluster用法及代码示例
- Python tf.config.experimental.set_memory_growth用法及代码示例
- Python tf.config.experimental_connect_to_host用法及代码示例
- Python tf.config.set_visible_devices用法及代码示例
- Python tf.config.set_logical_device_configuration用法及代码示例
- Python tf.config.experimental.enable_op_determinism用法及代码示例
- Python tf.constant_initializer.from_config用法及代码示例
- Python tf.config.get_visible_devices用法及代码示例
- Python tf.config.experimental.get_device_details用法及代码示例
- Python tf.config.experimental.ClusterDeviceFilters用法及代码示例
- Python tf.constant用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.cond。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
