Python – tensorflow.cond()
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
cond( ) 如果谓词 pred 为真,则返回 true_fn(),否则返回 false_fn()。
Syntax: tensorflow.cond( pred, true_fn, false_fn, name )
Parameters:
- pred: It is a scalar which determines the callable to return
- true_fn(optional): It is returned when pred is true.
- false_fn(optional): It is returned when pred is false.
- name(optional): It defines the name for the operation.
Return: It returns the result evaluated by callable.
示例 1:
Python3
# 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)
Python3
# 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:
Python3
# 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)