创建案例操作。
用法
tf.compat.v1.case(
pred_fn_pairs, default=None, exclusive=False, strict=False,
name='case'
)
参数
-
pred_fn_pairs
布尔标量张量和返回张量列表的可调用对象的字典或列表。 -
default
返回张量列表的可选可调用对象。 -
exclusive
如果最多允许一个谓词计算为True
,则为真。 -
strict
启用/禁用 'strict' 模式的布尔值;往上看。 -
name
此操作的名称(可选)。
返回
-
由谓词评估为 True 的第一对返回的张量,如果没有,则由
default
返回的张量。
抛出
-
TypeError
如果pred_fn_pairs
不是列表/字典。 -
TypeError
如果pred_fn_pairs
是一个列表但不包含 2 元组。 -
TypeError
如果fns[i]
对于任何 i 都不可调用,或者default
不可调用。
pred_fn_pairs
参数是大小为 N 的字典或对列表。每对包含一个布尔标量张量和一个 python 可调用函数,如果布尔值计算为 True,则创建要返回的张量。 default
是一个可调用的生成张量列表。 pred_fn_pairs
和 default
(如果提供)中的所有可调用对象都应返回相同数量和类型的张量。
如果 exclusive==True
,则评估所有谓词,如果多个谓词评估为 True
,则会引发异常。如果 exclusive==False
,则执行在第一个计算结果为 True 的谓词处停止,并立即返回相应函数生成的张量。如果没有任何谓词评估为 True,则此操作返回由 default
生成的张量。
tf.case
支持 tf.nest
中实现的嵌套结构。所有可调用对象必须返回相同的(可能是嵌套的)列表、元组和/或命名元组的值结构。单例列表和元组是唯一的异常:当由可调用对象返回时,它们被隐式解包为单个值。通过传递 strict=True
禁用此行为。
如果 pred_fn_pairs
使用无序字典,则无法保证条件测试的顺序。但是,顺序保证是确定性的,因此在条件分支中创建的变量在运行中以固定顺序创建。
示例 1:
伪代码:
if (x < y) return 17;
else return 23;
表达式:
f1 = lambda:tf.constant(17)
f2 = lambda:tf.constant(23)
r = tf.case([(tf.less(x, y), f1)], default=f2)
示例 2:
伪代码:
if (x < y && x > z) raise OpError("Only one predicate may evaluate to True");
if (x < y) return 17;
else if (x > z) return 23;
else return -1;
表达式:
def f1():return tf.constant(17)
def f2():return tf.constant(23)
def f3():return tf.constant(-1)
r = tf.case({tf.less(x, y):f1, tf.greater(x, z):f2},
default=f3, exclusive=True)
eager模式兼容性
当 exclusive=False
时,Eager 模式不支持无序字典。改为使用元组列表。
相关用法
- Python tf.compat.v1.confusion_matrix用法及代码示例
- Python tf.compat.v1.convert_to_tensor用法及代码示例
- Python tf.compat.v1.count_nonzero用法及代码示例
- Python tf.compat.v1.cond用法及代码示例
- Python tf.compat.v1.constant用法及代码示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代码示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代码示例
- Python tf.compat.v1.data.TFRecordDataset.interleave用法及代码示例
- Python tf.compat.v1.distributions.Bernoulli.cross_entropy用法及代码示例
- Python tf.compat.v1.Variable.eval用法及代码示例
- Python tf.compat.v1.train.FtrlOptimizer.compute_gradients用法及代码示例
- Python tf.compat.v1.layers.conv3d用法及代码示例
- Python tf.compat.v1.strings.length用法及代码示例
- Python tf.compat.v1.data.Dataset.snapshot用法及代码示例
- Python tf.compat.v1.data.experimental.SqlDataset.reduce用法及代码示例
- Python tf.compat.v1.feature_column.categorical_column_with_vocabulary_file用法及代码示例
- Python tf.compat.v1.data.TextLineDataset.from_tensors用法及代码示例
- Python tf.compat.v1.variable_scope用法及代码示例
- Python tf.compat.v1.data.experimental.SqlDataset.as_numpy_iterator用法及代码示例
- Python tf.compat.v1.distributions.Bernoulli.covariance用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.compat.v1.case。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。