Defining Operations in TensorFlow
Learn about the different operations in TensorFlow.
An operation in TensorFlow takes one or more inputs and produces one or more outputs. If we take a look at the TensorFlow API, we’ll see that TensorFlow has a massive collection of operations available. Here, we’ll take a look at a selected few of the myriad TensorFlow operations.
Comparison operations
Comparison operations are useful for comparing two tensors. The following code example includes a few useful comparison operations.
To understand the working of these operations, let’s consider two example tensors, x
and y
:
# Let's assume the following values for x and y# x (2-D tensor) => [[1,2],[3,4]]# y (2-D tensor) => [[4,3],[3,2]]x = tf.constant([[1, 2], [3, 4]], dtype = tf.int32)y = tf.constant([[4, 3], [3, 2]], dtype = tf.int32)# Checks if two tensors are equal element-wise and returns a boolean tensor# x_equal_y => [[False,False],[True,False]]x_equal_y = tf.equal(x, y, name = None)# Checks if x is less than y element-wise and returns a boolean tensor# x_less_y => [[True,True],[False,False]]x_less_y = tf.less(x, y, name = None)# Checks if x is greater or equal than y element-wise and#returns a boolean tensor# x_great_equal_y => [[False,False],[True,True]]x_great_equal_y = tf.greater_equal(x, y, name = None)# Selects elements from x and y depending on whether,#the condition is satisfied (select elements from x)#or the condition failed (select elements from y)condition = tf.constant([[True, False], [True, False]], dtype = tf.bool)# x_cond_y => [[1,3],[3,2]]x_cond_y = tf.where(condition, x, y, name = None)print('Is X == Y (element-wise)?')print(x_equal_y.numpy())print('\nIs X < Y (element-wise)?')print(x_less_y.numpy())print('\nIs X >= Y (element-wise)?')print(x_great_equal_y.numpy())print('\nX or Y depending on the condition (element-wise)')print(x_cond_y.numpy())
We have two tensors, x
and y
, in the code above, which we used to compare element-wise. First, we check if these are equal or not (line 9), then we check if x
is less than y
(line 13), and finally, if x
is greater than or equal to y
(line 17). We select elements from tensors x
and y
based on the corresponding elements of the boolean tensor condition
. If the condition is True
, it selects the element from x
; otherwise, it selects the element from y
(lines 20–23).
In the figure below, we show the symbols of the comparison operators:
Mathematical operations
TensorFlow allows ...