Python TensorFlow ``tensorflow.cond()`` 方法详解与实例


发布日期 : 2019-04-11 07:18:37 UTC

访问量: 10 次浏览

Python – tensorflow.cond()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

cond()
如果谓词pred为真,则返回 true\_fn() ,否则就返回 false\_fn()

语法:
tensorflow.cond( pred, true_fn, false_fn, name )

参数:

  • pred:它是一个标量,决定了要返回的可调用对象。
  • true\_fn(可选):当pred为真时,它被返回。
  • false\_fn(可选):当pred为false时,它被返回。
  • name(可选):它定义了该操作的名称。

返回:
它返回由可调用程序评估的结果。

示例 1:

# Importing the library
import tensorflow as tf

# Initializing the input
x = 5
y = 10


# Printing the input
print('x: ', x)
print('y: ', y)

# Calculating result
res = tf.cond(x < y, lambda: tf.add(x, y), lambda: tf.square(y))

# Printing the result
print('Result: ', res)

输出:

x: 5
y: 10
Result: tf.Tensor(15, shape=(), dtype=int32)

示例 2:

# Importing the library
import tensorflow as tf

# Initializing the input
x = 5
y = 10


# Printing the input
print('x: ', x)
print('y: ', y)

# Calculating result
res = tf.cond(x > y, lambda: tf.add(x, y), lambda: tf.square(y))

# Printing the result
print('Result: ', res)

输出:

x: 5
y: 10
Result: tf.Tensor(100, shape=(), dtype=int32)