- tf.case
- tf.case(
- ? ? pred_fn_pairs,
- ? ? default=None,
- ? ? exclusive=False,
- ? ? strict=False,
- ? ? name='case'
- )
创建 case 操作
pred_fn_pairs 参数是大小为 N 的字典或 pairs 的列表. 每对包含一个布尔标量 tensor 和一个 python 可调用函数项, 当条件为 True 将返回对应的函数项创建的 tensors. 在 pred_fn_pairs 对中的所有调用子以及默认值 (如果提供的话) 都应该返回相同数量和类型的张量.
如果 exclusive==True, 则计算所有的谓词, 如果多个谓词计算为 True, 则引发异常. 如果 exclusive==False, 则执行在求值为 True 的第一个谓词处停止, 并且立即返回由相应函数生成的张量(tensors). 如果没有一个谓词评估为 true, 则此操作返回默认生成的张量.
tf.case 支持在 tensorflow.python.util.nest 中实现的嵌套结构. 所有的调用都必须返回相同的 (可能嵌套的) 列表, 元组和 / 或命名元组的值结构. 单例列表和元组形成了唯一的例外: 当由可调用程序返回时, 它们被隐式地解包为单个值. 通过通过传递 strict=True 禁用此行为.
如果无序字典在 pred_fn_pairs 使用, 则条件测试的顺序不能保证. 不管怎么样, 顺序保证是确定的, 以便在条件分支中变量按固定顺序被创建.
- #!/usr/bin/env python2
- # -*- coding: utf-8 -*-
- """
- Created on Mon Aug 27 11:16:32 2018
- @author: myhaspl
- """
- import tensorflow as tf
- x = tf.constant(7)
- y = tf.constant(27)
- f1 = lambda: tf.constant(17)
- f2 = lambda: tf.constant(23)
- r = tf.case([(tf.Less(x, y), f1)], default=f2)
- #if (x <y) return 17;
- #else return 23;
- sess=tf.Session()
- with sess:
- print sess.run(r)
- 17
- Example 2:
- #!/usr/bin/env python2
- # -*- coding: utf-8 -*-
- """
- Created on Mon Aug 27 11:16:32 2018
- @author: myhaspl
- """
- import tensorflow as tf
- x = tf.constant(7)
- y = tf.constant(27)
- z = tf.constant(21)
- 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);
- sess=tf.Session()
- with sess:
- print sess.run(r)
相当于:
- if (x < y && x> z) raise OpError("Only one predicate may evaluate true");
- if (x <y) return 17;
- else if (x> z) return 23;
- else return -1;
参数:
pred_fn_pairs: 字典或 pairs 的列表(由 boolean 标量和可调用函数返回张量列表)
default: 默认返回 tensors 列表
exclusive: 如果为 True 表示仅最多一个谓语为 True?
strict: boolean 打开或关闭'strict' 模式
name: 操作的名字(可选)
返回:
第一个谓词为 True 时执行返回的 tensors, 如果没有谓词为 True, 则返回 default
Raises:
TypeError: pred_fn_pairs? 不是一个列表或字典
TypeError: pred_fn_pairs 是一个列表, 但不包括 2 个元素的元组?
TypeError: fns[i]? 不是任何 i 的调用, 或 default 不是可调用的
来源: http://www.bubuko.com/infodetail-2890754.html