/    /  TensorFlow Mathematics

TensorFlow Mathematics

Deep learning and Machine learning applications are basically mathematical, and TensorFlow provides a efficient way for performing mathematical operations on tensors. Each and Every way is represented by a function of the tf module, and each function returns a tensor.Following are some mathematical functions provided by tensorflow.

 

Basic Math Operations

FunctionDescription
add(a, b, name=None)Adds two tensors
subtract(a, b, name=None)Subtracts two tensors
multiply(a, b, name=None)Multiplies two tensors
divide(a, b, name=None)Divides the elements of two tensors
div(a, b, name=None)Divides the elements of two tensors
add_n(inputs, name=None)Adds multiple tensors
scalar_mul(scalar, a)Scales a tensor by a scalar value
mod(a, b, name=None)Performs the modulo operation
abs(a, name=None)Computes the absolute value
negative(a, name=None)Negates the tensor’s elements
sign(a, name=None)Extracts the signs of the tensor’s element
reciprocal(a, name=None)Computes the reciprocals

 

The first four functions perform element-wise arithmetic.

X = tf.constant([2., 2., 2.])



Y = tf.constant([4., 4., 4.])



sum = tf.add(X, Y)                 # [ 6. 6. 6. ]



diff = tf.subtract(X, Y)           # [ 2. 2. 2. ]



prod = tf.multiply(X,Y)           # [ 8. 8. 8. ]



quot = tf.divide(X,Y)             # [ 2 2 2 ]

 

Applications can perform identical operations by using regular Python operators, such as +, -, *, /, and //. For example, the following two lines of code create the same tensor:

total = tf.add(X,Y)               # [ 6. 6. 6. ]



total2 = X + Y                     # [ 6. 6. 6. ]

 

When operating on floating-point values, div and divide produce the same result. But for integer division, divide returns a floating-point result, and divreturns an integer result. The following code demonstrates the difference between them:

a = tf.constant([3, 3, 3])



b = tf.constant([2, 2, 2])



div1 = tf.divide(a, b)             # [ 1.5 1.5 1.5 ]



div2 = a / b                       # [ 1.5 1.5 1.5 ]



div3 = tf.div(a, b)                # [ 1 1 1 ]



div4 = a // b                      # [ 1 1 1 ]

 

The  operator “ / ” and  “div” function both do element-wise division. On the other hand, the divide function do Python-style division.