在TensorFlow中,tf.cond()类似于c语言中的if…else…,用来控制数据流向,但是仅仅类似而已,其中差别还是挺大的。关于tf.cond()函数的具体操作,我参考了tf的说明文档。
format:tf.cond(pred, fn1, fn2, name=None)
Return :either fn1() or fn2() based on the boolean predicate pred.(注意这里,也就是说’fnq’和‘fn2’是两个函数)
arguments:fn1 and fn2 both return lists of output tensors. fn1 and fn2 must have the same non-zero number and type of outputs('fnq’和‘fn2’返回的是非零的且类型相同的输出)
官方例子:
z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
上面例子执行这样的操作,如果x<y则result这个操作是tf.add(x,z),反之则是tf.square(y)。这一点上,确实很像逻辑控制中的if…else…,但是官方说明里也提到
Since z is needed for at least one branch of the cond,branch of the cond, the tf.mul operation is always executed, unconditionally.
因为z在cond函数中的至少一个分支被用到,所以
z = tf.multiply(a, b)
总是被无条件执行
原文链接:https://blog.youkuaiyun.com/m0_37041325/article/details/76908660
1万+

被折叠的 条评论
为什么被折叠?



