tensorflow条件语句-tf.cond

tf.cond
 
tf.cond(
    pred,
    true_fn=None,
    false_fn=None,
    strict=False,
    name=None,
    fn1=None,
    fn2=None
)

如果谓词pred是真的返回true_fn(),否则返回false_fn()。

有些参数将过时,在未来版本将被移除,指令更新:fn1/fn2 不支持 true_fn/false_fn参数。

true_fn 和 false_fn 都返回一个输出tensors。true_fn 和 false_fn 必须有相同的非零数和类型输出。

条件执行仅用于在true_fn 和false_fn定义的操作。


#!/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(11)
y = tf.constant(22)

z = tf.multiply(x, y)
result1 = tf.cond(x > y, lambda: tf.add(x, y), lambda: tf.square(y))
result2 = tf.cond(x < y, lambda: tf.add(x, y), lambda: tf.square(y))

init_op = tf.global_variables_initializer()
sess=tf.Session()
with sess: 
    sess.run(init_op)
    print sess.run(result1)
    print sess.run(result2)

484
33
result2:当x<y,tf.add
result1:当x>y:tf.add

这种行为偶尔也会让一些期望语义更懒的用户感到惊讶。

条件调用 true_fn和 false_fn 仅一次(包括对cond的调用,不在Session.run()期间),条件将true_fn和false_fn调用期间创建的计算图片断和一些附加的计算图结点缝合在一起,以确保根据pred的值执行正确的分支。

tf.cond 支持在 tensorflow.python.util.nest.实现的嵌套结构。true_fn和false_fn必须返回相同的(可能是嵌套的)值结构,这些结构包括lists、tuples、命名元组。单例列表和元组形成了唯一的例外:当由true_fn和false_fn返回时,它们被隐式地解包为单个值。通过传递strict=True,禁用此行为。

参数:

pred: 一个标量决定了返回结果是true_fn 还是 false_fn。
true_fn: 当pred为真时,调用。
false_fn: 当pred为假时,调用。
strict: 一个boolen类型。
name: 返回tensors的可选名字前缀。
返回:

返回

通过调用true_fn或ffalse_fn 返回的张量。如果回调函数返回单列表,则从列表中提取元素。

Raises:

TypeError: true_fn或false_fn 不能调用
ValueError:true_fn和false_fn 不能返回相同数量的张量,或者返回不同类型的张量。

#!/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(2)
y = tf.constant(5)
def f1(): 
    return tf.multiply(x, 17)
def f2(): 
    return tf.add(y, 23)
z = tf.cond(tf.less(x, y), f1, f2)

sess=tf.Session()
with sess: 
    print sess.run(z)

34

猜你喜欢

转载自blog.51cto.com/13959448/2333009
今日推荐