Math operation in TensorFlow 2.x


 Math operation in TensorFlow 2.x

If you have ever use TensorFlow 1.x then you remember that you need to initialize the something called session to execute the command but in tensorflow2.x they remove all these unnecessary things and make your work easier let see how it works

Suppose i have to two matrix so you can simply write this code : 
import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]])
b = tf.constant([[5,6,7],[7,8,9]])
c = tf.add(a,b)
print(c.numpy())  # if you remove numpy() you will also see data shape and data type in output

Output : [[6 8 10]
               [11 13 15]]

Similarly, if you want to multiply two number all you need to do is

import tensorflow as tf
x = tf.constant(5)
y =  tf.constant(7)
z = tf.multiply(x,y)
print(z) #notice in output you see shape and dtype it is because we don't add .numpy() here)

Output : tf.Tensor(35, shape=(), dtype=int32)

But in the case of matrix multiplication rule is a little bit different

import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6],[6,8,9]])
b = tf.constant([[5,6,7],[7,8,9],[5,8,9]])
c = tf.matmul(a,b)

Output : [[ 34  46  52]
              [ 85 112 127]
              [131 172 195]]

Similarly, you can do a lot of mathematical operation in Tensorflow

if you are wondering how the code looks like in TensorFlow 1.x here is the example

import tensorflow.compat.v1 as tf   # first two line only need to add if you are using tensorflow2.x 
tf.disable_v2_behavior()  # else just write import tensorfow as tf
x = tf.constant(5)
y =  tf.constant(7)
sess = tf.Session() # this sess if remove in tensorflow 2.x
z = tf.multiply(x,y)


Post a Comment